1
0

test.cc 436 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216
  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. #if __cplusplus >= 202002L
  28. inline std::string u8_to_string(const char8_t *s) {
  29. return std::string(reinterpret_cast<const char *>(s));
  30. }
  31. #define U8(x) u8_to_string(u8##x)
  32. #else
  33. #define U8(x) u8##x
  34. #endif
  35. #define SERVER_CERT_FILE "./cert.pem"
  36. #define SERVER_CERT2_FILE "./cert2.pem"
  37. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  38. #define CA_CERT_FILE "./ca-bundle.crt"
  39. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  40. #define CLIENT_CA_CERT_DIR "."
  41. #define CLIENT_CERT_FILE "./client.cert.pem"
  42. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  43. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  44. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  45. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  46. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  47. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  48. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  49. using namespace std;
  50. using namespace httplib;
  51. const char *HOST = "localhost";
  52. const int PORT = 1234;
  53. const string LONG_QUERY_VALUE = string(25000, '@');
  54. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  55. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  56. const string TOO_LONG_QUERY_URL =
  57. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  58. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  59. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  60. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  61. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  62. return file.name == key;
  63. });
  64. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  65. return *it;
  66. #else
  67. if (it != items.end()) { return *it; }
  68. throw std::runtime_error("invalid multipart form data name error");
  69. #endif
  70. }
  71. static void read_file(const std::string &path, std::string &out) {
  72. std::ifstream fs(path, std::ios_base::binary);
  73. if (!fs) throw std::runtime_error("File not found: " + path);
  74. fs.seekg(0, std::ios_base::end);
  75. auto size = fs.tellg();
  76. fs.seekg(0);
  77. out.resize(static_cast<size_t>(size));
  78. fs.read(&out[0], static_cast<std::streamsize>(size));
  79. }
  80. void performance_test(const char *host) {
  81. Server svr;
  82. svr.Get("/benchmark", [&](const Request & /*req*/, Response &res) {
  83. res.set_content("Benchmark Response", "text/plain");
  84. });
  85. auto listen_thread = std::thread([&]() { svr.listen(host, PORT); });
  86. auto se = detail::scope_exit([&] {
  87. svr.stop();
  88. listen_thread.join();
  89. ASSERT_FALSE(svr.is_running());
  90. });
  91. svr.wait_until_ready();
  92. Client cli(host, PORT);
  93. // Warm-up request to establish connection and resolve DNS
  94. auto warmup_res = cli.Get("/benchmark");
  95. ASSERT_TRUE(warmup_res); // Ensure server is responding correctly
  96. // Run multiple trials and collect timings
  97. const int num_trials = 20;
  98. std::vector<int64_t> timings;
  99. timings.reserve(num_trials);
  100. for (int i = 0; i < num_trials; i++) {
  101. auto start = std::chrono::high_resolution_clock::now();
  102. auto res = cli.Get("/benchmark");
  103. auto end = std::chrono::high_resolution_clock::now();
  104. auto elapsed =
  105. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  106. .count();
  107. // Assertions after timing measurement to avoid overhead
  108. ASSERT_TRUE(res);
  109. EXPECT_EQ(StatusCode::OK_200, res->status);
  110. timings.push_back(elapsed);
  111. }
  112. // Calculate 25th percentile (lower quartile)
  113. std::sort(timings.begin(), timings.end());
  114. auto p25 = timings[num_trials / 4];
  115. // Format timings for output
  116. std::ostringstream timings_str;
  117. timings_str << "[";
  118. for (size_t i = 0; i < timings.size(); i++) {
  119. if (i > 0) timings_str << ", ";
  120. timings_str << timings[i];
  121. }
  122. timings_str << "]";
  123. // Localhost HTTP GET should be fast even in CI environments
  124. EXPECT_LE(p25, 5) << "25th percentile performance is too slow: " << p25
  125. << "ms (Issue #1777). Timings: " << timings_str.str();
  126. }
  127. TEST(BenchmarkTest, localhost) { performance_test("localhost"); }
  128. TEST(BenchmarkTest, v6) { performance_test("::1"); }
  129. class UnixSocketTest : public ::testing::Test {
  130. protected:
  131. void TearDown() override { std::remove(pathname_.c_str()); }
  132. void client_GET(const std::string &addr) {
  133. httplib::Client cli{addr};
  134. cli.set_address_family(AF_UNIX);
  135. ASSERT_TRUE(cli.is_valid());
  136. const auto &result = cli.Get(pattern_);
  137. ASSERT_TRUE(result) << "error: " << result.error();
  138. const auto &resp = result.value();
  139. EXPECT_EQ(resp.status, StatusCode::OK_200);
  140. EXPECT_EQ(resp.body, content_);
  141. }
  142. const std::string pathname_{"./httplib-server.sock"};
  143. const std::string pattern_{"/hi"};
  144. const std::string content_{"Hello World!"};
  145. };
  146. TEST_F(UnixSocketTest, pathname) {
  147. httplib::Server svr;
  148. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  149. res.set_content(content_, "text/plain");
  150. });
  151. std::thread t{[&] {
  152. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  153. }};
  154. auto se = detail::scope_exit([&] {
  155. svr.stop();
  156. t.join();
  157. ASSERT_FALSE(svr.is_running());
  158. });
  159. svr.wait_until_ready();
  160. ASSERT_TRUE(svr.is_running());
  161. client_GET(pathname_);
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_EQ(0, close(fds[1]));
  254. EXPECT_FALSE(s0.wait_writable());
  255. return true;
  256. });
  257. EXPECT_EQ(0, close(fds[0]));
  258. }
  259. TEST(SocketStream, wait_writable_INET) {
  260. sockaddr_in addr;
  261. memset(&addr, 0, sizeof(addr));
  262. addr.sin_family = AF_INET;
  263. addr.sin_port = htons(PORT + 1);
  264. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  265. int disconnected_svr_sock = -1;
  266. std::thread svr{[&] {
  267. const int s = socket(AF_INET, SOCK_STREAM, 0);
  268. ASSERT_LE(0, s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. EXPECT_FALSE(ss.wait_writable());
  292. return true;
  293. });
  294. ASSERT_EQ(0, close(disconnected_svr_sock));
  295. }
  296. #endif // #ifndef _WIN32
  297. TEST(ClientTest, MoveConstructible) {
  298. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  299. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  300. }
  301. TEST(ClientTest, MoveAssignable) {
  302. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  303. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  304. }
  305. #ifdef _WIN32
  306. TEST(StartupTest, WSAStartup) {
  307. WSADATA wsaData;
  308. int ret = WSAStartup(0x0002, &wsaData);
  309. ASSERT_EQ(0, ret);
  310. }
  311. #endif
  312. TEST(DecodePathTest, PercentCharacter) {
  313. EXPECT_EQ(
  314. decode_path_component(
  315. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  316. U8("descrip=Gastos áéíóúñÑ 6"));
  317. }
  318. TEST(DecodePathTest, PercentCharacterNUL) {
  319. string expected;
  320. expected.push_back('x');
  321. expected.push_back('\0');
  322. expected.push_back('x');
  323. EXPECT_EQ(decode_path_component("x%00x"), expected);
  324. }
  325. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  326. string unescapedCharacters = "-_.!~*'()";
  327. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  328. }
  329. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  330. string reservedCharacters = ";,/?:@&=+$";
  331. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  332. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  333. }
  334. TEST(ClientQueryOrder, PreserveOrder) {
  335. // This test reproduces Issue #2259: client may reorder query parameters
  336. // when sending a GET request. The expected behavior is that the client
  337. // preserves the original query string order when the caller supplied it
  338. // as part of the path.
  339. Server svr;
  340. svr.Get("/", [&](const Request &req, Response &res) {
  341. // Echo back the raw target so the test can assert ordering
  342. res.set_content(req.target, "text/plain");
  343. });
  344. std::thread t{[&] { svr.listen(HOST, PORT); }};
  345. auto se = detail::scope_exit([&] {
  346. svr.stop();
  347. t.join();
  348. ASSERT_FALSE(svr.is_running());
  349. });
  350. svr.wait_until_ready();
  351. Client cli(HOST, PORT);
  352. ASSERT_TRUE(cli.is_valid());
  353. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  354. auto res = cli.Get(original);
  355. ASSERT_TRUE(res);
  356. // Expect the echoed target to exactly match the original path (order
  357. // preserved)
  358. EXPECT_EQ(res->body, original);
  359. }
  360. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  361. string chineseCharacters = U8("中国語");
  362. string russianCharacters = U8("дом");
  363. string brazilianCharacters = U8("óculos");
  364. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  365. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  366. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  367. "%D0%B4%D0%BE%D0%BC");
  368. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  369. }
  370. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  371. string unescapedCharacters = "-_.!~*'()";
  372. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  373. }
  374. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  375. string reservedCharacters = ";,/?:@&=+$";
  376. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  377. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  378. }
  379. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  380. string chineseCharacters = U8("中国語");
  381. string russianCharacters = U8("дом");
  382. string brazilianCharacters = U8("óculos");
  383. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  384. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  385. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  386. "%D0%B4%D0%BE%D0%BC");
  387. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  388. }
  389. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  390. // Issue #2082 use case: encoding path component with ampersand
  391. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  392. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  393. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  394. }
  395. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  396. string unescapedCharacters = "-_.!~*'()";
  397. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  398. }
  399. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  400. string reservedCharacters = ";,/?:@&=+$#";
  401. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  402. }
  403. TEST(EncodeUriTest, TestUTF8Characters) {
  404. string chineseCharacters = U8("中国語");
  405. string russianCharacters = U8("дом");
  406. string brazilianCharacters = U8("óculos");
  407. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  408. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  409. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  410. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  411. }
  412. TEST(EncodeUriTest, TestCompleteUri) {
  413. string uri =
  414. "https://example.com/path/to/resource?query=value&param=test#fragment";
  415. EXPECT_EQ(
  416. httplib::encode_uri(uri),
  417. "https://example.com/path/to/resource?query=value&param=test#fragment");
  418. }
  419. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  420. string uri =
  421. "https://example.com/path with spaces/file name.html?q=hello world";
  422. EXPECT_EQ(httplib::encode_uri(uri),
  423. "https://example.com/path%20with%20spaces/"
  424. "file%20name.html?q=hello%20world");
  425. }
  426. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  427. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  428. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  429. }
  430. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  431. string unescapedCharacters = "-_.!~*'()";
  432. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  433. }
  434. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  435. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  436. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  437. string encodedBrazilian = "%C3%B3culos";
  438. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  439. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  440. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  441. }
  442. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  443. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  444. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  445. "Piri Tommy Villiers - on & on");
  446. }
  447. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  448. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  449. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  450. }
  451. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  452. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  453. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  454. }
  455. TEST(DecodeUriTest, TestUTF8Characters) {
  456. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  457. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  458. string encodedBrazilian = "%C3%B3culos";
  459. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  460. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  461. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  462. }
  463. TEST(DecodeUriTest, TestCompleteUri) {
  464. string encodedUri = "https://example.com/path%20with%20spaces/"
  465. "file%20name.html?q=hello%20world";
  466. EXPECT_EQ(
  467. httplib::decode_uri(encodedUri),
  468. "https://example.com/path with spaces/file name.html?q=hello world");
  469. }
  470. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  471. string original =
  472. "https://example.com/path with spaces/file name.html?q=hello world";
  473. string encoded = httplib::encode_uri(original);
  474. string decoded = httplib::decode_uri(encoded);
  475. EXPECT_EQ(decoded, original);
  476. }
  477. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  478. string original = "Piri Tommy Villiers - on & on";
  479. string encoded = httplib::encode_uri_component(original);
  480. string decoded = httplib::decode_uri_component(encoded);
  481. EXPECT_EQ(decoded, original);
  482. }
  483. TEST(TrimTests, TrimStringTests) {
  484. EXPECT_EQ("abc", detail::trim_copy("abc"));
  485. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  486. EXPECT_TRUE(detail::trim_copy("").empty());
  487. }
  488. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  489. // Simple case without quality values
  490. std::vector<std::string> result1;
  491. EXPECT_TRUE(detail::parse_accept_header(
  492. "text/html,application/json,text/plain", result1));
  493. EXPECT_EQ(result1.size(), 3U);
  494. EXPECT_EQ(result1[0], "text/html");
  495. EXPECT_EQ(result1[1], "application/json");
  496. EXPECT_EQ(result1[2], "text/plain");
  497. // With quality values
  498. std::vector<std::string> result2;
  499. EXPECT_TRUE(detail::parse_accept_header(
  500. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  501. EXPECT_EQ(result2.size(), 3U);
  502. EXPECT_EQ(result2[0], "application/json"); // highest q value
  503. EXPECT_EQ(result2[1], "text/html");
  504. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  505. }
  506. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  507. // Mixed with and without quality values
  508. std::vector<std::string> result;
  509. EXPECT_TRUE(detail::parse_accept_header(
  510. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  511. EXPECT_EQ(result.size(), 3U);
  512. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  513. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  514. EXPECT_EQ(result[2], "application/json"); // q=0.5
  515. }
  516. TEST(ParseAcceptHeaderTest, EdgeCases) {
  517. // Empty header
  518. std::vector<std::string> empty_result;
  519. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  520. EXPECT_TRUE(empty_result.empty());
  521. // Single type
  522. std::vector<std::string> single_result;
  523. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  524. EXPECT_EQ(single_result.size(), 1U);
  525. EXPECT_EQ(single_result[0], "application/json");
  526. // Wildcard types
  527. std::vector<std::string> wildcard_result;
  528. EXPECT_TRUE(detail::parse_accept_header(
  529. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  530. EXPECT_EQ(wildcard_result.size(), 3U);
  531. EXPECT_EQ(wildcard_result[0], "application/json");
  532. EXPECT_EQ(wildcard_result[1], "text/*");
  533. EXPECT_EQ(wildcard_result[2], "*/*");
  534. }
  535. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  536. // Common browser Accept header
  537. std::vector<std::string> browser_result;
  538. EXPECT_TRUE(
  539. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  540. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  541. browser_result));
  542. EXPECT_EQ(browser_result.size(), 6U);
  543. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  544. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  545. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  546. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  547. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  548. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  549. // API client header
  550. std::vector<std::string> api_result;
  551. EXPECT_TRUE(detail::parse_accept_header(
  552. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  553. api_result));
  554. EXPECT_EQ(api_result.size(), 3U);
  555. EXPECT_EQ(api_result[0], "application/json");
  556. EXPECT_EQ(api_result[1], "application/xml");
  557. EXPECT_EQ(api_result[2], "text/plain");
  558. }
  559. TEST(ParseAcceptHeaderTest, SpecialCases) {
  560. // Quality value with 3 decimal places
  561. std::vector<std::string> decimal_result;
  562. EXPECT_TRUE(detail::parse_accept_header(
  563. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  564. EXPECT_EQ(decimal_result.size(), 2U);
  565. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  566. EXPECT_EQ(decimal_result[1], "text/html");
  567. // Zero quality (should still be included but with lowest priority)
  568. std::vector<std::string> zero_q_result;
  569. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  570. zero_q_result));
  571. EXPECT_EQ(zero_q_result.size(), 2U);
  572. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  573. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  574. // No spaces around commas
  575. std::vector<std::string> no_space_result;
  576. EXPECT_TRUE(detail::parse_accept_header(
  577. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  578. no_space_result));
  579. EXPECT_EQ(no_space_result.size(), 3U);
  580. EXPECT_EQ(no_space_result[0], "text/html");
  581. EXPECT_EQ(no_space_result[1], "application/json");
  582. EXPECT_EQ(no_space_result[2], "text/plain");
  583. }
  584. TEST(ParseAcceptHeaderTest, InvalidCases) {
  585. std::vector<std::string> result;
  586. // Invalid quality value (> 1.0)
  587. EXPECT_FALSE(
  588. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  589. // Invalid quality value (< 0.0)
  590. EXPECT_FALSE(
  591. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  592. // Invalid quality value (not a number)
  593. EXPECT_FALSE(detail::parse_accept_header(
  594. "text/html;q=invalid,application/json", result));
  595. // Empty quality value
  596. EXPECT_FALSE(
  597. detail::parse_accept_header("text/html;q=,application/json", result));
  598. // Invalid media type format (no slash and not wildcard)
  599. EXPECT_FALSE(
  600. detail::parse_accept_header("invalidtype,application/json", result));
  601. // Empty media type
  602. result.clear();
  603. EXPECT_FALSE(detail::parse_accept_header(",application/json", result));
  604. // Only commas
  605. result.clear();
  606. EXPECT_FALSE(detail::parse_accept_header(",,,", result));
  607. // Valid cases should still work
  608. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  609. EXPECT_EQ(result.size(), 1U);
  610. EXPECT_EQ(result[0], "*/*");
  611. EXPECT_TRUE(detail::parse_accept_header("*", result));
  612. EXPECT_EQ(result.size(), 1U);
  613. EXPECT_EQ(result[0], "*");
  614. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  615. EXPECT_EQ(result.size(), 1U);
  616. EXPECT_EQ(result[0], "text/*");
  617. }
  618. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  619. Server svr;
  620. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  621. EXPECT_EQ(req.accept_content_types.size(), 3U);
  622. EXPECT_EQ(req.accept_content_types[0], "application/json");
  623. EXPECT_EQ(req.accept_content_types[1], "text/html");
  624. EXPECT_EQ(req.accept_content_types[2], "*/*");
  625. res.set_content("ok", "text/plain");
  626. });
  627. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  628. EXPECT_TRUE(false);
  629. res.set_content("bad request", "text/plain");
  630. });
  631. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  632. auto se = detail::scope_exit([&] {
  633. svr.stop();
  634. listen_thread.join();
  635. ASSERT_FALSE(svr.is_running());
  636. });
  637. svr.wait_until_ready();
  638. Client cli("localhost", PORT);
  639. {
  640. auto res =
  641. cli.Get("/accept_ok",
  642. {{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  643. ASSERT_TRUE(res);
  644. EXPECT_EQ(StatusCode::OK_200, res->status);
  645. }
  646. {
  647. auto res = cli.Get("/accept_bad_request",
  648. {{"Accept", "text/html;q=abc,application/json"}});
  649. ASSERT_TRUE(res);
  650. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  651. }
  652. }
  653. TEST(DivideTest, DivideStringTests) {
  654. auto divide = [](const std::string &str, char d) {
  655. std::string lhs;
  656. std::string rhs;
  657. detail::divide(str, d,
  658. [&](const char *lhs_data, std::size_t lhs_size,
  659. const char *rhs_data, std::size_t rhs_size) {
  660. lhs.assign(lhs_data, lhs_size);
  661. rhs.assign(rhs_data, rhs_size);
  662. });
  663. return std::make_pair(std::move(lhs), std::move(rhs));
  664. };
  665. {
  666. const auto res = divide("", '=');
  667. EXPECT_EQ(res.first, "");
  668. EXPECT_EQ(res.second, "");
  669. }
  670. {
  671. const auto res = divide("=", '=');
  672. EXPECT_EQ(res.first, "");
  673. EXPECT_EQ(res.second, "");
  674. }
  675. {
  676. const auto res = divide(" ", '=');
  677. EXPECT_EQ(res.first, " ");
  678. EXPECT_EQ(res.second, "");
  679. }
  680. {
  681. const auto res = divide("a", '=');
  682. EXPECT_EQ(res.first, "a");
  683. EXPECT_EQ(res.second, "");
  684. }
  685. {
  686. const auto res = divide("a=", '=');
  687. EXPECT_EQ(res.first, "a");
  688. EXPECT_EQ(res.second, "");
  689. }
  690. {
  691. const auto res = divide("=b", '=');
  692. EXPECT_EQ(res.first, "");
  693. EXPECT_EQ(res.second, "b");
  694. }
  695. {
  696. const auto res = divide("a=b", '=');
  697. EXPECT_EQ(res.first, "a");
  698. EXPECT_EQ(res.second, "b");
  699. }
  700. {
  701. const auto res = divide("a=b=", '=');
  702. EXPECT_EQ(res.first, "a");
  703. EXPECT_EQ(res.second, "b=");
  704. }
  705. {
  706. const auto res = divide("a=b=c", '=');
  707. EXPECT_EQ(res.first, "a");
  708. EXPECT_EQ(res.second, "b=c");
  709. }
  710. }
  711. TEST(SplitTest, ParseQueryString) {
  712. string s = "key1=val1&key2=val2&key3=val3";
  713. Params dic;
  714. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  715. [&](const char *b, const char *e) {
  716. string key, val;
  717. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  718. if (key.empty()) {
  719. key.assign(b2, e2);
  720. } else {
  721. val.assign(b2, e2);
  722. }
  723. });
  724. dic.emplace(key, val);
  725. });
  726. EXPECT_EQ("val1", dic.find("key1")->second);
  727. EXPECT_EQ("val2", dic.find("key2")->second);
  728. EXPECT_EQ("val3", dic.find("key3")->second);
  729. }
  730. TEST(SplitTest, ParseInvalidQueryTests) {
  731. {
  732. string s = " ";
  733. Params dict;
  734. detail::parse_query_text(s, dict);
  735. EXPECT_TRUE(dict.empty());
  736. }
  737. {
  738. string s = " = =";
  739. Params dict;
  740. detail::parse_query_text(s, dict);
  741. EXPECT_TRUE(dict.empty());
  742. }
  743. }
  744. TEST(ParseQueryTest, ParseQueryString) {
  745. {
  746. std::string s = "key1=val1&key2=val2&key3=val3";
  747. Params dic;
  748. detail::parse_query_text(s, dic);
  749. EXPECT_EQ("val1", dic.find("key1")->second);
  750. EXPECT_EQ("val2", dic.find("key2")->second);
  751. EXPECT_EQ("val3", dic.find("key3")->second);
  752. }
  753. {
  754. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  755. Params dic;
  756. detail::parse_query_text(s, dic);
  757. EXPECT_EQ("", dic.find("key1")->second);
  758. EXPECT_EQ("val1", dic.find("key2")->second);
  759. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  760. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  761. }
  762. }
  763. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  764. Params dic;
  765. EXPECT_EQ(detail::params_to_query_str(dic), "");
  766. dic.emplace("key1", "val1");
  767. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  768. dic.emplace("key2", "val2");
  769. dic.emplace("key3", "val3");
  770. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  771. }
  772. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  773. string content_type = "multipart/form-data; boundary=something";
  774. string boundary;
  775. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  776. EXPECT_TRUE(ret);
  777. EXPECT_EQ(boundary, "something");
  778. }
  779. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  780. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  781. string boundary;
  782. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  783. EXPECT_TRUE(ret);
  784. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  785. }
  786. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  787. string content_type =
  788. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  789. string boundary;
  790. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  791. EXPECT_TRUE(ret);
  792. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  793. }
  794. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  795. string content_type =
  796. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  797. string boundary;
  798. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  799. EXPECT_TRUE(ret);
  800. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  801. }
  802. TEST(GetHeaderValueTest, DefaultValue) {
  803. Headers headers = {{"Dummy", "Dummy"}};
  804. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  805. EXPECT_STREQ("text/plain", val);
  806. }
  807. TEST(GetHeaderValueTest, DefaultValueInt) {
  808. Headers headers = {{"Dummy", "Dummy"}};
  809. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  810. EXPECT_EQ(100ull, val);
  811. }
  812. TEST(GetHeaderValueTest, RegularValue) {
  813. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  814. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  815. EXPECT_STREQ("text/html", val);
  816. }
  817. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  818. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  819. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  820. EXPECT_STREQ("text/html", val);
  821. }
  822. TEST(GetHeaderValueTest, SetContent) {
  823. Response res;
  824. res.set_content("html", "text/html");
  825. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  826. res.set_content("text", "text/plain");
  827. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  828. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  829. }
  830. TEST(GetHeaderValueTest, RegularValueInt) {
  831. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  832. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  833. EXPECT_EQ(100ull, val);
  834. }
  835. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  836. Headers headers = {{"Content-Length", "x"}};
  837. auto is_invalid_value = false;
  838. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  839. is_invalid_value);
  840. EXPECT_EQ(0ull, val);
  841. EXPECT_TRUE(is_invalid_value);
  842. }
  843. TEST(GetHeaderValueTest, Range) {
  844. {
  845. Headers headers = {make_range_header({{1, -1}})};
  846. auto val = detail::get_header_value(headers, "Range", 0, 0);
  847. EXPECT_STREQ("bytes=1-", val);
  848. }
  849. {
  850. Headers headers = {make_range_header({{-1, 1}})};
  851. auto val = detail::get_header_value(headers, "Range", 0, 0);
  852. EXPECT_STREQ("bytes=-1", val);
  853. }
  854. {
  855. Headers headers = {make_range_header({{1, 10}})};
  856. auto val = detail::get_header_value(headers, "Range", 0, 0);
  857. EXPECT_STREQ("bytes=1-10", val);
  858. }
  859. {
  860. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  861. auto val = detail::get_header_value(headers, "Range", 0, 0);
  862. EXPECT_STREQ("bytes=1-10, 100-", val);
  863. }
  864. {
  865. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  866. auto val = detail::get_header_value(headers, "Range", 0, 0);
  867. EXPECT_STREQ("bytes=1-10, 100-200", val);
  868. }
  869. {
  870. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  871. auto val = detail::get_header_value(headers, "Range", 0, 0);
  872. EXPECT_STREQ("bytes=0-0, -1", val);
  873. }
  874. }
  875. TEST(ParseHeaderValueTest, Range) {
  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(1u, ranges[0].first);
  882. EXPECT_EQ(-1, ranges[0].second);
  883. }
  884. {
  885. Ranges ranges;
  886. auto ret = detail::parse_range_header("bytes=-1", ranges);
  887. EXPECT_TRUE(ret);
  888. EXPECT_EQ(1u, ranges.size());
  889. EXPECT_EQ(-1, ranges[0].first);
  890. EXPECT_EQ(1u, ranges[0].second);
  891. }
  892. {
  893. Ranges ranges;
  894. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  895. EXPECT_TRUE(ret);
  896. EXPECT_EQ(1u, ranges.size());
  897. EXPECT_EQ(1u, ranges[0].first);
  898. EXPECT_EQ(10u, ranges[0].second);
  899. }
  900. {
  901. Ranges ranges;
  902. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  903. EXPECT_FALSE(ret);
  904. }
  905. {
  906. Ranges ranges;
  907. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  908. EXPECT_TRUE(ret);
  909. EXPECT_EQ(2u, ranges.size());
  910. EXPECT_EQ(1u, ranges[0].first);
  911. EXPECT_EQ(10u, ranges[0].second);
  912. EXPECT_EQ(100u, ranges[1].first);
  913. EXPECT_EQ(-1, ranges[1].second);
  914. }
  915. {
  916. Ranges ranges;
  917. auto ret =
  918. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  919. EXPECT_TRUE(ret);
  920. EXPECT_EQ(3u, ranges.size());
  921. EXPECT_EQ(1u, ranges[0].first);
  922. EXPECT_EQ(10u, ranges[0].second);
  923. EXPECT_EQ(100u, ranges[1].first);
  924. EXPECT_EQ(200u, ranges[1].second);
  925. EXPECT_EQ(300u, ranges[2].first);
  926. EXPECT_EQ(400u, ranges[2].second);
  927. }
  928. {
  929. Ranges ranges;
  930. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  931. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  932. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  933. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  934. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  935. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  936. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  937. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  938. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  939. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  940. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  941. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  942. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  943. EXPECT_TRUE(ranges.empty());
  944. }
  945. }
  946. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  947. Request req;
  948. req.set_header("Accept-Encoding", "gzip");
  949. Response res;
  950. res.set_header("Content-Type", "text/plain");
  951. auto ret = detail::encoding_type(req, res);
  952. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  953. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  954. #else
  955. EXPECT_TRUE(ret == detail::EncodingType::None);
  956. #endif
  957. }
  958. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  959. Request req;
  960. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  961. Response res;
  962. res.set_header("Content-Type", "text/plain");
  963. auto ret = detail::encoding_type(req, res);
  964. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  965. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  966. #elif CPPHTTPLIB_ZLIB_SUPPORT
  967. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  968. #elif CPPHTTPLIB_ZSTD_SUPPORT
  969. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  970. #else
  971. EXPECT_TRUE(ret == detail::EncodingType::None);
  972. #endif
  973. }
  974. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  975. Request req;
  976. req.set_header("Accept-Encoding",
  977. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  978. Response res;
  979. res.set_header("Content-Type", "text/plain");
  980. auto ret = detail::encoding_type(req, res);
  981. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  982. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  983. #elif CPPHTTPLIB_ZLIB_SUPPORT
  984. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  985. #elif CPPHTTPLIB_ZSTD_SUPPORT
  986. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  987. #else
  988. EXPECT_TRUE(ret == detail::EncodingType::None);
  989. #endif
  990. }
  991. TEST(BufferStreamTest, read) {
  992. detail::BufferStream strm1;
  993. Stream &strm = strm1;
  994. EXPECT_EQ(5, strm.write("hello"));
  995. char buf[512];
  996. EXPECT_EQ(2, strm.read(buf, 2));
  997. EXPECT_EQ('h', buf[0]);
  998. EXPECT_EQ('e', buf[1]);
  999. EXPECT_EQ(2, strm.read(buf, 2));
  1000. EXPECT_EQ('l', buf[0]);
  1001. EXPECT_EQ('l', buf[1]);
  1002. EXPECT_EQ(1, strm.read(buf, 1));
  1003. EXPECT_EQ('o', buf[0]);
  1004. EXPECT_EQ(0, strm.read(buf, 1));
  1005. }
  1006. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1007. auto host = "www.httpwatch.com";
  1008. auto ip = hosted_at(host);
  1009. EXPECT_EQ("23.96.13.243", ip);
  1010. std::vector<std::string> addrs;
  1011. hosted_at(host, addrs);
  1012. EXPECT_EQ(1u, addrs.size());
  1013. }
  1014. #if 0 // It depends on each test environment...
  1015. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1016. auto host = "www.youtube.com";
  1017. std::vector<std::string> addrs;
  1018. hosted_at(host, addrs);
  1019. EXPECT_EQ(20u, addrs.size());
  1020. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1021. EXPECT_TRUE(it != addrs.end());
  1022. }
  1023. #endif
  1024. class ChunkedEncodingTest : public ::testing::Test {
  1025. protected:
  1026. ChunkedEncodingTest()
  1027. : cli_(HOST, PORT)
  1028. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1029. ,
  1030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1031. #endif
  1032. {
  1033. cli_.set_connection_timeout(2);
  1034. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1035. cli_.enable_server_certificate_verification(false);
  1036. #endif
  1037. }
  1038. virtual void SetUp() {
  1039. read_file("./image.jpg", image_data_);
  1040. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1041. res.set_content("Hello World!", "text/plain");
  1042. });
  1043. svr_.Get(
  1044. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1045. res.set_chunked_content_provider(
  1046. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1047. size_t remaining = image_data_.size() - offset;
  1048. if (remaining == 0) {
  1049. sink.done();
  1050. } else {
  1051. constexpr size_t CHUNK_SIZE = 1024;
  1052. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1053. sink.write(&image_data_[offset], send_size);
  1054. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1055. }
  1056. return true;
  1057. });
  1058. });
  1059. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1060. svr_.wait_until_ready();
  1061. }
  1062. virtual void TearDown() {
  1063. svr_.stop();
  1064. if (!request_threads_.empty()) {
  1065. std::this_thread::sleep_for(std::chrono::seconds(1));
  1066. for (auto &t : request_threads_) {
  1067. t.join();
  1068. }
  1069. }
  1070. t_.join();
  1071. }
  1072. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1073. SSLClient cli_;
  1074. SSLServer svr_;
  1075. #else
  1076. Client cli_;
  1077. Server svr_;
  1078. #endif
  1079. thread t_;
  1080. std::vector<thread> request_threads_;
  1081. std::string image_data_;
  1082. };
  1083. TEST_F(ChunkedEncodingTest, NormalGet) {
  1084. auto res = cli_.Get("/chunked");
  1085. ASSERT_TRUE(res);
  1086. std::string out;
  1087. read_file("./image.jpg", out);
  1088. EXPECT_EQ(StatusCode::OK_200, res->status);
  1089. EXPECT_EQ(out, res->body);
  1090. }
  1091. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1092. std::string body;
  1093. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1094. body.append(data, data_length);
  1095. return true;
  1096. });
  1097. ASSERT_TRUE(res);
  1098. std::string out;
  1099. read_file("./image.jpg", out);
  1100. EXPECT_EQ(StatusCode::OK_200, res->status);
  1101. EXPECT_EQ(out, body);
  1102. }
  1103. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1104. std::string body;
  1105. auto res = cli_.Get(
  1106. "/chunked",
  1107. [&](const Response &response) {
  1108. EXPECT_EQ(StatusCode::OK_200, response.status);
  1109. return true;
  1110. },
  1111. [&](const char *data, size_t data_length) {
  1112. body.append(data, data_length);
  1113. return true;
  1114. });
  1115. ASSERT_TRUE(res);
  1116. std::string out;
  1117. read_file("./image.jpg", out);
  1118. EXPECT_EQ(StatusCode::OK_200, res->status);
  1119. EXPECT_EQ(out, body);
  1120. }
  1121. TEST(RangeTest, FromHTTPBin_Online) {
  1122. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1123. auto host = "httpcan.org";
  1124. auto path = std::string{"/range/32"};
  1125. #else
  1126. auto host = "nghttp2.org";
  1127. auto path = std::string{"/httpbin/range/32"};
  1128. #endif
  1129. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1130. auto port = 443;
  1131. SSLClient cli(host, port);
  1132. #else
  1133. auto port = 80;
  1134. Client cli(host, port);
  1135. #endif
  1136. cli.set_connection_timeout(5);
  1137. {
  1138. auto res = cli.Get(path);
  1139. ASSERT_TRUE(res);
  1140. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1141. EXPECT_EQ(StatusCode::OK_200, res->status);
  1142. }
  1143. {
  1144. Headers headers = {make_range_header({{1, -1}})};
  1145. auto res = cli.Get(path, headers);
  1146. ASSERT_TRUE(res);
  1147. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1148. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1149. }
  1150. {
  1151. Headers headers = {make_range_header({{1, 10}})};
  1152. auto res = cli.Get(path, headers);
  1153. ASSERT_TRUE(res);
  1154. EXPECT_EQ("bcdefghijk", res->body);
  1155. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1156. }
  1157. {
  1158. Headers headers = {make_range_header({{0, 31}})};
  1159. auto res = cli.Get(path, headers);
  1160. ASSERT_TRUE(res);
  1161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1162. EXPECT_EQ(StatusCode::OK_200, res->status);
  1163. }
  1164. {
  1165. Headers headers = {make_range_header({{0, -1}})};
  1166. auto res = cli.Get(path, headers);
  1167. ASSERT_TRUE(res);
  1168. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1169. EXPECT_EQ(StatusCode::OK_200, res->status);
  1170. }
  1171. {
  1172. Headers headers = {make_range_header({{0, 32}})};
  1173. auto res = cli.Get(path, headers);
  1174. ASSERT_TRUE(res);
  1175. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  1176. }
  1177. }
  1178. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  1179. auto host = "unresolvableaddress.local";
  1180. auto path = std::string{"/"};
  1181. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1182. auto port = 443;
  1183. SSLClient cli(host, port);
  1184. #else
  1185. auto port = 80;
  1186. Client cli(host, port);
  1187. #endif
  1188. cli.set_connection_timeout(1);
  1189. {
  1190. auto res = cli.Get(path);
  1191. ASSERT_FALSE(res);
  1192. }
  1193. std::this_thread::sleep_for(std::chrono::seconds(8));
  1194. }
  1195. TEST(ConnectionErrorTest, InvalidHost) {
  1196. auto host = "-abcde.com";
  1197. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1198. auto port = 443;
  1199. SSLClient cli(host, port);
  1200. #else
  1201. auto port = 80;
  1202. Client cli(host, port);
  1203. #endif
  1204. cli.set_connection_timeout(std::chrono::seconds(2));
  1205. auto res = cli.Get("/");
  1206. ASSERT_TRUE(!res);
  1207. EXPECT_EQ(Error::Connection, res.error());
  1208. }
  1209. TEST(ConnectionErrorTest, InvalidHost2) {
  1210. auto host = "httpcan.org/";
  1211. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1212. SSLClient cli(host);
  1213. #else
  1214. Client cli(host);
  1215. #endif
  1216. cli.set_connection_timeout(std::chrono::seconds(2));
  1217. auto res = cli.Get("/");
  1218. ASSERT_TRUE(!res);
  1219. EXPECT_EQ(Error::Connection, res.error());
  1220. }
  1221. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  1222. auto host = "httpcan.org/";
  1223. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1224. SSLClient cli(host);
  1225. #else
  1226. Client cli(host);
  1227. #endif
  1228. cli.set_connection_timeout(std::chrono::seconds(2));
  1229. auto res = cli.Get("/");
  1230. ASSERT_TRUE(!res);
  1231. stringstream s;
  1232. s << "error code: " << res.error();
  1233. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  1234. }
  1235. TEST(ConnectionErrorTest, InvalidPort) {
  1236. auto host = "localhost";
  1237. auto port = 44380;
  1238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1239. SSLClient cli(host, port);
  1240. #else
  1241. Client cli(host, port);
  1242. #endif
  1243. cli.set_connection_timeout(std::chrono::seconds(2));
  1244. auto res = cli.Get("/");
  1245. ASSERT_TRUE(!res);
  1246. EXPECT_TRUE(Error::Connection == res.error() ||
  1247. Error::ConnectionTimeout == res.error());
  1248. }
  1249. TEST(ConnectionErrorTest, Timeout_Online) {
  1250. auto host = "google.com";
  1251. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1252. auto port = 44380;
  1253. SSLClient cli(host, port);
  1254. #else
  1255. auto port = 8080;
  1256. Client cli(host, port);
  1257. #endif
  1258. cli.set_connection_timeout(std::chrono::seconds(2));
  1259. // only probe one address type so that the error reason
  1260. // correlates to the timed-out IPv4, not the unsupported
  1261. // IPv6 connection attempt
  1262. cli.set_address_family(AF_INET);
  1263. auto res = cli.Get("/");
  1264. ASSERT_TRUE(!res);
  1265. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  1266. }
  1267. TEST(CancelTest, NoCancel_Online) {
  1268. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1269. auto host = "httpcan.org";
  1270. auto path = std::string{"/range/32"};
  1271. #else
  1272. auto host = "nghttp2.org";
  1273. auto path = std::string{"/httpbin/range/32"};
  1274. #endif
  1275. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1276. auto port = 443;
  1277. SSLClient cli(host, port);
  1278. #else
  1279. auto port = 80;
  1280. Client cli(host, port);
  1281. #endif
  1282. cli.set_connection_timeout(std::chrono::seconds(5));
  1283. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  1284. ASSERT_TRUE(res);
  1285. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1286. EXPECT_EQ(StatusCode::OK_200, res->status);
  1287. }
  1288. TEST(CancelTest, WithCancelSmallPayload_Online) {
  1289. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1290. auto host = "httpcan.org";
  1291. auto path = std::string{"/range/32"};
  1292. #else
  1293. auto host = "nghttp2.org";
  1294. auto path = std::string{"/httpbin/range/32"};
  1295. #endif
  1296. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1297. auto port = 443;
  1298. SSLClient cli(host, port);
  1299. #else
  1300. auto port = 80;
  1301. Client cli(host, port);
  1302. #endif
  1303. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  1304. cli.set_connection_timeout(std::chrono::seconds(5));
  1305. ASSERT_TRUE(!res);
  1306. EXPECT_EQ(Error::Canceled, res.error());
  1307. }
  1308. TEST(CancelTest, WithCancelLargePayload_Online) {
  1309. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1310. auto host = "httpcan.org";
  1311. auto path = std::string{"/range/65536"};
  1312. #else
  1313. auto host = "nghttp2.org";
  1314. auto path = std::string{"/httpbin/range/65536"};
  1315. #endif
  1316. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1317. auto port = 443;
  1318. SSLClient cli(host, port);
  1319. #else
  1320. auto port = 80;
  1321. Client cli(host, port);
  1322. #endif
  1323. cli.set_connection_timeout(std::chrono::seconds(5));
  1324. uint32_t count = 0;
  1325. auto res =
  1326. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  1327. ASSERT_TRUE(!res);
  1328. EXPECT_EQ(Error::Canceled, res.error());
  1329. }
  1330. TEST(CancelTest, NoCancelPost) {
  1331. Server svr;
  1332. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1333. res.set_content("Hello World!", "text/plain");
  1334. });
  1335. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1336. auto se = detail::scope_exit([&] {
  1337. svr.stop();
  1338. thread.join();
  1339. ASSERT_FALSE(svr.is_running());
  1340. });
  1341. svr.wait_until_ready();
  1342. Client cli(HOST, PORT);
  1343. cli.set_connection_timeout(std::chrono::seconds(5));
  1344. auto res =
  1345. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1346. "application/json", [](uint64_t, uint64_t) { return true; });
  1347. ASSERT_TRUE(res);
  1348. EXPECT_EQ("Hello World!", res->body);
  1349. EXPECT_EQ(StatusCode::OK_200, res->status);
  1350. }
  1351. TEST(CancelTest, WithCancelSmallPayloadPost) {
  1352. Server svr;
  1353. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1354. res.set_content("Hello World!", "text/plain");
  1355. });
  1356. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1357. auto se = detail::scope_exit([&] {
  1358. svr.stop();
  1359. thread.join();
  1360. ASSERT_FALSE(svr.is_running());
  1361. });
  1362. svr.wait_until_ready();
  1363. Client cli(HOST, PORT);
  1364. cli.set_connection_timeout(std::chrono::seconds(5));
  1365. auto res =
  1366. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1367. "application/json", [](uint64_t, uint64_t) { return false; });
  1368. ASSERT_TRUE(!res);
  1369. EXPECT_EQ(Error::Canceled, res.error());
  1370. }
  1371. TEST(CancelTest, WithCancelLargePayloadPost) {
  1372. Server svr;
  1373. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  1374. res.set_content(LARGE_DATA, "text/plain");
  1375. });
  1376. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1377. auto se = detail::scope_exit([&] {
  1378. svr.stop();
  1379. thread.join();
  1380. ASSERT_FALSE(svr.is_running());
  1381. });
  1382. svr.wait_until_ready();
  1383. Client cli(HOST, PORT);
  1384. cli.set_connection_timeout(std::chrono::seconds(5));
  1385. auto res =
  1386. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1387. "application/json", [](uint64_t, uint64_t) { return false; });
  1388. ASSERT_TRUE(!res);
  1389. EXPECT_EQ(Error::Canceled, res.error());
  1390. }
  1391. TEST(CancelTest, NoCancelPut) {
  1392. Server svr;
  1393. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1394. res.set_content("Hello World!", "text/plain");
  1395. });
  1396. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1397. auto se = detail::scope_exit([&] {
  1398. svr.stop();
  1399. thread.join();
  1400. ASSERT_FALSE(svr.is_running());
  1401. });
  1402. svr.wait_until_ready();
  1403. Client cli(HOST, PORT);
  1404. cli.set_connection_timeout(std::chrono::seconds(5));
  1405. auto res =
  1406. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1407. "application/json", [](uint64_t, uint64_t) { return true; });
  1408. ASSERT_TRUE(res);
  1409. EXPECT_EQ("Hello World!", res->body);
  1410. EXPECT_EQ(StatusCode::OK_200, res->status);
  1411. }
  1412. TEST(CancelTest, WithCancelSmallPayloadPut) {
  1413. Server svr;
  1414. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1415. res.set_content("Hello World!", "text/plain");
  1416. });
  1417. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1418. auto se = detail::scope_exit([&] {
  1419. svr.stop();
  1420. thread.join();
  1421. ASSERT_FALSE(svr.is_running());
  1422. });
  1423. svr.wait_until_ready();
  1424. Client cli(HOST, PORT);
  1425. cli.set_connection_timeout(std::chrono::seconds(5));
  1426. auto res =
  1427. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1428. "application/json", [](uint64_t, uint64_t) { return false; });
  1429. ASSERT_TRUE(!res);
  1430. EXPECT_EQ(Error::Canceled, res.error());
  1431. }
  1432. TEST(CancelTest, WithCancelLargePayloadPut) {
  1433. Server svr;
  1434. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  1435. res.set_content(LARGE_DATA, "text/plain");
  1436. });
  1437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1438. auto se = detail::scope_exit([&] {
  1439. svr.stop();
  1440. thread.join();
  1441. ASSERT_FALSE(svr.is_running());
  1442. });
  1443. svr.wait_until_ready();
  1444. Client cli(HOST, PORT);
  1445. cli.set_connection_timeout(std::chrono::seconds(5));
  1446. auto res =
  1447. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1448. "application/json", [](uint64_t, uint64_t) { return false; });
  1449. ASSERT_TRUE(!res);
  1450. EXPECT_EQ(Error::Canceled, res.error());
  1451. }
  1452. TEST(CancelTest, NoCancelPatch) {
  1453. Server svr;
  1454. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1455. res.set_content("Hello World!", "text/plain");
  1456. });
  1457. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1458. auto se = detail::scope_exit([&] {
  1459. svr.stop();
  1460. thread.join();
  1461. ASSERT_FALSE(svr.is_running());
  1462. });
  1463. svr.wait_until_ready();
  1464. Client cli(HOST, PORT);
  1465. cli.set_connection_timeout(std::chrono::seconds(5));
  1466. auto res =
  1467. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1468. "application/json", [](uint64_t, uint64_t) { return true; });
  1469. ASSERT_TRUE(res);
  1470. EXPECT_EQ("Hello World!", res->body);
  1471. EXPECT_EQ(StatusCode::OK_200, res->status);
  1472. }
  1473. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  1474. Server svr;
  1475. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1476. res.set_content("Hello World!", "text/plain");
  1477. });
  1478. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1479. auto se = detail::scope_exit([&] {
  1480. svr.stop();
  1481. thread.join();
  1482. ASSERT_FALSE(svr.is_running());
  1483. });
  1484. svr.wait_until_ready();
  1485. Client cli(HOST, PORT);
  1486. cli.set_connection_timeout(std::chrono::seconds(5));
  1487. auto res =
  1488. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1489. "application/json", [](uint64_t, uint64_t) { return false; });
  1490. ASSERT_TRUE(!res);
  1491. EXPECT_EQ(Error::Canceled, res.error());
  1492. }
  1493. TEST(CancelTest, WithCancelLargePayloadPatch) {
  1494. Server svr;
  1495. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  1496. res.set_content(LARGE_DATA, "text/plain");
  1497. });
  1498. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1499. auto se = detail::scope_exit([&] {
  1500. svr.stop();
  1501. thread.join();
  1502. ASSERT_FALSE(svr.is_running());
  1503. });
  1504. svr.wait_until_ready();
  1505. Client cli(HOST, PORT);
  1506. cli.set_connection_timeout(std::chrono::seconds(5));
  1507. auto res =
  1508. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1509. "application/json", [](uint64_t, uint64_t) { return false; });
  1510. ASSERT_TRUE(!res);
  1511. EXPECT_EQ(Error::Canceled, res.error());
  1512. }
  1513. TEST(CancelTest, NoCancelDelete) {
  1514. Server svr;
  1515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1516. res.set_content("Hello World!", "text/plain");
  1517. });
  1518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1519. auto se = detail::scope_exit([&] {
  1520. svr.stop();
  1521. thread.join();
  1522. ASSERT_FALSE(svr.is_running());
  1523. });
  1524. svr.wait_until_ready();
  1525. Client cli(HOST, PORT);
  1526. cli.set_connection_timeout(std::chrono::seconds(5));
  1527. auto res =
  1528. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1529. "application/json", [](uint64_t, uint64_t) { return true; });
  1530. ASSERT_TRUE(res);
  1531. EXPECT_EQ("Hello World!", res->body);
  1532. EXPECT_EQ(StatusCode::OK_200, res->status);
  1533. }
  1534. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  1535. Server svr;
  1536. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1537. res.set_content("Hello World!", "text/plain");
  1538. });
  1539. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1540. auto se = detail::scope_exit([&] {
  1541. svr.stop();
  1542. thread.join();
  1543. ASSERT_FALSE(svr.is_running());
  1544. });
  1545. svr.wait_until_ready();
  1546. Client cli(HOST, PORT);
  1547. cli.set_connection_timeout(std::chrono::seconds(5));
  1548. auto res =
  1549. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1550. "application/json", [](uint64_t, uint64_t) { return false; });
  1551. ASSERT_TRUE(!res);
  1552. EXPECT_EQ(Error::Canceled, res.error());
  1553. }
  1554. TEST(CancelTest, WithCancelLargePayloadDelete) {
  1555. Server svr;
  1556. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  1557. res.set_content(LARGE_DATA, "text/plain");
  1558. });
  1559. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. thread.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. Client cli(HOST, PORT);
  1567. cli.set_connection_timeout(std::chrono::seconds(5));
  1568. auto res =
  1569. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  1570. "application/json", [](uint64_t, uint64_t) { return false; });
  1571. ASSERT_TRUE(!res);
  1572. EXPECT_EQ(Error::Canceled, res.error());
  1573. }
  1574. static std::string remove_whitespace(const std::string &input) {
  1575. std::string output;
  1576. output.reserve(input.size());
  1577. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  1578. [](unsigned char c) { return !std::isspace(c); });
  1579. return output;
  1580. }
  1581. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  1582. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1583. auto host = "httpcan.org";
  1584. auto path = std::string{"/basic-auth/hello/world"};
  1585. #else
  1586. auto host = "nghttp2.org";
  1587. auto path = std::string{"/httpbin/basic-auth/hello/world"};
  1588. #endif
  1589. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1590. auto port = 443;
  1591. SSLClient cli(host, port);
  1592. #else
  1593. auto port = 80;
  1594. Client cli(host, port);
  1595. #endif
  1596. {
  1597. auto res = cli.Get(path);
  1598. ASSERT_TRUE(res);
  1599. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1600. }
  1601. {
  1602. auto res =
  1603. cli.Get(path, {make_basic_authentication_header("hello", "world")});
  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", "world");
  1611. auto res = cli.Get(path);
  1612. ASSERT_TRUE(res);
  1613. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1614. remove_whitespace(res->body));
  1615. EXPECT_EQ(StatusCode::OK_200, res->status);
  1616. }
  1617. {
  1618. cli.set_basic_auth("hello", "bad");
  1619. auto res = cli.Get(path);
  1620. ASSERT_TRUE(res);
  1621. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1622. }
  1623. {
  1624. cli.set_basic_auth("bad", "world");
  1625. auto res = cli.Get(path);
  1626. ASSERT_TRUE(res);
  1627. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1628. }
  1629. }
  1630. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1631. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  1632. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1633. auto host = "httpcan.org";
  1634. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  1635. auto paths = std::vector<std::string>{
  1636. "/digest-auth/auth/hello/world/MD5",
  1637. "/digest-auth/auth/hello/world/SHA-256",
  1638. "/digest-auth/auth/hello/world/SHA-512",
  1639. };
  1640. #else
  1641. auto host = "nghttp2.org";
  1642. auto unauth_path = std::string{"/httpbin/digest-auth/auth/hello/world"};
  1643. auto paths = std::vector<std::string>{
  1644. "/httpbin/digest-auth/auth/hello/world/MD5",
  1645. "/httpbin/digest-auth/auth/hello/world/SHA-256",
  1646. "/httpbin/digest-auth/auth/hello/world/SHA-512",
  1647. "/httpbin/digest-auth/auth-int/hello/world/MD5",
  1648. };
  1649. #endif
  1650. auto port = 443;
  1651. SSLClient cli(host, port);
  1652. {
  1653. auto res = cli.Get(unauth_path);
  1654. ASSERT_TRUE(res);
  1655. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1656. }
  1657. {
  1658. cli.set_digest_auth("hello", "world");
  1659. for (const auto &path : paths) {
  1660. auto res = cli.Get(path.c_str());
  1661. ASSERT_TRUE(res);
  1662. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1663. std::string algo(path.substr(path.rfind('/') + 1));
  1664. EXPECT_EQ(
  1665. remove_whitespace("{\"algorithm\":\"" + algo +
  1666. "\",\"authenticated\":true,\"user\":\"hello\"}\n"),
  1667. remove_whitespace(res->body));
  1668. #else
  1669. EXPECT_EQ("{\"authenticated\":true,\"user\":\"hello\"}",
  1670. remove_whitespace(res->body));
  1671. #endif
  1672. EXPECT_EQ(StatusCode::OK_200, res->status);
  1673. }
  1674. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  1675. cli.set_digest_auth("hello", "bad");
  1676. for (const auto &path : paths) {
  1677. auto res = cli.Get(path.c_str());
  1678. ASSERT_TRUE(res);
  1679. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  1680. }
  1681. #endif
  1682. }
  1683. }
  1684. #endif
  1685. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  1686. auto host = "google.com";
  1687. auto another_host = "example.com";
  1688. auto wrong_ip = "0.0.0.0";
  1689. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1690. SSLClient cli(host);
  1691. #else
  1692. Client cli(host);
  1693. #endif
  1694. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  1695. auto res = cli.Get("/");
  1696. ASSERT_TRUE(res);
  1697. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  1698. }
  1699. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  1700. auto host = "google.com";
  1701. auto wrong_ip = "0.0.0.0";
  1702. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1703. SSLClient cli(host);
  1704. #else
  1705. Client cli(host);
  1706. #endif
  1707. cli.set_hostname_addr_map({{host, wrong_ip}});
  1708. auto res = cli.Get("/");
  1709. ASSERT_TRUE(!res);
  1710. EXPECT_EQ(Error::Connection, res.error());
  1711. }
  1712. TEST(AbsoluteRedirectTest, Redirect_Online) {
  1713. auto host = "nghttp2.org";
  1714. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1715. SSLClient cli(host);
  1716. #else
  1717. Client cli(host);
  1718. #endif
  1719. cli.set_follow_location(true);
  1720. auto res = cli.Get("/httpbin/absolute-redirect/3");
  1721. ASSERT_TRUE(res);
  1722. EXPECT_EQ(StatusCode::OK_200, res->status);
  1723. }
  1724. TEST(RedirectTest, Redirect_Online) {
  1725. auto host = "nghttp2.org";
  1726. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1727. SSLClient cli(host);
  1728. #else
  1729. Client cli(host);
  1730. #endif
  1731. cli.set_follow_location(true);
  1732. auto res = cli.Get("/httpbin/redirect/3");
  1733. ASSERT_TRUE(res);
  1734. EXPECT_EQ(StatusCode::OK_200, res->status);
  1735. }
  1736. TEST(RelativeRedirectTest, Redirect_Online) {
  1737. auto host = "nghttp2.org";
  1738. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1739. SSLClient cli(host);
  1740. #else
  1741. Client cli(host);
  1742. #endif
  1743. cli.set_follow_location(true);
  1744. auto res = cli.Get("/httpbin/relative-redirect/3");
  1745. ASSERT_TRUE(res);
  1746. EXPECT_EQ(StatusCode::OK_200, res->status);
  1747. }
  1748. TEST(TooManyRedirectTest, Redirect_Online) {
  1749. auto host = "nghttp2.org";
  1750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1751. SSLClient cli(host);
  1752. #else
  1753. Client cli(host);
  1754. #endif
  1755. cli.set_follow_location(true);
  1756. auto res = cli.Get("/httpbin/redirect/21");
  1757. ASSERT_TRUE(!res);
  1758. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  1759. }
  1760. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  1761. TEST(YahooRedirectTest, Redirect_Online) {
  1762. Client cli("yahoo.com");
  1763. auto res = cli.Get("/");
  1764. ASSERT_TRUE(res);
  1765. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  1766. cli.set_follow_location(true);
  1767. res = cli.Get("/");
  1768. ASSERT_TRUE(res);
  1769. EXPECT_EQ(StatusCode::OK_200, res->status);
  1770. EXPECT_EQ("https://www.yahoo.com/", res->location);
  1771. }
  1772. // Previously "nghttp2.org" "/httpbin/redirect-to"
  1773. #define REDIR_HOST "httpbingo.org"
  1774. #define REDIR_PATH "/redirect-to"
  1775. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  1776. SSLClient cli(REDIR_HOST);
  1777. cli.set_follow_location(true);
  1778. auto res =
  1779. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  1780. ASSERT_TRUE(res);
  1781. EXPECT_EQ(StatusCode::OK_200, res->status);
  1782. }
  1783. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  1784. SSLClient cli(REDIR_HOST);
  1785. cli.set_follow_location(true);
  1786. Params params;
  1787. params.emplace("url", "http://example.com");
  1788. params.emplace("status_code", "302");
  1789. auto res = cli.Get(REDIR_PATH, params, Headers{});
  1790. ASSERT_TRUE(res);
  1791. EXPECT_EQ(StatusCode::OK_200, res->status);
  1792. }
  1793. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  1794. SSLClient cli(REDIR_HOST);
  1795. cli.set_follow_location(true);
  1796. Params params;
  1797. params.emplace("url", "http://example.com");
  1798. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  1799. ASSERT_TRUE(res);
  1800. EXPECT_EQ(StatusCode::OK_200, res->status);
  1801. }
  1802. TEST(UrlWithSpace, Redirect_Online) {
  1803. SSLClient cli("edge.forgecdn.net");
  1804. cli.set_follow_location(true);
  1805. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  1806. ASSERT_TRUE(res);
  1807. EXPECT_EQ(StatusCode::OK_200, res->status);
  1808. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  1809. }
  1810. #endif
  1811. #if !defined(_WIN32) && !defined(_WIN64)
  1812. TEST(ReceiveSignals, Signal) {
  1813. auto setupSignalHandlers = []() {
  1814. struct sigaction act;
  1815. sigemptyset(&act.sa_mask);
  1816. act.sa_flags = SA_SIGINFO;
  1817. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  1818. switch (sig) {
  1819. case SIGINT:
  1820. default: break;
  1821. }
  1822. };
  1823. ::sigaction(SIGINT, &act, nullptr);
  1824. };
  1825. Server svr;
  1826. int port = 0;
  1827. auto thread = std::thread([&]() {
  1828. setupSignalHandlers();
  1829. port = svr.bind_to_any_port(HOST);
  1830. svr.listen_after_bind();
  1831. });
  1832. auto se = detail::scope_exit([&] {
  1833. svr.stop();
  1834. thread.join();
  1835. ASSERT_FALSE(svr.is_running());
  1836. });
  1837. svr.wait_until_ready();
  1838. ASSERT_TRUE(svr.is_running());
  1839. pthread_kill(thread.native_handle(), SIGINT);
  1840. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  1841. ASSERT_TRUE(svr.is_running());
  1842. }
  1843. #endif
  1844. TEST(RedirectToDifferentPort, Redirect) {
  1845. Server svr1;
  1846. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  1847. res.set_content("Hello World!", "text/plain");
  1848. });
  1849. int svr1_port = 0;
  1850. auto thread1 = std::thread([&]() {
  1851. svr1_port = svr1.bind_to_any_port(HOST);
  1852. svr1.listen_after_bind();
  1853. });
  1854. Server svr2;
  1855. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  1856. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  1857. });
  1858. int svr2_port = 0;
  1859. auto thread2 = std::thread([&]() {
  1860. svr2_port = svr2.bind_to_any_port(HOST);
  1861. svr2.listen_after_bind();
  1862. });
  1863. auto se = detail::scope_exit([&] {
  1864. svr2.stop();
  1865. thread2.join();
  1866. svr1.stop();
  1867. thread1.join();
  1868. ASSERT_FALSE(svr2.is_running());
  1869. ASSERT_FALSE(svr1.is_running());
  1870. });
  1871. svr1.wait_until_ready();
  1872. svr2.wait_until_ready();
  1873. Client cli("localhost", svr2_port);
  1874. cli.set_follow_location(true);
  1875. auto res = cli.Get("/2");
  1876. ASSERT_TRUE(res);
  1877. EXPECT_EQ(StatusCode::OK_200, res->status);
  1878. EXPECT_EQ("Hello World!", res->body);
  1879. }
  1880. TEST(RedirectFromPageWithContent, Redirect) {
  1881. Server svr;
  1882. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1883. res.set_content("___", "text/plain");
  1884. res.set_redirect("/2");
  1885. });
  1886. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  1887. res.set_content("Hello World!", "text/plain");
  1888. });
  1889. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  1890. auto se = detail::scope_exit([&] {
  1891. svr.stop();
  1892. th.join();
  1893. ASSERT_FALSE(svr.is_running());
  1894. });
  1895. svr.wait_until_ready();
  1896. {
  1897. Client cli("localhost", PORT);
  1898. cli.set_follow_location(true);
  1899. std::string body;
  1900. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1901. body.append(data, data_length);
  1902. return true;
  1903. });
  1904. ASSERT_TRUE(res);
  1905. EXPECT_EQ(StatusCode::OK_200, res->status);
  1906. EXPECT_EQ("Hello World!", body);
  1907. }
  1908. {
  1909. Client cli("localhost", PORT);
  1910. std::string body;
  1911. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1912. body.append(data, data_length);
  1913. return true;
  1914. });
  1915. ASSERT_TRUE(res);
  1916. EXPECT_EQ(StatusCode::Found_302, res->status);
  1917. EXPECT_EQ("___", body);
  1918. }
  1919. }
  1920. TEST(RedirectFromPageWithContentIP6, Redirect) {
  1921. Server svr;
  1922. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  1923. res.set_content("___", "text/plain");
  1924. // res.set_redirect("/2");
  1925. res.set_redirect("http://[::1]:1234/2");
  1926. });
  1927. svr.Get("/2", [&](const Request &req, Response &res) {
  1928. auto host_header = req.headers.find("Host");
  1929. ASSERT_TRUE(host_header != req.headers.end());
  1930. EXPECT_EQ("[::1]:1234", host_header->second);
  1931. res.set_content("Hello World!", "text/plain");
  1932. });
  1933. auto th = std::thread([&]() { svr.listen("::1", 1234); });
  1934. auto se = detail::scope_exit([&] {
  1935. svr.stop();
  1936. th.join();
  1937. ASSERT_FALSE(svr.is_running());
  1938. });
  1939. // When IPV6 support isn't available svr.listen("::1", 1234) never
  1940. // actually starts anything, so the condition !svr.is_running() will
  1941. // always remain true, and the loop never stops.
  1942. // This basically counts how many milliseconds have passed since the
  1943. // call to svr.listen(), and if after 5 seconds nothing started yet
  1944. // aborts the test.
  1945. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  1946. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1947. ASSERT_LT(milliseconds, 5000U);
  1948. }
  1949. {
  1950. Client cli("http://[::1]:1234");
  1951. cli.set_follow_location(true);
  1952. std::string body;
  1953. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1954. body.append(data, data_length);
  1955. return true;
  1956. });
  1957. ASSERT_TRUE(res);
  1958. EXPECT_EQ(StatusCode::OK_200, res->status);
  1959. EXPECT_EQ("Hello World!", body);
  1960. }
  1961. {
  1962. Client cli("http://[::1]:1234");
  1963. std::string body;
  1964. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  1965. body.append(data, data_length);
  1966. return true;
  1967. });
  1968. ASSERT_TRUE(res);
  1969. EXPECT_EQ(StatusCode::Found_302, res->status);
  1970. EXPECT_EQ("___", body);
  1971. }
  1972. }
  1973. TEST(PathUrlEncodeTest, PathUrlEncode) {
  1974. Server svr;
  1975. svr.Get("/foo", [](const Request &req, Response &res) {
  1976. auto a = req.params.find("a");
  1977. if (a != req.params.end()) {
  1978. res.set_content((*a).second, "text/plain");
  1979. res.status = StatusCode::OK_200;
  1980. } else {
  1981. res.status = StatusCode::BadRequest_400;
  1982. }
  1983. });
  1984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1985. auto se = detail::scope_exit([&] {
  1986. svr.stop();
  1987. thread.join();
  1988. ASSERT_FALSE(svr.is_running());
  1989. });
  1990. svr.wait_until_ready();
  1991. {
  1992. Client cli(HOST, PORT);
  1993. cli.set_path_encode(false);
  1994. auto res = cli.Get("/foo?a=explicitly+encoded");
  1995. ASSERT_TRUE(res);
  1996. EXPECT_EQ(StatusCode::OK_200, res->status);
  1997. // This expects it back with a space, as the `+` won't have been
  1998. // url-encoded, and server-side the params get decoded turning `+`
  1999. // into spaces.
  2000. EXPECT_EQ("explicitly encoded", res->body);
  2001. }
  2002. }
  2003. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  2004. Server svr;
  2005. svr.Get("/", [](const Request &req, Response &) {
  2006. EXPECT_EQ("\x0A", req.get_param_value("something"));
  2007. });
  2008. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2009. auto se = detail::scope_exit([&] {
  2010. svr.stop();
  2011. thread.join();
  2012. ASSERT_FALSE(svr.is_running());
  2013. });
  2014. svr.wait_until_ready();
  2015. {
  2016. Client cli(HOST, PORT);
  2017. cli.set_path_encode(false);
  2018. auto res = cli.Get("/?something=%0A");
  2019. ASSERT_TRUE(res);
  2020. EXPECT_EQ(StatusCode::OK_200, res->status);
  2021. }
  2022. }
  2023. TEST(BindServerTest, DISABLED_BindDualStack) {
  2024. Server svr;
  2025. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  2026. res.set_content("Hello World!", "text/plain");
  2027. });
  2028. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  2029. auto se = detail::scope_exit([&] {
  2030. svr.stop();
  2031. thread.join();
  2032. ASSERT_FALSE(svr.is_running());
  2033. });
  2034. svr.wait_until_ready();
  2035. {
  2036. Client cli("127.0.0.1", PORT);
  2037. auto res = cli.Get("/1");
  2038. ASSERT_TRUE(res);
  2039. EXPECT_EQ(StatusCode::OK_200, res->status);
  2040. EXPECT_EQ("Hello World!", res->body);
  2041. }
  2042. {
  2043. Client cli("::1", PORT);
  2044. auto res = cli.Get("/1");
  2045. ASSERT_TRUE(res);
  2046. EXPECT_EQ(StatusCode::OK_200, res->status);
  2047. EXPECT_EQ("Hello World!", res->body);
  2048. }
  2049. }
  2050. TEST(BindServerTest, BindAndListenSeparately) {
  2051. Server svr;
  2052. int port = svr.bind_to_any_port("0.0.0.0");
  2053. ASSERT_TRUE(svr.is_valid());
  2054. ASSERT_TRUE(port > 0);
  2055. svr.stop();
  2056. }
  2057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2058. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  2059. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  2060. CLIENT_CA_CERT_DIR);
  2061. int port = svr.bind_to_any_port("0.0.0.0");
  2062. ASSERT_TRUE(svr.is_valid());
  2063. ASSERT_TRUE(port > 0);
  2064. svr.stop();
  2065. }
  2066. #endif
  2067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2068. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  2069. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  2070. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  2071. int port = svr.bind_to_any_port("0.0.0.0");
  2072. ASSERT_TRUE(svr.is_valid());
  2073. ASSERT_TRUE(port > 0);
  2074. svr.stop();
  2075. }
  2076. #endif
  2077. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2078. X509 *readCertificate(const std::string &strFileName) {
  2079. std::ifstream inStream(strFileName);
  2080. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  2081. std::istreambuf_iterator<char>());
  2082. if (strCertPEM.empty()) return (nullptr);
  2083. BIO *pbCert = BIO_new(BIO_s_mem());
  2084. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  2085. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  2086. BIO_free(pbCert);
  2087. return (pCert);
  2088. }
  2089. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  2090. std::ifstream inStream(strFileName);
  2091. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  2092. std::istreambuf_iterator<char>());
  2093. if (strPrivateKeyPEM.empty()) return (nullptr);
  2094. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  2095. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  2096. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  2097. BIO_free(pbPrivKey);
  2098. return (pPrivateKey);
  2099. }
  2100. TEST(BindServerTest, UpdateCerts) {
  2101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  2102. int port = svr.bind_to_any_port("0.0.0.0");
  2103. ASSERT_TRUE(svr.is_valid());
  2104. ASSERT_TRUE(port > 0);
  2105. X509 *cert = readCertificate(SERVER_CERT_FILE);
  2106. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  2107. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  2108. ASSERT_TRUE(cert != nullptr);
  2109. ASSERT_TRUE(ca_cert != nullptr);
  2110. ASSERT_TRUE(key != nullptr);
  2111. X509_STORE *cert_store = X509_STORE_new();
  2112. X509_STORE_add_cert(cert_store, ca_cert);
  2113. svr.update_certs(cert, key, cert_store);
  2114. ASSERT_TRUE(svr.is_valid());
  2115. svr.stop();
  2116. X509_free(cert);
  2117. X509_free(ca_cert);
  2118. EVP_PKEY_free(key);
  2119. }
  2120. #endif
  2121. TEST(ErrorHandlerTest, ContentLength) {
  2122. Server svr;
  2123. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2124. res.status = StatusCode::OK_200;
  2125. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2126. "text/html"); // <= Content-Length still 13
  2127. });
  2128. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2129. res.set_content("Hello World!\n", "text/plain");
  2130. res.status = 524;
  2131. });
  2132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2133. auto se = detail::scope_exit([&] {
  2134. svr.stop();
  2135. thread.join();
  2136. ASSERT_FALSE(svr.is_running());
  2137. });
  2138. svr.wait_until_ready();
  2139. {
  2140. Client cli(HOST, PORT);
  2141. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2142. ASSERT_TRUE(res);
  2143. EXPECT_EQ(StatusCode::OK_200, res->status);
  2144. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2145. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2146. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2147. }
  2148. }
  2149. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  2150. TEST(ExceptionTest, WithoutExceptionHandler) {
  2151. Server svr;
  2152. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  2153. throw std::runtime_error("exception...");
  2154. });
  2155. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  2156. throw std::runtime_error("exception\r\n...");
  2157. });
  2158. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  2159. auto se = detail::scope_exit([&] {
  2160. svr.stop();
  2161. listen_thread.join();
  2162. ASSERT_FALSE(svr.is_running());
  2163. });
  2164. svr.wait_until_ready();
  2165. Client cli("localhost", PORT);
  2166. {
  2167. auto res = cli.Get("/exception");
  2168. ASSERT_TRUE(res);
  2169. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2170. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2171. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  2172. }
  2173. {
  2174. auto res = cli.Get("/unknown");
  2175. ASSERT_TRUE(res);
  2176. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2177. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  2178. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  2179. }
  2180. }
  2181. TEST(ExceptionTest, WithExceptionHandler) {
  2182. Server svr;
  2183. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  2184. std::exception_ptr ep) {
  2185. EXPECT_FALSE(ep == nullptr);
  2186. try {
  2187. std::rethrow_exception(ep);
  2188. } catch (std::exception &e) {
  2189. EXPECT_EQ("abc", std::string(e.what()));
  2190. } catch (...) {}
  2191. res.status = StatusCode::InternalServerError_500;
  2192. res.set_content("abcdefghijklmnopqrstuvwxyz",
  2193. "text/html"); // <= Content-Length still 13 at this point
  2194. });
  2195. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2196. res.set_content("Hello World!\n", "text/plain");
  2197. throw std::runtime_error("abc");
  2198. });
  2199. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2200. auto se = detail::scope_exit([&] {
  2201. svr.stop();
  2202. thread.join();
  2203. ASSERT_FALSE(svr.is_running());
  2204. });
  2205. svr.wait_until_ready();
  2206. for (size_t i = 0; i < 10; i++) {
  2207. Client cli(HOST, PORT);
  2208. for (size_t j = 0; j < 100; j++) {
  2209. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2210. ASSERT_TRUE(res);
  2211. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2213. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2214. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2215. }
  2216. cli.set_keep_alive(true);
  2217. for (size_t j = 0; j < 100; j++) {
  2218. auto res = cli.Get("/hi", {{"Accept-Encoding", ""}});
  2219. ASSERT_TRUE(res);
  2220. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2221. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2222. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  2223. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  2224. }
  2225. }
  2226. }
  2227. TEST(ExceptionTest, AndErrorHandler) {
  2228. Server svr;
  2229. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2230. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  2231. });
  2232. svr.set_exception_handler(
  2233. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  2234. EXPECT_FALSE(ep == nullptr);
  2235. try {
  2236. std::rethrow_exception(ep);
  2237. } catch (std::exception &e) {
  2238. res.set_content(e.what(), "text/html");
  2239. } catch (...) {}
  2240. res.status = StatusCode::InternalServerError_500;
  2241. });
  2242. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  2243. throw std::runtime_error("EXCEPTION");
  2244. });
  2245. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  2246. res.set_content("ERROR", "text/html");
  2247. res.status = StatusCode::InternalServerError_500;
  2248. });
  2249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2250. auto se = detail::scope_exit([&] {
  2251. svr.stop();
  2252. thread.join();
  2253. ASSERT_FALSE(svr.is_running());
  2254. });
  2255. svr.wait_until_ready();
  2256. Client cli(HOST, PORT);
  2257. {
  2258. auto res = cli.Get("/exception");
  2259. ASSERT_TRUE(res);
  2260. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2261. EXPECT_EQ("EXCEPTION", res->body);
  2262. }
  2263. {
  2264. auto res = cli.Get("/error");
  2265. ASSERT_TRUE(res);
  2266. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  2267. EXPECT_EQ("ERROR", res->body);
  2268. }
  2269. {
  2270. auto res = cli.Get("/invalid");
  2271. ASSERT_TRUE(res);
  2272. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2273. EXPECT_EQ("NOT_FOUND", res->body);
  2274. }
  2275. }
  2276. #endif
  2277. TEST(NoContentTest, ContentLength) {
  2278. Server svr;
  2279. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2280. res.status = StatusCode::NoContent_204;
  2281. });
  2282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2283. auto se = detail::scope_exit([&] {
  2284. svr.stop();
  2285. thread.join();
  2286. ASSERT_FALSE(svr.is_running());
  2287. });
  2288. svr.wait_until_ready();
  2289. {
  2290. Client cli(HOST, PORT);
  2291. auto res = cli.Get("/hi");
  2292. ASSERT_TRUE(res);
  2293. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  2294. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  2295. }
  2296. }
  2297. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  2298. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2299. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  2300. ASSERT_TRUE(svr.is_valid());
  2301. #else
  2302. Server svr;
  2303. #endif
  2304. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  2305. if (req.path == "/routing_handler") {
  2306. res.set_header("PRE_ROUTING", "on");
  2307. res.set_content("Routing Handler", "text/plain");
  2308. return httplib::Server::HandlerResponse::Handled;
  2309. }
  2310. return httplib::Server::HandlerResponse::Unhandled;
  2311. });
  2312. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  2313. res.set_content("Error", "text/html");
  2314. });
  2315. svr.set_post_routing_handler([](const Request &req, Response &res) {
  2316. if (req.path == "/routing_handler") {
  2317. res.set_header("POST_ROUTING", "on");
  2318. }
  2319. });
  2320. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2321. res.set_content("Hello World!\n", "text/plain");
  2322. });
  2323. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2324. auto se = detail::scope_exit([&] {
  2325. svr.stop();
  2326. thread.join();
  2327. ASSERT_FALSE(svr.is_running());
  2328. });
  2329. svr.wait_until_ready();
  2330. {
  2331. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2332. SSLClient cli(HOST, PORT);
  2333. cli.enable_server_certificate_verification(false);
  2334. #else
  2335. Client cli(HOST, PORT);
  2336. #endif
  2337. auto res = cli.Get("/routing_handler");
  2338. ASSERT_TRUE(res);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ("Routing Handler", res->body);
  2341. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  2342. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  2343. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  2344. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  2345. }
  2346. {
  2347. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2348. SSLClient cli(HOST, PORT);
  2349. cli.enable_server_certificate_verification(false);
  2350. #else
  2351. Client cli(HOST, PORT);
  2352. #endif
  2353. auto res = cli.Get("/hi");
  2354. ASSERT_TRUE(res);
  2355. EXPECT_EQ(StatusCode::OK_200, res->status);
  2356. EXPECT_EQ("Hello World!\n", res->body);
  2357. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2358. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2359. }
  2360. {
  2361. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2362. SSLClient cli(HOST, PORT);
  2363. cli.enable_server_certificate_verification(false);
  2364. #else
  2365. Client cli(HOST, PORT);
  2366. #endif
  2367. auto res = cli.Get("/aaa");
  2368. ASSERT_TRUE(res);
  2369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2370. EXPECT_EQ("Error", res->body);
  2371. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  2372. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  2373. }
  2374. }
  2375. TEST(RequestHandlerTest, PreRequestHandler) {
  2376. auto route_path = "/user/:user";
  2377. Server svr;
  2378. svr.Get("/hi", [](const Request &, Response &res) {
  2379. res.set_content("hi", "text/plain");
  2380. });
  2381. svr.Get(route_path, [](const Request &req, Response &res) {
  2382. res.set_content(req.path_params.at("user"), "text/plain");
  2383. });
  2384. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  2385. if (req.matched_route == route_path) {
  2386. auto user = req.path_params.at("user");
  2387. if (user != "john") {
  2388. res.status = StatusCode::Forbidden_403;
  2389. res.set_content("error", "text/html");
  2390. return Server::HandlerResponse::Handled;
  2391. }
  2392. }
  2393. return Server::HandlerResponse::Unhandled;
  2394. });
  2395. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2396. auto se = detail::scope_exit([&] {
  2397. svr.stop();
  2398. thread.join();
  2399. ASSERT_FALSE(svr.is_running());
  2400. });
  2401. svr.wait_until_ready();
  2402. Client cli(HOST, PORT);
  2403. {
  2404. auto res = cli.Get("/hi");
  2405. ASSERT_TRUE(res);
  2406. EXPECT_EQ(StatusCode::OK_200, res->status);
  2407. EXPECT_EQ("hi", res->body);
  2408. }
  2409. {
  2410. auto res = cli.Get("/user/john");
  2411. ASSERT_TRUE(res);
  2412. EXPECT_EQ(StatusCode::OK_200, res->status);
  2413. EXPECT_EQ("john", res->body);
  2414. }
  2415. {
  2416. auto res = cli.Get("/user/invalid-user");
  2417. ASSERT_TRUE(res);
  2418. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  2419. EXPECT_EQ("error", res->body);
  2420. }
  2421. }
  2422. TEST(InvalidFormatTest, StatusCode) {
  2423. Server svr;
  2424. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2425. res.set_content("Hello World!\n", "text/plain");
  2426. res.status = 9999; // Status should be a three-digit code...
  2427. });
  2428. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2429. auto se = detail::scope_exit([&] {
  2430. svr.stop();
  2431. thread.join();
  2432. ASSERT_FALSE(svr.is_running());
  2433. });
  2434. svr.wait_until_ready();
  2435. {
  2436. Client cli(HOST, PORT);
  2437. auto res = cli.Get("/hi");
  2438. ASSERT_FALSE(res);
  2439. }
  2440. }
  2441. TEST(URLFragmentTest, WithFragment) {
  2442. Server svr;
  2443. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  2444. EXPECT_TRUE(req.target == "/hi");
  2445. });
  2446. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2447. auto se = detail::scope_exit([&] {
  2448. svr.stop();
  2449. thread.join();
  2450. ASSERT_FALSE(svr.is_running());
  2451. });
  2452. svr.wait_until_ready();
  2453. {
  2454. Client cli(HOST, PORT);
  2455. auto res = cli.Get("/hi#key1=val1=key2=val2");
  2456. EXPECT_TRUE(res);
  2457. EXPECT_EQ(StatusCode::OK_200, res->status);
  2458. res = cli.Get("/hi%23key1=val1=key2=val2");
  2459. EXPECT_TRUE(res);
  2460. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2461. }
  2462. }
  2463. TEST(HeaderWriter, SetHeaderWriter) {
  2464. Server svr;
  2465. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  2466. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  2467. return detail::write_headers(strm, hdrs);
  2468. });
  2469. svr.Get("/hi", [](const Request &req, Response &res) {
  2470. auto it = req.headers.find("CustomClientHeader");
  2471. EXPECT_TRUE(it != req.headers.end());
  2472. EXPECT_EQ(it->second, "CustomClientValue");
  2473. res.set_content("Hello World!\n", "text/plain");
  2474. });
  2475. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2476. auto se = detail::scope_exit([&] {
  2477. svr.stop();
  2478. thread.join();
  2479. ASSERT_FALSE(svr.is_running());
  2480. });
  2481. svr.wait_until_ready();
  2482. {
  2483. Client cli(HOST, PORT);
  2484. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  2485. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  2486. return detail::write_headers(strm, hdrs);
  2487. });
  2488. auto res = cli.Get("/hi");
  2489. EXPECT_TRUE(res);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. auto it = res->headers.find("CustomServerHeader");
  2492. EXPECT_TRUE(it != res->headers.end());
  2493. EXPECT_EQ(it->second, "CustomServerValue");
  2494. }
  2495. }
  2496. class ServerTest : public ::testing::Test {
  2497. protected:
  2498. ServerTest()
  2499. : cli_(HOST, PORT)
  2500. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2501. ,
  2502. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2503. #endif
  2504. {
  2505. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2506. cli_.enable_server_certificate_verification(false);
  2507. #endif
  2508. }
  2509. virtual void SetUp() {
  2510. svr_.set_mount_point("/", "./www");
  2511. svr_.set_mount_point("/mount", "./www2");
  2512. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  2513. svr_.Get("/hi",
  2514. [&](const Request & /*req*/, Response &res) {
  2515. res.set_content("Hello World!", "text/plain");
  2516. })
  2517. .Get("/file_content",
  2518. [&](const Request & /*req*/, Response &res) {
  2519. res.set_file_content("./www/dir/test.html");
  2520. })
  2521. .Get("/file_content_with_content_type",
  2522. [&](const Request & /*req*/, Response &res) {
  2523. res.set_file_content("./www/file", "text/plain");
  2524. })
  2525. .Get("/invalid_file_content",
  2526. [&](const Request & /*req*/, Response &res) {
  2527. res.set_file_content("./www/dir/invalid_file_path");
  2528. })
  2529. .Get("/http_response_splitting",
  2530. [&](const Request & /*req*/, Response &res) {
  2531. res.set_header("a", "1\r\nSet-Cookie: a=1");
  2532. EXPECT_EQ(0U, res.headers.size());
  2533. EXPECT_FALSE(res.has_header("a"));
  2534. res.set_header("a", "1\nSet-Cookie: a=1");
  2535. EXPECT_EQ(0U, res.headers.size());
  2536. EXPECT_FALSE(res.has_header("a"));
  2537. res.set_header("a", "1\rSet-Cookie: a=1");
  2538. EXPECT_EQ(0U, res.headers.size());
  2539. EXPECT_FALSE(res.has_header("a"));
  2540. res.set_header("a\r\nb", "0");
  2541. EXPECT_EQ(0U, res.headers.size());
  2542. EXPECT_FALSE(res.has_header("a"));
  2543. res.set_header("a\rb", "0");
  2544. EXPECT_EQ(0U, res.headers.size());
  2545. EXPECT_FALSE(res.has_header("a"));
  2546. res.set_header("a\nb", "0");
  2547. EXPECT_EQ(0U, res.headers.size());
  2548. EXPECT_FALSE(res.has_header("a"));
  2549. res.set_redirect("1\r\nSet-Cookie: a=1");
  2550. EXPECT_EQ(0U, res.headers.size());
  2551. EXPECT_FALSE(res.has_header("Location"));
  2552. })
  2553. .Get("/slow",
  2554. [&](const Request & /*req*/, Response &res) {
  2555. std::this_thread::sleep_for(std::chrono::seconds(2));
  2556. res.set_content("slow", "text/plain");
  2557. })
  2558. #if 0
  2559. .Post("/slowpost",
  2560. [&](const Request & /*req*/, Response &res) {
  2561. std::this_thread::sleep_for(std::chrono::seconds(2));
  2562. res.set_content("slow", "text/plain");
  2563. })
  2564. #endif
  2565. .Get("/remote_addr",
  2566. [&](const Request &req, Response &res) {
  2567. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  2568. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  2569. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  2570. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  2571. res.set_content(req.remote_addr, "text/plain");
  2572. })
  2573. .Get("/local_addr",
  2574. [&](const Request &req, Response &res) {
  2575. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  2576. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  2577. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  2578. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  2579. auto local_addr = req.local_addr;
  2580. auto local_port = std::to_string(req.local_port);
  2581. res.set_content(local_addr.append(":").append(local_port),
  2582. "text/plain");
  2583. })
  2584. .Get("/endwith%",
  2585. [&](const Request & /*req*/, Response &res) {
  2586. res.set_content("Hello World!", "text/plain");
  2587. })
  2588. .Get("/a\\+\\+b",
  2589. [&](const Request &req, Response &res) {
  2590. ASSERT_TRUE(req.has_param("a +b"));
  2591. auto val = req.get_param_value("a +b");
  2592. res.set_content(val, "text/plain");
  2593. })
  2594. .Get("/", [&](const Request & /*req*/,
  2595. Response &res) { res.set_redirect("/hi"); })
  2596. .Post("/1",
  2597. [](const Request & /*req*/, Response &res) {
  2598. res.set_redirect("/2", StatusCode::SeeOther_303);
  2599. })
  2600. .Get("/2",
  2601. [](const Request & /*req*/, Response &res) {
  2602. res.set_content("redirected.", "text/plain");
  2603. res.status = StatusCode::OK_200;
  2604. })
  2605. .Post("/person",
  2606. [&](const Request &req, Response &res) {
  2607. if (req.has_param("name") && req.has_param("note")) {
  2608. persons_[req.get_param_value("name")] =
  2609. req.get_param_value("note");
  2610. } else {
  2611. res.status = StatusCode::BadRequest_400;
  2612. }
  2613. })
  2614. .Put("/person",
  2615. [&](const Request &req, Response &res) {
  2616. if (req.has_param("name") && req.has_param("note")) {
  2617. persons_[req.get_param_value("name")] =
  2618. req.get_param_value("note");
  2619. } else {
  2620. res.status = StatusCode::BadRequest_400;
  2621. }
  2622. })
  2623. .Get("/person/(.*)",
  2624. [&](const Request &req, Response &res) {
  2625. string name = req.matches[1];
  2626. if (persons_.find(name) != persons_.end()) {
  2627. auto note = persons_[name];
  2628. res.set_content(note, "text/plain");
  2629. } else {
  2630. res.status = StatusCode::NotFound_404;
  2631. }
  2632. })
  2633. .Delete("/person",
  2634. [&](const Request &req, Response &res) {
  2635. if (req.has_param("name")) {
  2636. string name = req.get_param_value("name");
  2637. if (persons_.find(name) != persons_.end()) {
  2638. persons_.erase(name);
  2639. res.set_content("DELETED", "text/plain");
  2640. } else {
  2641. res.status = StatusCode::NotFound_404;
  2642. }
  2643. } else {
  2644. res.status = StatusCode::BadRequest_400;
  2645. }
  2646. })
  2647. .Post("/x-www-form-urlencoded-json",
  2648. [&](const Request &req, Response &res) {
  2649. auto json = req.get_param_value("json");
  2650. ASSERT_EQ(JSON_DATA, json);
  2651. res.set_content(json, "appliation/json");
  2652. res.status = StatusCode::OK_200;
  2653. })
  2654. .Get("/streamed-chunked",
  2655. [&](const Request & /*req*/, Response &res) {
  2656. res.set_chunked_content_provider(
  2657. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2658. sink.os << "123";
  2659. sink.os << "456";
  2660. sink.os << "789";
  2661. sink.done();
  2662. return true;
  2663. });
  2664. })
  2665. .Get("/streamed-chunked-with-prohibited-trailer",
  2666. [&](const Request & /*req*/, Response &res) {
  2667. auto i = new int(0);
  2668. // Declare both a prohibited trailer (Content-Length) and an
  2669. // allowed one
  2670. res.set_header("Trailer", "Content-Length, X-Allowed");
  2671. res.set_chunked_content_provider(
  2672. "text/plain",
  2673. [i](size_t /*offset*/, DataSink &sink) {
  2674. switch (*i) {
  2675. case 0: sink.os << "123"; break;
  2676. case 1: sink.os << "456"; break;
  2677. case 2: sink.os << "789"; break;
  2678. case 3: {
  2679. sink.done_with_trailer(
  2680. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  2681. } break;
  2682. }
  2683. (*i)++;
  2684. return true;
  2685. },
  2686. [i](bool success) {
  2687. EXPECT_TRUE(success);
  2688. delete i;
  2689. });
  2690. })
  2691. .Get("/streamed-chunked2",
  2692. [&](const Request & /*req*/, Response &res) {
  2693. auto i = new int(0);
  2694. res.set_chunked_content_provider(
  2695. "text/plain",
  2696. [i](size_t /*offset*/, DataSink &sink) {
  2697. switch (*i) {
  2698. case 0: sink.os << "123"; break;
  2699. case 1: sink.os << "456"; break;
  2700. case 2: sink.os << "789"; break;
  2701. case 3: sink.done(); break;
  2702. }
  2703. (*i)++;
  2704. return true;
  2705. },
  2706. [i](bool success) {
  2707. EXPECT_TRUE(success);
  2708. delete i;
  2709. });
  2710. })
  2711. .Get("/streamed-chunked-with-trailer",
  2712. [&](const Request & /*req*/, Response &res) {
  2713. auto i = new int(0);
  2714. res.set_header("Trailer", "Dummy1, Dummy2");
  2715. res.set_chunked_content_provider(
  2716. "text/plain",
  2717. [i](size_t /*offset*/, DataSink &sink) {
  2718. switch (*i) {
  2719. case 0: sink.os << "123"; break;
  2720. case 1: sink.os << "456"; break;
  2721. case 2: sink.os << "789"; break;
  2722. case 3: {
  2723. sink.done_with_trailer(
  2724. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2725. } break;
  2726. }
  2727. (*i)++;
  2728. return true;
  2729. },
  2730. [i](bool success) {
  2731. EXPECT_TRUE(success);
  2732. delete i;
  2733. });
  2734. })
  2735. .Get("/streamed",
  2736. [&](const Request & /*req*/, Response &res) {
  2737. res.set_content_provider(
  2738. 6, "text/plain",
  2739. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2740. sink.os << (offset < 3 ? "a" : "b");
  2741. return true;
  2742. });
  2743. })
  2744. .Get("/streamed-with-range",
  2745. [&](const Request &req, Response &res) {
  2746. auto data = new std::string("abcdefg");
  2747. res.set_content_provider(
  2748. data->size(), "text/plain",
  2749. [data](size_t offset, size_t length, DataSink &sink) {
  2750. size_t DATA_CHUNK_SIZE = 4;
  2751. const auto &d = *data;
  2752. auto out_len =
  2753. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2754. auto ret =
  2755. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2756. EXPECT_TRUE(ret);
  2757. return true;
  2758. },
  2759. [data, &req](bool success) {
  2760. EXPECT_EQ(success, !req.has_param("error"));
  2761. delete data;
  2762. });
  2763. })
  2764. .Get("/streamed-cancel",
  2765. [&](const Request & /*req*/, Response &res) {
  2766. res.set_content_provider(
  2767. size_t(-1), "text/plain",
  2768. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2769. sink.os << "data_chunk";
  2770. return true;
  2771. });
  2772. })
  2773. .Get("/regex-with-delimiter",
  2774. [&](const Request &req, Response & /*res*/) {
  2775. ASSERT_TRUE(req.has_param("key"));
  2776. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2777. })
  2778. .Get("/with-range",
  2779. [&](const Request & /*req*/, Response &res) {
  2780. res.set_content("abcdefg", "text/plain");
  2781. })
  2782. .Get("/test-start-time",
  2783. [&](const Request &req, Response & /*res*/) {
  2784. EXPECT_NE(req.start_time_,
  2785. std::chrono::steady_clock::time_point::min());
  2786. })
  2787. .Get("/with-range-customized-response",
  2788. [&](const Request & /*req*/, Response &res) {
  2789. res.status = StatusCode::BadRequest_400;
  2790. res.set_content(JSON_DATA, "application/json");
  2791. })
  2792. .Post("/chunked",
  2793. [&](const Request &req, Response & /*res*/) {
  2794. EXPECT_EQ(req.body, "dechunked post body");
  2795. })
  2796. .Post("/large-chunked",
  2797. [&](const Request &req, Response & /*res*/) {
  2798. std::string expected(6 * 30 * 1024u, 'a');
  2799. EXPECT_EQ(req.body, expected);
  2800. })
  2801. .Post("/multipart",
  2802. [&](const Request &req, Response & /*res*/) {
  2803. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  2804. req.form.get_field_count("text2") +
  2805. req.form.get_field_count("file3") +
  2806. req.form.get_field_count("file4"));
  2807. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  2808. req.form.get_file_count("file2"));
  2809. ASSERT_TRUE(!req.form.has_file("???"));
  2810. ASSERT_TRUE(!req.form.has_field("???"));
  2811. ASSERT_TRUE(req.body.empty());
  2812. {
  2813. const auto &text = req.form.get_field("text1");
  2814. EXPECT_EQ("text default", text);
  2815. }
  2816. {
  2817. const auto &text = req.form.get_field("text2");
  2818. EXPECT_EQ("aωb", text);
  2819. }
  2820. {
  2821. const auto &file = req.form.get_file("file1");
  2822. EXPECT_EQ("hello.txt", file.filename);
  2823. EXPECT_EQ("text/plain", file.content_type);
  2824. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2825. }
  2826. {
  2827. const auto &file = req.form.get_file("file2");
  2828. EXPECT_EQ("world.json", file.filename);
  2829. EXPECT_EQ("application/json", file.content_type);
  2830. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  2831. }
  2832. {
  2833. const auto &text = req.form.get_field("file3");
  2834. EXPECT_EQ(0u, text.size());
  2835. }
  2836. {
  2837. const auto &text = req.form.get_field("file4");
  2838. EXPECT_EQ(0u, text.size());
  2839. }
  2840. })
  2841. .Post("/multipart/multi_file_values",
  2842. [&](const Request &req, Response & /*res*/) {
  2843. EXPECT_EQ(3u, req.form.get_field_count("text") +
  2844. req.form.get_field_count("multi_text1"));
  2845. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  2846. ASSERT_TRUE(!req.form.has_file("???"));
  2847. ASSERT_TRUE(!req.form.has_field("???"));
  2848. ASSERT_TRUE(req.body.empty());
  2849. {
  2850. const auto &text = req.form.get_field("text");
  2851. EXPECT_EQ("default text", text);
  2852. }
  2853. {
  2854. const auto &text1_values = req.form.get_fields("multi_text1");
  2855. EXPECT_EQ(2u, text1_values.size());
  2856. EXPECT_EQ("aaaaa", text1_values[0]);
  2857. EXPECT_EQ("bbbbb", text1_values[1]);
  2858. }
  2859. {
  2860. const auto &file1_values = req.form.get_files("multi_file1");
  2861. EXPECT_EQ(2u, file1_values.size());
  2862. auto file1 = file1_values[0];
  2863. EXPECT_EQ(file1.filename, "hello.txt");
  2864. EXPECT_EQ(file1.content_type, "text/plain");
  2865. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2866. auto file2 = file1_values[1];
  2867. EXPECT_EQ(file2.filename, "world.json");
  2868. EXPECT_EQ(file2.content_type, "application/json");
  2869. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2870. }
  2871. })
  2872. .Post("/empty",
  2873. [&](const Request &req, Response &res) {
  2874. EXPECT_EQ(req.body, "");
  2875. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2876. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2877. res.set_content("empty", "text/plain");
  2878. })
  2879. .Post("/empty-no-content-type",
  2880. [&](const Request &req, Response &res) {
  2881. EXPECT_EQ(req.body, "");
  2882. EXPECT_FALSE(req.has_header("Content-Type"));
  2883. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2884. res.set_content("empty-no-content-type", "text/plain");
  2885. })
  2886. .Post("/path-only",
  2887. [&](const Request &req, Response &res) {
  2888. EXPECT_EQ(req.body, "");
  2889. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2890. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2891. res.set_content("path-only", "text/plain");
  2892. })
  2893. .Post("/path-headers-only",
  2894. [&](const Request &req, Response &res) {
  2895. EXPECT_EQ(req.body, "");
  2896. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2897. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2898. EXPECT_EQ("world", req.get_header_value("hello"));
  2899. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2900. res.set_content("path-headers-only", "text/plain");
  2901. })
  2902. .Post("/post-large",
  2903. [&](const Request &req, Response &res) {
  2904. EXPECT_EQ(req.body, LARGE_DATA);
  2905. res.set_content(req.body, "text/plain");
  2906. })
  2907. .Post("/post-loopback",
  2908. [&](const Request &, Response &res,
  2909. ContentReader const &content_reader) {
  2910. std::string body;
  2911. content_reader([&](const char *data, size_t data_length) {
  2912. body.append(data, data_length);
  2913. return true;
  2914. });
  2915. res.set_content(body, "text/plain");
  2916. })
  2917. .Put("/put-loopback",
  2918. [&](const Request &, Response &res,
  2919. ContentReader const &content_reader) {
  2920. std::string body;
  2921. content_reader([&](const char *data, size_t data_length) {
  2922. body.append(data, data_length);
  2923. return true;
  2924. });
  2925. res.set_content(body, "text/plain");
  2926. })
  2927. .Patch("/patch-loopback",
  2928. [&](const Request &, Response &res,
  2929. ContentReader const &content_reader) {
  2930. std::string body;
  2931. content_reader([&](const char *data, size_t data_length) {
  2932. body.append(data, data_length);
  2933. return true;
  2934. });
  2935. res.set_content(body, "text/plain");
  2936. })
  2937. .Put("/empty-no-content-type",
  2938. [&](const Request &req, Response &res) {
  2939. EXPECT_EQ(req.body, "");
  2940. EXPECT_FALSE(req.has_header("Content-Type"));
  2941. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2942. res.set_content("empty-no-content-type", "text/plain");
  2943. })
  2944. .Put("/put",
  2945. [&](const Request &req, Response &res) {
  2946. EXPECT_EQ(req.body, "PUT");
  2947. res.set_content(req.body, "text/plain");
  2948. })
  2949. .Put("/put-large",
  2950. [&](const Request &req, Response &res) {
  2951. EXPECT_EQ(req.body, LARGE_DATA);
  2952. res.set_content(req.body, "text/plain");
  2953. })
  2954. .Patch("/patch",
  2955. [&](const Request &req, Response &res) {
  2956. EXPECT_EQ(req.body, "PATCH");
  2957. res.set_content(req.body, "text/plain");
  2958. })
  2959. .Delete("/delete",
  2960. [&](const Request & /*req*/, Response &res) {
  2961. res.set_content("DELETE", "text/plain");
  2962. })
  2963. .Delete("/delete-body",
  2964. [&](const Request &req, Response &res) {
  2965. EXPECT_EQ(req.body, "content");
  2966. res.set_content(req.body, "text/plain");
  2967. })
  2968. .Options(R"(\*)",
  2969. [&](const Request & /*req*/, Response &res) {
  2970. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2971. })
  2972. .Get("/request-target",
  2973. [&](const Request &req, Response & /*res*/) {
  2974. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2975. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2976. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2977. })
  2978. .Get("/long-query-value",
  2979. [&](const Request &req, Response & /*res*/) {
  2980. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2981. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2982. })
  2983. .Get("/too-long-query-value",
  2984. [&](const Request &req, Response & /*res*/) {
  2985. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  2986. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  2987. })
  2988. .Get("/array-param",
  2989. [&](const Request &req, Response & /*res*/) {
  2990. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2991. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2992. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2993. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2994. })
  2995. .Post("/validate-no-multiple-headers",
  2996. [&](const Request &req, Response & /*res*/) {
  2997. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2998. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2999. })
  3000. .Post("/content_receiver",
  3001. [&](const Request &req, Response &res,
  3002. const ContentReader &content_reader) {
  3003. if (req.is_multipart_form_data()) {
  3004. std::vector<FormData> items;
  3005. content_reader(
  3006. [&](const FormData &file) {
  3007. items.push_back(file);
  3008. return true;
  3009. },
  3010. [&](const char *data, size_t data_length) {
  3011. items.back().content.append(data, data_length);
  3012. return true;
  3013. });
  3014. EXPECT_EQ(5u, items.size());
  3015. {
  3016. const auto &file = get_file_value(items, "text1");
  3017. EXPECT_TRUE(file.filename.empty());
  3018. EXPECT_EQ("text default", file.content);
  3019. }
  3020. {
  3021. const auto &file = get_file_value(items, "text2");
  3022. EXPECT_TRUE(file.filename.empty());
  3023. EXPECT_EQ("aωb", file.content);
  3024. }
  3025. {
  3026. const auto &file = get_file_value(items, "file1");
  3027. EXPECT_EQ("hello.txt", file.filename);
  3028. EXPECT_EQ("text/plain", file.content_type);
  3029. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  3030. }
  3031. {
  3032. const auto &file = get_file_value(items, "file2");
  3033. EXPECT_EQ("world.json", file.filename);
  3034. EXPECT_EQ("application/json", file.content_type);
  3035. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  3036. }
  3037. {
  3038. const auto &file = get_file_value(items, "file3");
  3039. EXPECT_TRUE(file.filename.empty());
  3040. EXPECT_EQ("application/octet-stream", file.content_type);
  3041. EXPECT_EQ(0u, file.content.size());
  3042. }
  3043. } else {
  3044. std::string body;
  3045. content_reader([&](const char *data, size_t data_length) {
  3046. EXPECT_EQ(7U, data_length);
  3047. body.append(data, data_length);
  3048. return true;
  3049. });
  3050. EXPECT_EQ(body, "content");
  3051. res.set_content(body, "text/plain");
  3052. }
  3053. })
  3054. .Put("/content_receiver",
  3055. [&](const Request & /*req*/, Response &res,
  3056. const ContentReader &content_reader) {
  3057. std::string body;
  3058. content_reader([&](const char *data, size_t data_length) {
  3059. body.append(data, data_length);
  3060. return true;
  3061. });
  3062. EXPECT_EQ(body, "content");
  3063. res.set_content(body, "text/plain");
  3064. })
  3065. .Patch("/content_receiver",
  3066. [&](const Request & /*req*/, Response &res,
  3067. const ContentReader &content_reader) {
  3068. std::string body;
  3069. content_reader([&](const char *data, size_t data_length) {
  3070. body.append(data, data_length);
  3071. return true;
  3072. });
  3073. EXPECT_EQ(body, "content");
  3074. res.set_content(body, "text/plain");
  3075. })
  3076. .Post("/query-string-and-body",
  3077. [&](const Request &req, Response & /*res*/) {
  3078. ASSERT_TRUE(req.has_param("key"));
  3079. EXPECT_EQ(req.get_param_value("key"), "value");
  3080. EXPECT_EQ(req.body, "content");
  3081. })
  3082. .Get("/last-request",
  3083. [&](const Request &req, Response & /*res*/) {
  3084. EXPECT_EQ("close", req.get_header_value("Connection"));
  3085. })
  3086. .Get(R"(/redirect/(\d+))",
  3087. [&](const Request &req, Response &res) {
  3088. auto num = std::stoi(req.matches[1]) + 1;
  3089. std::string url = "/redirect/" + std::to_string(num);
  3090. res.set_redirect(url);
  3091. })
  3092. .Post("/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. .Put("/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. .Patch("/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. .Delete("/binary",
  3117. [&](const Request &req, Response &res) {
  3118. EXPECT_EQ(4U, req.body.size());
  3119. EXPECT_EQ("application/octet-stream",
  3120. req.get_header_value("Content-Type"));
  3121. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  3122. res.set_content(req.body, "application/octet-stream");
  3123. })
  3124. .Get("/issue1772",
  3125. [&](const Request & /*req*/, Response &res) {
  3126. res.status = 401;
  3127. res.set_header("WWW-Authenticate", "Basic realm=123456");
  3128. })
  3129. .Delete("/issue609",
  3130. [](const httplib::Request &, httplib::Response &res,
  3131. const httplib::ContentReader &) {
  3132. res.set_content("ok", "text/plain");
  3133. })
  3134. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  3135. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  3136. .Get("/compress",
  3137. [&](const Request & /*req*/, Response &res) {
  3138. res.set_content(
  3139. "12345678901234567890123456789012345678901234567890123456789"
  3140. "01234567890123456789012345678901234567890",
  3141. "text/plain");
  3142. })
  3143. .Get("/nocompress",
  3144. [&](const Request & /*req*/, Response &res) {
  3145. res.set_content(
  3146. "12345678901234567890123456789012345678901234567890123456789"
  3147. "01234567890123456789012345678901234567890",
  3148. "application/octet-stream");
  3149. })
  3150. .Post("/compress-multipart",
  3151. [&](const Request &req, Response & /*res*/) {
  3152. EXPECT_EQ(2u, req.form.fields.size());
  3153. ASSERT_TRUE(!req.form.has_field("???"));
  3154. {
  3155. const auto &text = req.form.get_field("key1");
  3156. EXPECT_EQ("test", text);
  3157. }
  3158. {
  3159. const auto &text = req.form.get_field("key2");
  3160. EXPECT_EQ("--abcdefg123", text);
  3161. }
  3162. })
  3163. #endif
  3164. ;
  3165. persons_["john"] = "programmer";
  3166. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3167. svr_.wait_until_ready();
  3168. }
  3169. virtual void TearDown() {
  3170. svr_.stop();
  3171. if (!request_threads_.empty()) {
  3172. std::this_thread::sleep_for(std::chrono::seconds(1));
  3173. for (auto &t : request_threads_) {
  3174. t.join();
  3175. }
  3176. }
  3177. t_.join();
  3178. }
  3179. map<string, string> persons_;
  3180. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3181. SSLClient cli_;
  3182. SSLServer svr_;
  3183. #else
  3184. Client cli_;
  3185. Server svr_;
  3186. #endif
  3187. thread t_;
  3188. std::vector<thread> request_threads_;
  3189. };
  3190. TEST_F(ServerTest, GetMethod200) {
  3191. auto res = cli_.Get("/hi");
  3192. ASSERT_TRUE(res);
  3193. EXPECT_EQ("HTTP/1.1", res->version);
  3194. EXPECT_EQ(StatusCode::OK_200, res->status);
  3195. EXPECT_EQ("OK", res->reason);
  3196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3197. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3198. EXPECT_EQ("Hello World!", res->body);
  3199. }
  3200. TEST_F(ServerTest, GetEmptyFile) {
  3201. auto res = cli_.Get("/empty_file");
  3202. ASSERT_TRUE(res);
  3203. EXPECT_EQ(StatusCode::OK_200, res->status);
  3204. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3205. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  3206. EXPECT_EQ("", res->body);
  3207. }
  3208. TEST_F(ServerTest, GetFileContent) {
  3209. auto res = cli_.Get("/file_content");
  3210. ASSERT_TRUE(res);
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3213. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  3214. EXPECT_EQ("test.html", res->body);
  3215. }
  3216. TEST_F(ServerTest, GetFileContentWithRange) {
  3217. auto res = cli_.Get("/file_content", {{make_range_header({{1, 3}})}});
  3218. ASSERT_TRUE(res);
  3219. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3220. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3221. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  3222. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  3223. EXPECT_EQ("est", res->body);
  3224. }
  3225. TEST_F(ServerTest, GetFileContentWithContentType) {
  3226. auto res = cli_.Get("/file_content_with_content_type");
  3227. ASSERT_TRUE(res);
  3228. EXPECT_EQ(StatusCode::OK_200, res->status);
  3229. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3230. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  3231. EXPECT_EQ("file\n", res->body);
  3232. }
  3233. TEST_F(ServerTest, GetInvalidFileContent) {
  3234. auto res = cli_.Get("/invalid_file_content");
  3235. ASSERT_TRUE(res);
  3236. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3237. }
  3238. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  3239. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  3240. ASSERT_TRUE(res);
  3241. EXPECT_EQ("HTTP/1.1", res->version);
  3242. EXPECT_EQ(StatusCode::OK_200, res->status);
  3243. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3244. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  3245. EXPECT_EQ("Hello World!", res->body);
  3246. }
  3247. TEST_F(ServerTest, GetMethod302) {
  3248. auto res = cli_.Get("/");
  3249. ASSERT_TRUE(res);
  3250. EXPECT_EQ(StatusCode::Found_302, res->status);
  3251. EXPECT_EQ("/hi", res->get_header_value("Location"));
  3252. }
  3253. TEST_F(ServerTest, GetMethod302Redirect) {
  3254. cli_.set_follow_location(true);
  3255. auto res = cli_.Get("/");
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::OK_200, res->status);
  3258. EXPECT_EQ("Hello World!", res->body);
  3259. EXPECT_EQ("/hi", res->location);
  3260. }
  3261. TEST_F(ServerTest, GetMethod404) {
  3262. auto res = cli_.Get("/invalid");
  3263. ASSERT_TRUE(res);
  3264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3265. }
  3266. TEST_F(ServerTest, HeadMethod200) {
  3267. auto res = cli_.Head("/hi");
  3268. ASSERT_TRUE(res);
  3269. EXPECT_EQ(StatusCode::OK_200, res->status);
  3270. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3271. EXPECT_TRUE(res->body.empty());
  3272. }
  3273. TEST_F(ServerTest, HeadMethod200Static) {
  3274. auto res = cli_.Head("/mount/dir/index.html");
  3275. ASSERT_TRUE(res);
  3276. EXPECT_EQ(StatusCode::OK_200, res->status);
  3277. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3278. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  3279. EXPECT_TRUE(res->body.empty());
  3280. }
  3281. TEST_F(ServerTest, HeadMethod404) {
  3282. auto res = cli_.Head("/invalid");
  3283. ASSERT_TRUE(res);
  3284. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3285. EXPECT_TRUE(res->body.empty());
  3286. }
  3287. TEST_F(ServerTest, GetMethodPersonJohn) {
  3288. auto res = cli_.Get("/person/john");
  3289. ASSERT_TRUE(res);
  3290. EXPECT_EQ(StatusCode::OK_200, res->status);
  3291. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3292. EXPECT_EQ("programmer", res->body);
  3293. }
  3294. TEST_F(ServerTest, PostMethod1) {
  3295. auto res = cli_.Get("/person/john1");
  3296. ASSERT_TRUE(res);
  3297. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3298. res = cli_.Post("/person", "name=john1&note=coder",
  3299. "application/x-www-form-urlencoded");
  3300. ASSERT_TRUE(res);
  3301. ASSERT_EQ(StatusCode::OK_200, res->status);
  3302. res = cli_.Get("/person/john1");
  3303. ASSERT_TRUE(res);
  3304. ASSERT_EQ(StatusCode::OK_200, res->status);
  3305. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3306. ASSERT_EQ("coder", res->body);
  3307. }
  3308. TEST_F(ServerTest, PostMethod2) {
  3309. auto res = cli_.Get("/person/john2");
  3310. ASSERT_TRUE(res);
  3311. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3312. Params params;
  3313. params.emplace("name", "john2");
  3314. params.emplace("note", "coder");
  3315. res = cli_.Post("/person", params);
  3316. ASSERT_TRUE(res);
  3317. ASSERT_EQ(StatusCode::OK_200, res->status);
  3318. res = cli_.Get("/person/john2");
  3319. ASSERT_TRUE(res);
  3320. ASSERT_EQ(StatusCode::OK_200, res->status);
  3321. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3322. ASSERT_EQ("coder", res->body);
  3323. }
  3324. TEST_F(ServerTest, PutMethod3) {
  3325. auto res = cli_.Get("/person/john3");
  3326. ASSERT_TRUE(res);
  3327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3328. Params params;
  3329. params.emplace("name", "john3");
  3330. params.emplace("note", "coder");
  3331. res = cli_.Put("/person", params);
  3332. ASSERT_TRUE(res);
  3333. ASSERT_EQ(StatusCode::OK_200, res->status);
  3334. res = cli_.Get("/person/john3");
  3335. ASSERT_TRUE(res);
  3336. ASSERT_EQ(StatusCode::OK_200, res->status);
  3337. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3338. ASSERT_EQ("coder", res->body);
  3339. }
  3340. TEST_F(ServerTest, DeleteMethod1) {
  3341. auto res = cli_.Get("/person/john4");
  3342. ASSERT_TRUE(res);
  3343. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3344. Params params;
  3345. params.emplace("name", "john4");
  3346. params.emplace("note", "coder");
  3347. res = cli_.Post("/person", params);
  3348. ASSERT_TRUE(res);
  3349. ASSERT_EQ(StatusCode::OK_200, res->status);
  3350. res = cli_.Get("/person/john4");
  3351. ASSERT_TRUE(res);
  3352. ASSERT_EQ(StatusCode::OK_200, res->status);
  3353. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3354. ASSERT_EQ("coder", res->body);
  3355. Params delete_params;
  3356. delete_params.emplace("name", "john4");
  3357. res = cli_.Delete("/person", delete_params);
  3358. ASSERT_TRUE(res);
  3359. ASSERT_EQ(StatusCode::OK_200, res->status);
  3360. ASSERT_EQ("DELETED", res->body);
  3361. res = cli_.Get("/person/john4");
  3362. ASSERT_TRUE(res);
  3363. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3364. }
  3365. TEST_F(ServerTest, DeleteMethod2) {
  3366. auto res = cli_.Get("/person/john5");
  3367. ASSERT_TRUE(res);
  3368. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3369. Params params;
  3370. params.emplace("name", "john5");
  3371. params.emplace("note", "developer");
  3372. res = cli_.Post("/person", params);
  3373. ASSERT_TRUE(res);
  3374. ASSERT_EQ(StatusCode::OK_200, res->status);
  3375. res = cli_.Get("/person/john5");
  3376. ASSERT_TRUE(res);
  3377. ASSERT_EQ(StatusCode::OK_200, res->status);
  3378. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3379. ASSERT_EQ("developer", res->body);
  3380. Params delete_params;
  3381. delete_params.emplace("name", "john5");
  3382. Headers headers;
  3383. headers.emplace("Custom-Header", "test-value");
  3384. res = cli_.Delete("/person", headers, delete_params);
  3385. ASSERT_TRUE(res);
  3386. ASSERT_EQ(StatusCode::OK_200, res->status);
  3387. ASSERT_EQ("DELETED", res->body);
  3388. res = cli_.Get("/person/john5");
  3389. ASSERT_TRUE(res);
  3390. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3391. }
  3392. TEST_F(ServerTest, DeleteMethod3) {
  3393. auto res = cli_.Get("/person/john6");
  3394. ASSERT_TRUE(res);
  3395. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3396. Params params;
  3397. params.emplace("name", "john6");
  3398. params.emplace("note", "tester");
  3399. res = cli_.Post("/person", params);
  3400. ASSERT_TRUE(res);
  3401. ASSERT_EQ(StatusCode::OK_200, res->status);
  3402. res = cli_.Get("/person/john6");
  3403. ASSERT_TRUE(res);
  3404. ASSERT_EQ(StatusCode::OK_200, res->status);
  3405. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  3406. ASSERT_EQ("tester", res->body);
  3407. Params delete_params;
  3408. delete_params.emplace("name", "john6");
  3409. Headers headers;
  3410. headers.emplace("Custom-Header", "test-value");
  3411. res = cli_.Delete("/person", headers, delete_params, nullptr);
  3412. ASSERT_TRUE(res);
  3413. ASSERT_EQ(StatusCode::OK_200, res->status);
  3414. ASSERT_EQ("DELETED", res->body);
  3415. res = cli_.Get("/person/john6");
  3416. ASSERT_TRUE(res);
  3417. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  3418. }
  3419. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  3420. Params params;
  3421. params.emplace("json", JSON_DATA);
  3422. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  3423. ASSERT_TRUE(res);
  3424. ASSERT_EQ(StatusCode::OK_200, res->status);
  3425. ASSERT_EQ(JSON_DATA, res->body);
  3426. }
  3427. TEST_F(ServerTest, PostEmptyContent) {
  3428. auto res = cli_.Post("/empty", "", "text/plain");
  3429. ASSERT_TRUE(res);
  3430. ASSERT_EQ(StatusCode::OK_200, res->status);
  3431. ASSERT_EQ("empty", res->body);
  3432. }
  3433. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  3434. auto res = cli_.Post("/empty-no-content-type");
  3435. ASSERT_TRUE(res);
  3436. ASSERT_EQ(StatusCode::OK_200, res->status);
  3437. ASSERT_EQ("empty-no-content-type", res->body);
  3438. }
  3439. TEST_F(ServerTest, PostPathOnly) {
  3440. auto res = cli_.Post("/path-only");
  3441. ASSERT_TRUE(res);
  3442. ASSERT_EQ(StatusCode::OK_200, res->status);
  3443. ASSERT_EQ("path-only", res->body);
  3444. }
  3445. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  3446. auto res = cli_.Post("/path-headers-only",
  3447. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  3448. ASSERT_TRUE(res);
  3449. ASSERT_EQ(StatusCode::OK_200, res->status);
  3450. ASSERT_EQ("path-headers-only", res->body);
  3451. }
  3452. TEST_F(ServerTest, PostLarge) {
  3453. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  3454. ASSERT_TRUE(res);
  3455. ASSERT_EQ(StatusCode::OK_200, res->status);
  3456. EXPECT_EQ(LARGE_DATA, res->body);
  3457. }
  3458. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  3459. auto res = cli_.Put("/empty-no-content-type");
  3460. ASSERT_TRUE(res);
  3461. ASSERT_EQ(StatusCode::OK_200, res->status);
  3462. ASSERT_EQ("empty-no-content-type", res->body);
  3463. }
  3464. TEST_F(ServerTest, GetMethodDir) {
  3465. auto res = cli_.Get("/dir/");
  3466. ASSERT_TRUE(res);
  3467. EXPECT_EQ(StatusCode::OK_200, res->status);
  3468. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3469. auto body = R"(<html>
  3470. <head>
  3471. </head>
  3472. <body>
  3473. <a href="/dir/test.html">Test</a>
  3474. <a href="/hi">hi</a>
  3475. </body>
  3476. </html>
  3477. )";
  3478. EXPECT_EQ(body, res->body);
  3479. }
  3480. TEST_F(ServerTest, GetMethodDirTest) {
  3481. auto res = cli_.Get("/dir/test.html");
  3482. ASSERT_TRUE(res);
  3483. EXPECT_EQ(StatusCode::OK_200, res->status);
  3484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3485. EXPECT_EQ("test.html", res->body);
  3486. }
  3487. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  3488. auto res = cli_.Get("/dir/../dir/test.html");
  3489. ASSERT_TRUE(res);
  3490. EXPECT_EQ(StatusCode::OK_200, res->status);
  3491. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3492. EXPECT_EQ("test.html", res->body);
  3493. }
  3494. TEST_F(ServerTest, GetMethodInvalidPath) {
  3495. auto res = cli_.Get("/dir/../test.html");
  3496. ASSERT_TRUE(res);
  3497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3498. }
  3499. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  3500. auto res = cli_.Get("/../www/dir/test.html");
  3501. ASSERT_TRUE(res);
  3502. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3503. }
  3504. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  3505. auto res = cli_.Get("/dir/../../www/dir/test.html");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3508. }
  3509. TEST_F(ServerTest, GetMethodDirMountTest) {
  3510. auto res = cli_.Get("/mount/dir/test.html");
  3511. ASSERT_TRUE(res);
  3512. EXPECT_EQ(StatusCode::OK_200, res->status);
  3513. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3514. EXPECT_EQ("test.html", res->body);
  3515. }
  3516. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  3517. auto res = cli_.Get("/mount/dir/../dir/test.html");
  3518. ASSERT_TRUE(res);
  3519. EXPECT_EQ(StatusCode::OK_200, res->status);
  3520. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3521. EXPECT_EQ("test.html", res->body);
  3522. }
  3523. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  3524. auto res = cli_.Get("/mount/dir/../test.html");
  3525. ASSERT_TRUE(res);
  3526. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3527. }
  3528. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  3529. auto res = cli_.Get("/mount/dir/test.html%00.js");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3532. }
  3533. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  3534. auto res = cli_.Get("/mount/../www2/dir/test.html");
  3535. ASSERT_TRUE(res);
  3536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3537. }
  3538. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  3539. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  3540. ASSERT_TRUE(res);
  3541. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3542. }
  3543. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  3544. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  3545. ASSERT_TRUE(res);
  3546. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3547. }
  3548. TEST_F(ServerTest, PostMethod303) {
  3549. auto res = cli_.Post("/1", "body", "text/plain");
  3550. ASSERT_TRUE(res);
  3551. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  3552. EXPECT_EQ("/2", res->get_header_value("Location"));
  3553. }
  3554. TEST_F(ServerTest, PostMethod303Redirect) {
  3555. cli_.set_follow_location(true);
  3556. auto res = cli_.Post("/1", "body", "text/plain");
  3557. ASSERT_TRUE(res);
  3558. EXPECT_EQ(StatusCode::OK_200, res->status);
  3559. EXPECT_EQ("redirected.", res->body);
  3560. EXPECT_EQ("/2", res->location);
  3561. }
  3562. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  3563. auto res = cli_.Get("/dir/test.abcde");
  3564. ASSERT_TRUE(res);
  3565. EXPECT_EQ(StatusCode::OK_200, res->status);
  3566. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3567. EXPECT_EQ("abcde", res->body);
  3568. }
  3569. TEST_F(ServerTest, StaticFileRange) {
  3570. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3571. ASSERT_TRUE(res);
  3572. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3573. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3574. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3575. EXPECT_EQ(true, res->has_header("Content-Range"));
  3576. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3577. EXPECT_EQ(std::string("cd"), res->body);
  3578. }
  3579. TEST_F(ServerTest, StaticFileRanges) {
  3580. auto res =
  3581. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  3582. ASSERT_TRUE(res);
  3583. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3584. EXPECT_TRUE(
  3585. res->get_header_value("Content-Type")
  3586. .find(
  3587. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  3588. 0);
  3589. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  3590. }
  3591. TEST_F(ServerTest, StaticFileRangeHead) {
  3592. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  3593. ASSERT_TRUE(res);
  3594. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3595. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  3596. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3597. EXPECT_EQ(true, res->has_header("Content-Range"));
  3598. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  3599. }
  3600. TEST_F(ServerTest, StaticFileRangeBigFile) {
  3601. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  3602. ASSERT_TRUE(res);
  3603. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3605. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  3606. EXPECT_EQ(true, res->has_header("Content-Range"));
  3607. EXPECT_EQ("bytes 1048571-1048575/1048576",
  3608. res->get_header_value("Content-Range"));
  3609. EXPECT_EQ("LAST\n", res->body);
  3610. }
  3611. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  3612. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  3613. ASSERT_TRUE(res);
  3614. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3615. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3616. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  3617. EXPECT_EQ(true, res->has_header("Content-Range"));
  3618. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  3619. }
  3620. TEST_F(ServerTest, StaticFileBigFile) {
  3621. auto res = cli_.Get("/dir/1MB.txt");
  3622. ASSERT_TRUE(res);
  3623. EXPECT_EQ(StatusCode::OK_200, res->status);
  3624. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3625. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  3626. }
  3627. TEST_F(ServerTest, InvalidBaseDirMount) {
  3628. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  3629. }
  3630. TEST_F(ServerTest, Binary) {
  3631. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  3632. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  3633. "application/octet-stream");
  3634. ASSERT_TRUE(res);
  3635. ASSERT_EQ(StatusCode::OK_200, res->status);
  3636. ASSERT_EQ(4U, res->body.size());
  3637. res = cli_.Put("/binary", binary.data(), binary.size(),
  3638. "application/octet-stream");
  3639. ASSERT_TRUE(res);
  3640. ASSERT_EQ(StatusCode::OK_200, res->status);
  3641. ASSERT_EQ(4U, res->body.size());
  3642. res = cli_.Patch("/binary", binary.data(), binary.size(),
  3643. "application/octet-stream");
  3644. ASSERT_TRUE(res);
  3645. ASSERT_EQ(StatusCode::OK_200, res->status);
  3646. ASSERT_EQ(4U, res->body.size());
  3647. res = cli_.Delete("/binary", binary.data(), binary.size(),
  3648. "application/octet-stream");
  3649. ASSERT_TRUE(res);
  3650. ASSERT_EQ(StatusCode::OK_200, res->status);
  3651. ASSERT_EQ(4U, res->body.size());
  3652. }
  3653. TEST_F(ServerTest, BinaryString) {
  3654. auto binary = std::string("\x00\x01\x02\x03", 4);
  3655. auto res = cli_.Post("/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_.Put("/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. res = cli_.Patch("/binary", binary, "application/octet-stream");
  3664. ASSERT_TRUE(res);
  3665. ASSERT_EQ(StatusCode::OK_200, res->status);
  3666. ASSERT_EQ(4U, res->body.size());
  3667. res = cli_.Delete("/binary", binary, "application/octet-stream");
  3668. ASSERT_TRUE(res);
  3669. ASSERT_EQ(StatusCode::OK_200, res->status);
  3670. ASSERT_EQ(4U, res->body.size());
  3671. }
  3672. TEST_F(ServerTest, EmptyRequest) {
  3673. auto res = cli_.Get("");
  3674. ASSERT_TRUE(!res);
  3675. EXPECT_EQ(Error::Connection, res.error());
  3676. }
  3677. TEST_F(ServerTest, LongRequest) {
  3678. std::string request;
  3679. for (size_t i = 0; i < 545; i++) {
  3680. request += "/TooLongRequest";
  3681. }
  3682. request += "OK";
  3683. auto res = cli_.Get(request.c_str());
  3684. ASSERT_TRUE(res);
  3685. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3686. }
  3687. TEST_F(ServerTest, TooLongRequest) {
  3688. std::string request;
  3689. for (size_t i = 0; i < 546; i++) {
  3690. request += "/TooLongRequest";
  3691. }
  3692. request += "_NG";
  3693. auto start = std::chrono::high_resolution_clock::now();
  3694. cli_.set_keep_alive(true);
  3695. auto res = cli_.Get(request.c_str());
  3696. auto end = std::chrono::high_resolution_clock::now();
  3697. auto elapsed =
  3698. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3699. .count();
  3700. ASSERT_TRUE(res);
  3701. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3702. EXPECT_LE(elapsed, 100);
  3703. EXPECT_EQ("close", res->get_header_value("Connection"));
  3704. EXPECT_FALSE(cli_.is_socket_open());
  3705. }
  3706. TEST_F(ServerTest, AlmostTooLongRequest) {
  3707. // test for #2046 - URI length check shouldn't include other content on req
  3708. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  3709. // leading /, space, HTTP/1.1)
  3710. std::string request =
  3711. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  3712. auto res = cli_.Get(request.c_str());
  3713. ASSERT_TRUE(res);
  3714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3715. }
  3716. TEST_F(ServerTest, LongHeader) {
  3717. Request req;
  3718. req.method = "GET";
  3719. req.path = "/hi";
  3720. std::string host_and_port;
  3721. host_and_port += HOST;
  3722. host_and_port += ":";
  3723. host_and_port += std::to_string(PORT);
  3724. req.headers.emplace("Host", host_and_port.c_str());
  3725. req.headers.emplace("Accept", "*/*");
  3726. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3727. req.headers.emplace(
  3728. "Header-Name",
  3729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3757. "@@@@@@@@@@@@@@@@");
  3758. auto res = std::make_shared<Response>();
  3759. auto error = Error::Success;
  3760. auto ret = cli_.send(req, *res, error);
  3761. ASSERT_TRUE(ret);
  3762. EXPECT_EQ(StatusCode::OK_200, res->status);
  3763. }
  3764. TEST_F(ServerTest, LongQueryValue) {
  3765. auto start = std::chrono::high_resolution_clock::now();
  3766. cli_.set_keep_alive(true);
  3767. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  3768. auto end = std::chrono::high_resolution_clock::now();
  3769. auto elapsed =
  3770. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  3771. .count();
  3772. ASSERT_TRUE(res);
  3773. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  3774. EXPECT_LE(elapsed, 100);
  3775. EXPECT_EQ("close", res->get_header_value("Connection"));
  3776. EXPECT_FALSE(cli_.is_socket_open());
  3777. }
  3778. TEST_F(ServerTest, TooLongQueryValue) {
  3779. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  3780. ASSERT_FALSE(res);
  3781. EXPECT_EQ(Error::Read, res.error());
  3782. }
  3783. TEST_F(ServerTest, TooLongHeader) {
  3784. Request req;
  3785. req.method = "GET";
  3786. req.path = "/hi";
  3787. std::string host_and_port;
  3788. host_and_port += HOST;
  3789. host_and_port += ":";
  3790. host_and_port += std::to_string(PORT);
  3791. req.headers.emplace("Host", host_and_port.c_str());
  3792. req.headers.emplace("Accept", "*/*");
  3793. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3794. req.headers.emplace(
  3795. "Header-Name",
  3796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3808. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3809. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3810. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3811. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3812. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3813. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3814. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3815. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3816. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3817. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3818. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3819. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3820. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3821. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3822. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3823. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  3824. "@@@@@@@@@@@@@@@@@");
  3825. auto res = std::make_shared<Response>();
  3826. auto error = Error::Success;
  3827. auto ret = cli_.send(req, *res, error);
  3828. ASSERT_TRUE(ret);
  3829. EXPECT_EQ(StatusCode::OK_200, res->status);
  3830. }
  3831. TEST_F(ServerTest, HeaderCountAtLimit) {
  3832. // Test with headers just under the 100 limit
  3833. httplib::Headers headers;
  3834. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  3835. // This should keep us just under the 100 header limit
  3836. for (int i = 0; i < 95; i++) {
  3837. std::string name = "X-Test-Header-" + std::to_string(i);
  3838. std::string value = "value" + std::to_string(i);
  3839. headers.emplace(name, value);
  3840. }
  3841. // This should work fine as we're under the limit
  3842. auto res = cli_.Get("/hi", headers);
  3843. EXPECT_TRUE(res);
  3844. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  3845. }
  3846. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  3847. // Test with many headers to exceed the 100 limit
  3848. httplib::Headers headers;
  3849. // Add 150 headers to definitely exceed the 100 limit
  3850. for (int i = 0; i < 150; i++) {
  3851. std::string name = "X-Test-Header-" + std::to_string(i);
  3852. std::string value = "value" + std::to_string(i);
  3853. headers.emplace(name, value);
  3854. }
  3855. // This should fail due to exceeding header count limit
  3856. cli_.set_keep_alive(true);
  3857. auto res = cli_.Get("/hi", headers);
  3858. // The request should either fail or return 400 Bad Request
  3859. if (res) {
  3860. // If we get a response, it should be 400 Bad Request
  3861. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3862. } else {
  3863. // Or the request should fail entirely
  3864. EXPECT_FALSE(res);
  3865. }
  3866. EXPECT_EQ("close", res->get_header_value("Connection"));
  3867. EXPECT_FALSE(cli_.is_socket_open());
  3868. }
  3869. TEST_F(ServerTest, PercentEncoding) {
  3870. auto res = cli_.Get("/e%6edwith%");
  3871. ASSERT_TRUE(res);
  3872. EXPECT_EQ(StatusCode::OK_200, res->status);
  3873. }
  3874. TEST_F(ServerTest, PercentEncodingUnicode) {
  3875. auto res = cli_.Get("/e%u006edwith%");
  3876. ASSERT_TRUE(res);
  3877. EXPECT_EQ(StatusCode::OK_200, res->status);
  3878. }
  3879. TEST_F(ServerTest, InvalidPercentEncoding) {
  3880. auto res = cli_.Get("/%endwith%");
  3881. ASSERT_TRUE(res);
  3882. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3883. }
  3884. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  3885. auto res = cli_.Get("/%uendwith%");
  3886. ASSERT_TRUE(res);
  3887. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3888. }
  3889. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  3890. auto res = cli_.Get("/hello?aaa=bbb%");
  3891. ASSERT_TRUE(res);
  3892. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3893. }
  3894. TEST_F(ServerTest, PlusSignEncoding) {
  3895. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  3896. ASSERT_TRUE(res);
  3897. EXPECT_EQ(StatusCode::OK_200, res->status);
  3898. EXPECT_EQ("a +b", res->body);
  3899. }
  3900. TEST_F(ServerTest, HeaderCountSecurityTest) {
  3901. // This test simulates a potential DoS attack using many headers
  3902. // to verify our security fix prevents memory exhaustion
  3903. httplib::Headers attack_headers;
  3904. // Attempt to add many headers like an attacker would (200 headers to far
  3905. // exceed limit)
  3906. for (int i = 0; i < 200; i++) {
  3907. std::string name = "X-Attack-Header-" + std::to_string(i);
  3908. std::string value = "attack_payload_" + std::to_string(i);
  3909. attack_headers.emplace(name, value);
  3910. }
  3911. // Try to POST with excessive headers
  3912. cli_.set_keep_alive(true);
  3913. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  3914. // Should either fail or return 400 Bad Request due to security limit
  3915. if (res) {
  3916. // If we get a response, it should be 400 Bad Request
  3917. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3918. } else {
  3919. // Request failed, which is the expected behavior for DoS protection
  3920. EXPECT_FALSE(res);
  3921. }
  3922. EXPECT_EQ("close", res->get_header_value("Connection"));
  3923. EXPECT_FALSE(cli_.is_socket_open());
  3924. }
  3925. TEST_F(ServerTest, MultipartFormData) {
  3926. UploadFormDataItems items = {
  3927. {"text1", "text default", "", ""},
  3928. {"text2", "aωb", "", ""},
  3929. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3930. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3931. {"file3", "", "", "application/octet-stream"},
  3932. {"file4", "", "", " application/json tmp-string "}};
  3933. auto res = cli_.Post("/multipart", items);
  3934. ASSERT_TRUE(res);
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3938. UploadFormDataItems items = {
  3939. {"text", "default text", "", ""},
  3940. {"multi_text1", "aaaaa", "", ""},
  3941. {"multi_text1", "bbbbb", "", ""},
  3942. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3943. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3944. "application/json"},
  3945. };
  3946. auto res = cli_.Post("/multipart/multi_file_values", items);
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(StatusCode::OK_200, res->status);
  3949. }
  3950. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3951. auto res = cli_.Get("/hi");
  3952. ASSERT_TRUE(res);
  3953. EXPECT_EQ(StatusCode::OK_200, res->status);
  3954. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3955. EXPECT_EQ("Hello World!", res->body);
  3956. }
  3957. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3958. Request req;
  3959. req.method = "POST";
  3960. req.path = "/chunked";
  3961. std::string host_and_port;
  3962. host_and_port += HOST;
  3963. host_and_port += ":";
  3964. host_and_port += std::to_string(PORT);
  3965. req.headers.emplace("Host", host_and_port.c_str());
  3966. req.headers.emplace("Accept", "*/*");
  3967. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3968. req.headers.emplace("Content-Type", "text/plain");
  3969. req.headers.emplace("Content-Length", "0");
  3970. req.headers.emplace(
  3971. "Transfer-Encoding",
  3972. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3973. // Client does not chunk, so make a chunked body manually.
  3974. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3975. auto res = std::make_shared<Response>();
  3976. auto error = Error::Success;
  3977. auto ret = cli_.send(req, *res, error);
  3978. ASSERT_TRUE(ret);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. }
  3981. TEST_F(ServerTest, GetStreamed2) {
  3982. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3983. ASSERT_TRUE(res);
  3984. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3985. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3986. EXPECT_EQ(true, res->has_header("Content-Range"));
  3987. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3988. EXPECT_EQ(std::string("ab"), res->body);
  3989. }
  3990. TEST_F(ServerTest, GetStreamed) {
  3991. auto res = cli_.Get("/streamed");
  3992. ASSERT_TRUE(res);
  3993. EXPECT_EQ(StatusCode::OK_200, res->status);
  3994. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3995. EXPECT_EQ(std::string("aaabbb"), res->body);
  3996. }
  3997. TEST_F(ServerTest, GetStreamedWithRange1) {
  3998. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3999. ASSERT_TRUE(res);
  4000. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4001. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4002. EXPECT_EQ(true, res->has_header("Content-Range"));
  4003. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4004. EXPECT_EQ(std::string("def"), res->body);
  4005. }
  4006. TEST_F(ServerTest, GetStreamedWithRange2) {
  4007. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  4008. ASSERT_TRUE(res);
  4009. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4010. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4011. EXPECT_EQ(true, res->has_header("Content-Range"));
  4012. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4013. EXPECT_EQ(std::string("bcdefg"), res->body);
  4014. }
  4015. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  4016. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  4017. ASSERT_TRUE(res);
  4018. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4019. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4020. EXPECT_EQ(true, res->has_header("Content-Range"));
  4021. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  4022. EXPECT_EQ(std::string("efg"), res->body);
  4023. }
  4024. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  4025. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  4026. ASSERT_TRUE(res);
  4027. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4028. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4029. EXPECT_EQ(false, res->has_header("Content-Range"));
  4030. EXPECT_EQ(0U, res->body.size());
  4031. }
  4032. TEST_F(ServerTest, GetStreamedWithRangeError) {
  4033. auto res = cli_.Get("/streamed-with-range",
  4034. {{"Range", "bytes=92233720368547758079223372036854775806-"
  4035. "92233720368547758079223372036854775807"}});
  4036. ASSERT_TRUE(res);
  4037. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4038. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ(false, res->has_header("Content-Range"));
  4040. EXPECT_EQ(0U, res->body.size());
  4041. }
  4042. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  4043. auto res = cli_.Get(
  4044. "/with-range",
  4045. {{"Range", "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  4046. {"Accept-Encoding", ""}});
  4047. ASSERT_TRUE(res);
  4048. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4049. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4050. EXPECT_EQ(true, res->has_header("Content-Range"));
  4051. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4052. EXPECT_EQ(std::string("abcdefg"), res->body);
  4053. }
  4054. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  4055. auto res = cli_.Get("/with-range", {
  4056. {"Range", "bytes=0-"},
  4057. {"Accept-Encoding", ""},
  4058. });
  4059. ASSERT_TRUE(res);
  4060. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4061. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  4062. EXPECT_EQ(true, res->has_header("Content-Range"));
  4063. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  4064. EXPECT_EQ(std::string("abcdefg"), res->body);
  4065. }
  4066. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  4067. auto res =
  4068. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4069. ASSERT_TRUE(res);
  4070. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4071. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4072. EXPECT_EQ(false, res->has_header("Content-Range"));
  4073. EXPECT_EQ(267U, res->body.size());
  4074. // Check that both range contents are present
  4075. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  4076. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4077. // Check that Content-Range headers are present for both ranges
  4078. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  4079. std::string::npos);
  4080. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4081. std::string::npos);
  4082. }
  4083. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  4084. Ranges ranges;
  4085. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  4086. ranges.emplace_back(0, -1);
  4087. }
  4088. auto res =
  4089. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  4090. ASSERT_TRUE(res);
  4091. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4092. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4093. EXPECT_EQ(false, res->has_header("Content-Range"));
  4094. EXPECT_EQ(0U, res->body.size());
  4095. }
  4096. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  4097. auto res =
  4098. cli_.Get("/streamed-with-range", {{make_range_header({{1, 4}, {2, 5}})}});
  4099. ASSERT_TRUE(res);
  4100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4101. EXPECT_EQ(5U, res->body.size());
  4102. // Check that overlapping ranges are coalesced into a single range
  4103. EXPECT_EQ("bcdef", res->body);
  4104. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  4105. // Should be single range, not multipart
  4106. EXPECT_TRUE(res->has_header("Content-Range"));
  4107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4108. }
  4109. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  4110. auto res =
  4111. cli_.Get("/streamed-with-range", {{make_range_header({{4, 5}, {0, 2}})}});
  4112. ASSERT_TRUE(res);
  4113. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4114. EXPECT_EQ(268U, res->body.size());
  4115. // Check that both range contents are present
  4116. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  4117. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  4118. // Check that Content-Range headers are present for both ranges
  4119. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  4120. std::string::npos);
  4121. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  4122. std::string::npos);
  4123. }
  4124. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  4125. auto res =
  4126. cli_.Get("/streamed-with-range", {{make_range_header({{0, 2}, {0, 2}})}});
  4127. ASSERT_TRUE(res);
  4128. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4129. EXPECT_EQ(269U, res->body.size());
  4130. // Check that both duplicate range contents are present
  4131. size_t first_abc = res->body.find("abc\r\n");
  4132. EXPECT_TRUE(first_abc != std::string::npos);
  4133. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  4134. EXPECT_TRUE(second_abc != std::string::npos);
  4135. // Check that Content-Range headers are present for both ranges
  4136. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  4137. EXPECT_TRUE(first_range != std::string::npos);
  4138. size_t second_range =
  4139. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  4140. EXPECT_TRUE(second_range != std::string::npos);
  4141. }
  4142. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  4143. auto res = cli_.Get("/streamed-with-range?error",
  4144. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  4145. ASSERT_TRUE(res);
  4146. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4147. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4148. EXPECT_EQ(false, res->has_header("Content-Range"));
  4149. EXPECT_EQ(0U, res->body.size());
  4150. }
  4151. TEST_F(ServerTest, GetStreamedEndless) {
  4152. uint64_t offset = 0;
  4153. auto res = cli_.Get("/streamed-cancel",
  4154. [&](const char * /*data*/, uint64_t data_length) {
  4155. if (offset < 100) {
  4156. offset += data_length;
  4157. return true;
  4158. }
  4159. return false;
  4160. });
  4161. ASSERT_TRUE(!res);
  4162. EXPECT_EQ(Error::Canceled, res.error());
  4163. }
  4164. TEST_F(ServerTest, ClientStop) {
  4165. std::atomic_size_t count{4};
  4166. std::vector<std::thread> threads;
  4167. for (auto i = count.load(); i != 0; --i) {
  4168. threads.emplace_back([&]() {
  4169. auto res = cli_.Get("/streamed-cancel",
  4170. [&](const char *, uint64_t) { return true; });
  4171. --count;
  4172. ASSERT_TRUE(!res);
  4173. EXPECT_TRUE(res.error() == Error::Canceled ||
  4174. res.error() == Error::Read || res.error() == Error::Write);
  4175. });
  4176. }
  4177. std::this_thread::sleep_for(std::chrono::seconds(2));
  4178. while (count != 0) {
  4179. cli_.stop();
  4180. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4181. }
  4182. for (auto &t : threads) {
  4183. t.join();
  4184. }
  4185. }
  4186. TEST_F(ServerTest, GetWithRange1) {
  4187. auto res = cli_.Get("/with-range", {
  4188. make_range_header({{3, 5}}),
  4189. {"Accept-Encoding", ""},
  4190. });
  4191. ASSERT_TRUE(res);
  4192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4193. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  4194. EXPECT_EQ(true, res->has_header("Content-Range"));
  4195. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  4196. EXPECT_EQ(std::string("def"), res->body);
  4197. }
  4198. TEST_F(ServerTest, GetWithRange2) {
  4199. auto res = cli_.Get("/with-range", {
  4200. make_range_header({{1, -1}}),
  4201. {"Accept-Encoding", ""},
  4202. });
  4203. ASSERT_TRUE(res);
  4204. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4205. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4206. EXPECT_EQ(true, res->has_header("Content-Range"));
  4207. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  4208. EXPECT_EQ(std::string("bcdefg"), res->body);
  4209. }
  4210. TEST_F(ServerTest, GetWithRange3) {
  4211. auto res = cli_.Get("/with-range", {
  4212. make_range_header({{0, 0}}),
  4213. {"Accept-Encoding", ""},
  4214. });
  4215. ASSERT_TRUE(res);
  4216. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4217. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  4218. EXPECT_EQ(true, res->has_header("Content-Range"));
  4219. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  4220. EXPECT_EQ(std::string("a"), res->body);
  4221. }
  4222. TEST_F(ServerTest, GetWithRange4) {
  4223. auto res = cli_.Get("/with-range", {
  4224. make_range_header({{-1, 2}}),
  4225. {"Accept-Encoding", ""},
  4226. });
  4227. ASSERT_TRUE(res);
  4228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4229. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  4230. EXPECT_EQ(true, res->has_header("Content-Range"));
  4231. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  4232. EXPECT_EQ(std::string("fg"), res->body);
  4233. }
  4234. TEST_F(ServerTest, GetWithRange5) {
  4235. auto res = cli_.Get("/with-range", {
  4236. make_range_header({{0, 5}}),
  4237. {"Accept-Encoding", ""},
  4238. });
  4239. ASSERT_TRUE(res);
  4240. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4241. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  4242. EXPECT_EQ(true, res->has_header("Content-Range"));
  4243. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  4244. EXPECT_EQ(std::string("abcdef"), res->body);
  4245. }
  4246. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  4247. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  4248. ASSERT_TRUE(res);
  4249. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4250. }
  4251. TEST_F(ServerTest, GetWithRangeMultipart) {
  4252. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  4253. ASSERT_TRUE(res);
  4254. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4255. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  4256. EXPECT_EQ(false, res->has_header("Content-Range"));
  4257. EXPECT_EQ(267U, res->body.size());
  4258. }
  4259. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  4260. auto res =
  4261. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  4262. ASSERT_TRUE(res);
  4263. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  4264. }
  4265. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  4266. auto res = cli_.Get("/with-range-customized-response",
  4267. {{make_range_header({{1, 2}})}});
  4268. ASSERT_TRUE(res);
  4269. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4270. EXPECT_EQ(true, res->has_header("Content-Length"));
  4271. EXPECT_EQ(false, res->has_header("Content-Range"));
  4272. EXPECT_EQ(JSON_DATA, res->body);
  4273. }
  4274. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  4275. auto res = cli_.Get("/with-range-customized-response",
  4276. {{make_range_header({{1, 2}, {4, 5}})}});
  4277. ASSERT_TRUE(res);
  4278. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  4279. EXPECT_EQ(true, res->has_header("Content-Length"));
  4280. EXPECT_EQ(false, res->has_header("Content-Range"));
  4281. EXPECT_EQ(JSON_DATA, res->body);
  4282. }
  4283. TEST_F(ServerTest, Issue1772) {
  4284. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  4285. ASSERT_TRUE(res);
  4286. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  4287. }
  4288. TEST_F(ServerTest, Issue609) {
  4289. auto res = cli_.Delete("/issue609");
  4290. ASSERT_TRUE(res);
  4291. EXPECT_EQ(StatusCode::OK_200, res->status);
  4292. EXPECT_EQ(std::string("ok"), res->body);
  4293. }
  4294. TEST_F(ServerTest, GetStreamedChunked) {
  4295. auto res = cli_.Get("/streamed-chunked");
  4296. ASSERT_TRUE(res);
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ(std::string("123456789"), res->body);
  4299. }
  4300. TEST_F(ServerTest, GetStreamedChunked2) {
  4301. auto res = cli_.Get("/streamed-chunked2");
  4302. ASSERT_TRUE(res);
  4303. EXPECT_EQ(StatusCode::OK_200, res->status);
  4304. EXPECT_EQ(std::string("123456789"), res->body);
  4305. }
  4306. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  4307. auto res = cli_.Get("/streamed-chunked-with-trailer");
  4308. ASSERT_TRUE(res);
  4309. EXPECT_EQ(StatusCode::OK_200, res->status);
  4310. EXPECT_EQ(std::string("123456789"), res->body);
  4311. EXPECT_TRUE(res->has_header("Trailer"));
  4312. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  4313. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  4314. // Trailers are now stored separately from headers (security fix)
  4315. EXPECT_EQ(2U, res->trailers.size());
  4316. EXPECT_TRUE(res->has_trailer("Dummy1"));
  4317. EXPECT_TRUE(res->has_trailer("Dummy2"));
  4318. EXPECT_FALSE(res->has_trailer("Dummy3"));
  4319. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  4320. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  4321. // Verify trailers are NOT in headers (security verification)
  4322. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  4323. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  4324. }
  4325. TEST_F(ServerTest, LargeChunkedPost) {
  4326. Request req;
  4327. req.method = "POST";
  4328. req.path = "/large-chunked";
  4329. std::string host_and_port;
  4330. host_and_port += HOST;
  4331. host_and_port += ":";
  4332. host_and_port += std::to_string(PORT);
  4333. req.headers.emplace("Host", host_and_port.c_str());
  4334. req.headers.emplace("Accept", "*/*");
  4335. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  4336. req.headers.emplace("Content-Type", "text/plain");
  4337. req.headers.emplace("Content-Length", "0");
  4338. req.headers.emplace("Transfer-Encoding", "chunked");
  4339. std::string long_string(30 * 1024u, 'a');
  4340. std::string chunk = "7800\r\n" + long_string + "\r\n";
  4341. // Attempt to make a large enough post to exceed OS buffers, to test that
  4342. // the server handles short reads if the full chunk data isn't available.
  4343. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  4344. auto res = std::make_shared<Response>();
  4345. auto error = Error::Success;
  4346. auto ret = cli_.send(req, *res, error);
  4347. ASSERT_TRUE(ret);
  4348. EXPECT_EQ(StatusCode::OK_200, res->status);
  4349. }
  4350. TEST_F(ServerTest, GetMethodRemoteAddr) {
  4351. auto res = cli_.Get("/remote_addr");
  4352. ASSERT_TRUE(res);
  4353. EXPECT_EQ(StatusCode::OK_200, res->status);
  4354. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4355. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  4356. }
  4357. TEST_F(ServerTest, GetMethodLocalAddr) {
  4358. auto res = cli_.Get("/local_addr");
  4359. ASSERT_TRUE(res);
  4360. EXPECT_EQ(StatusCode::OK_200, res->status);
  4361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4362. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  4363. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  4364. }
  4365. TEST_F(ServerTest, HTTPResponseSplitting) {
  4366. auto res = cli_.Get("/http_response_splitting");
  4367. ASSERT_TRUE(res);
  4368. EXPECT_EQ(StatusCode::OK_200, res->status);
  4369. }
  4370. TEST_F(ServerTest, SlowRequest) {
  4371. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4372. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4373. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  4374. }
  4375. #if 0
  4376. TEST_F(ServerTest, SlowPost) {
  4377. char buffer[64 * 1024];
  4378. memset(buffer, 0x42, sizeof(buffer));
  4379. auto res = cli_.Post(
  4380. "/slowpost", 64 * 1024 * 1024,
  4381. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4382. auto ret = sink.write(buffer, sizeof(buffer));
  4383. EXPECT_TRUE(ret);
  4384. return true;
  4385. },
  4386. "text/plain");
  4387. ASSERT_TRUE(res);
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. }
  4390. TEST_F(ServerTest, SlowPostFail) {
  4391. char buffer[64 * 1024];
  4392. memset(buffer, 0x42, sizeof(buffer));
  4393. cli_.set_write_timeout(std::chrono::seconds(0));
  4394. auto res = cli_.Post(
  4395. "/slowpost", 64 * 1024 * 1024,
  4396. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4397. sink.write(buffer, sizeof(buffer));
  4398. return true;
  4399. },
  4400. "text/plain");
  4401. ASSERT_TRUE(!res);
  4402. EXPECT_EQ(Error::Write, res.error());
  4403. }
  4404. #endif
  4405. TEST_F(ServerTest, Put) {
  4406. auto res = cli_.Put("/put", "PUT", "text/plain");
  4407. ASSERT_TRUE(res);
  4408. EXPECT_EQ(StatusCode::OK_200, res->status);
  4409. EXPECT_EQ("PUT", res->body);
  4410. }
  4411. TEST_F(ServerTest, PutWithContentProvider) {
  4412. auto res = cli_.Put(
  4413. "/put", 3,
  4414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4415. sink.os << "PUT";
  4416. return true;
  4417. },
  4418. "text/plain");
  4419. ASSERT_TRUE(res);
  4420. EXPECT_EQ(StatusCode::OK_200, res->status);
  4421. EXPECT_EQ("PUT", res->body);
  4422. }
  4423. TEST_F(ServerTest, PostWithContentProviderAbort) {
  4424. auto res = cli_.Post(
  4425. "/post", 42,
  4426. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4427. return false;
  4428. },
  4429. "text/plain");
  4430. ASSERT_TRUE(!res);
  4431. EXPECT_EQ(Error::Canceled, res.error());
  4432. }
  4433. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  4434. auto res = cli_.Put(
  4435. "/put",
  4436. [](size_t /*offset*/, DataSink &sink) {
  4437. sink.os << "PUT";
  4438. sink.done();
  4439. return true;
  4440. },
  4441. "text/plain");
  4442. ASSERT_TRUE(res);
  4443. EXPECT_EQ(StatusCode::OK_200, res->status);
  4444. EXPECT_EQ("PUT", res->body);
  4445. }
  4446. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  4447. auto res = cli_.Post(
  4448. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4449. "text/plain");
  4450. ASSERT_TRUE(!res);
  4451. EXPECT_EQ(Error::Canceled, res.error());
  4452. }
  4453. TEST_F(ServerTest, PostLoopBack) {
  4454. std::string body;
  4455. auto res = cli_.Post(
  4456. "/post-loopback", 9,
  4457. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4458. EXPECT_EQ(9u, length);
  4459. sink.write("123", 3);
  4460. sink.write("456", 3);
  4461. sink.write("789", 3);
  4462. return true;
  4463. },
  4464. "text/plain",
  4465. [&body](const char *data, size_t data_length) {
  4466. body.append(data, data_length);
  4467. return true;
  4468. });
  4469. ASSERT_TRUE(res);
  4470. EXPECT_EQ(StatusCode::OK_200, res->status);
  4471. EXPECT_EQ("123456789", body);
  4472. }
  4473. TEST_F(ServerTest, PutLoopBack) {
  4474. std::string body;
  4475. auto res = cli_.Put(
  4476. "/put-loopback", 9,
  4477. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4478. EXPECT_EQ(9u, length);
  4479. sink.write("123", 3);
  4480. sink.write("456", 3);
  4481. sink.write("789", 3);
  4482. return true;
  4483. },
  4484. "text/plain",
  4485. [&body](const char *data, size_t data_length) {
  4486. body.append(data, data_length);
  4487. return true;
  4488. });
  4489. ASSERT_TRUE(res);
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. EXPECT_EQ("123456789", body);
  4492. }
  4493. TEST_F(ServerTest, PatchLoopBack) {
  4494. std::string body;
  4495. auto res = cli_.Patch(
  4496. "/patch-loopback", 9,
  4497. [](size_t /*offset*/, size_t length, DataSink &sink) {
  4498. EXPECT_EQ(9u, length);
  4499. sink.write("123", 3);
  4500. sink.write("456", 3);
  4501. sink.write("789", 3);
  4502. return true;
  4503. },
  4504. "text/plain",
  4505. [&body](const char *data, size_t data_length) {
  4506. body.append(data, data_length);
  4507. return true;
  4508. });
  4509. ASSERT_TRUE(res);
  4510. EXPECT_EQ(StatusCode::OK_200, res->status);
  4511. EXPECT_EQ("123456789", body);
  4512. }
  4513. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  4514. std::string body;
  4515. auto res = cli_.Post(
  4516. "/post-loopback",
  4517. [](size_t /*offset*/, DataSink &sink) {
  4518. sink.write("123", 3);
  4519. sink.write("456", 3);
  4520. sink.write("789", 3);
  4521. sink.done();
  4522. return true;
  4523. },
  4524. "text/plain",
  4525. [&body](const char *data, size_t data_length) {
  4526. body.append(data, data_length);
  4527. return true;
  4528. });
  4529. ASSERT_TRUE(res);
  4530. EXPECT_EQ(StatusCode::OK_200, res->status);
  4531. EXPECT_EQ("123456789", body);
  4532. }
  4533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  4534. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  4535. cli_.set_compress(true);
  4536. auto res = cli_.Put(
  4537. "/put", 3,
  4538. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4539. sink.os << "PUT";
  4540. return true;
  4541. },
  4542. "text/plain");
  4543. ASSERT_TRUE(res);
  4544. EXPECT_EQ(StatusCode::OK_200, res->status);
  4545. EXPECT_EQ("PUT", res->body);
  4546. }
  4547. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  4548. cli_.set_compress(true);
  4549. auto res = cli_.Post(
  4550. "/post", 42,
  4551. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  4552. return false;
  4553. },
  4554. "text/plain");
  4555. ASSERT_TRUE(!res);
  4556. EXPECT_EQ(Error::Canceled, res.error());
  4557. }
  4558. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  4559. cli_.set_compress(true);
  4560. auto res = cli_.Put(
  4561. "/put",
  4562. [](size_t /*offset*/, DataSink &sink) {
  4563. sink.os << "PUT";
  4564. sink.done();
  4565. return true;
  4566. },
  4567. "text/plain");
  4568. ASSERT_TRUE(res);
  4569. EXPECT_EQ(StatusCode::OK_200, res->status);
  4570. EXPECT_EQ("PUT", res->body);
  4571. }
  4572. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  4573. cli_.set_compress(true);
  4574. auto res = cli_.Post(
  4575. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  4576. "text/plain");
  4577. ASSERT_TRUE(!res);
  4578. EXPECT_EQ(Error::Canceled, res.error());
  4579. }
  4580. TEST_F(ServerTest, PutLargeFileWithGzip) {
  4581. cli_.set_compress(true);
  4582. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  4583. ASSERT_TRUE(res);
  4584. EXPECT_EQ(StatusCode::OK_200, res->status);
  4585. EXPECT_EQ(LARGE_DATA, res->body);
  4586. }
  4587. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  4588. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4589. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  4590. Client cli(s.c_str());
  4591. cli.enable_server_certificate_verification(false);
  4592. #else
  4593. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  4594. Client cli(s.c_str());
  4595. #endif
  4596. cli.set_compress(true);
  4597. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  4598. ASSERT_TRUE(res);
  4599. EXPECT_EQ(StatusCode::OK_200, res->status);
  4600. EXPECT_EQ(LARGE_DATA, res->body);
  4601. // The compressed size should be less than a 10th of the original. May vary
  4602. // depending on the zlib library.
  4603. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  4604. static_cast<uint64_t>(10 * 1024 * 1024));
  4605. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  4606. }
  4607. TEST_F(ServerTest, PutContentWithDeflate) {
  4608. cli_.set_compress(false);
  4609. Headers headers;
  4610. headers.emplace("Content-Encoding", "deflate");
  4611. // PUT in deflate format:
  4612. auto res = cli_.Put("/put", headers,
  4613. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  4614. ASSERT_TRUE(res);
  4615. EXPECT_EQ(StatusCode::OK_200, res->status);
  4616. EXPECT_EQ("PUT", res->body);
  4617. }
  4618. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  4619. Headers headers;
  4620. headers.emplace("Accept-Encoding", "gzip, deflate");
  4621. auto res = cli_.Get("/streamed-chunked", 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, GetStreamedChunkedWithGzip2) {
  4627. Headers headers;
  4628. headers.emplace("Accept-Encoding", "gzip, deflate");
  4629. auto res = cli_.Get("/streamed-chunked2", headers);
  4630. ASSERT_TRUE(res);
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. EXPECT_EQ(std::string("123456789"), res->body);
  4633. }
  4634. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  4635. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  4636. ASSERT_TRUE(res);
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. TEST(GzipDecompressor, ChunkedDecompression) {
  4640. std::string data;
  4641. for (size_t i = 0; i < 32 * 1024; ++i) {
  4642. data.push_back(static_cast<char>('a' + i % 26));
  4643. }
  4644. std::string compressed_data;
  4645. {
  4646. httplib::detail::gzip_compressor compressor;
  4647. bool result = compressor.compress(
  4648. data.data(), data.size(),
  4649. /*last=*/true,
  4650. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  4651. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  4652. compressed_data_size);
  4653. return true;
  4654. });
  4655. ASSERT_TRUE(result);
  4656. }
  4657. std::string decompressed_data;
  4658. {
  4659. httplib::detail::gzip_decompressor decompressor;
  4660. // Chunk size is chosen specifically to have a decompressed chunk size equal
  4661. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  4662. size_t chunk_size = 130;
  4663. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  4664. chunk_begin += chunk_size) {
  4665. size_t current_chunk_size =
  4666. std::min(compressed_data.size() - chunk_begin, chunk_size);
  4667. bool result = decompressor.decompress(
  4668. compressed_data.data() + chunk_begin, current_chunk_size,
  4669. [&](const char *decompressed_data_chunk,
  4670. size_t decompressed_data_chunk_size) {
  4671. decompressed_data.insert(decompressed_data.size(),
  4672. decompressed_data_chunk,
  4673. decompressed_data_chunk_size);
  4674. return true;
  4675. });
  4676. ASSERT_TRUE(result);
  4677. }
  4678. }
  4679. ASSERT_EQ(data, decompressed_data);
  4680. }
  4681. TEST(GzipDecompressor, DeflateDecompression) {
  4682. std::string original_text = "Raw deflate without gzip";
  4683. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4684. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4685. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4686. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  4687. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4688. std::string decompressed_data;
  4689. {
  4690. httplib::detail::gzip_decompressor decompressor;
  4691. bool result = decompressor.decompress(
  4692. compressed_data.data(), compressed_data.size(),
  4693. [&](const char *decompressed_data_chunk,
  4694. size_t decompressed_data_chunk_size) {
  4695. decompressed_data.insert(decompressed_data.size(),
  4696. decompressed_data_chunk,
  4697. decompressed_data_chunk_size);
  4698. return true;
  4699. });
  4700. ASSERT_TRUE(result);
  4701. }
  4702. ASSERT_EQ(original_text, decompressed_data);
  4703. }
  4704. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  4705. std::string original_text = "Raw deflate without gzip";
  4706. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  4707. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  4708. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  4709. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  4710. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  4711. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  4712. std::string decompressed_data;
  4713. {
  4714. httplib::detail::gzip_decompressor decompressor;
  4715. bool result = decompressor.decompress(
  4716. compressed_data.data(), compressed_data.size(),
  4717. [&](const char *decompressed_data_chunk,
  4718. size_t decompressed_data_chunk_size) {
  4719. decompressed_data.insert(decompressed_data.size(),
  4720. decompressed_data_chunk,
  4721. decompressed_data_chunk_size);
  4722. return true;
  4723. });
  4724. ASSERT_TRUE(result);
  4725. }
  4726. ASSERT_EQ(original_text, decompressed_data);
  4727. }
  4728. #ifdef _WIN32
  4729. TEST(GzipDecompressor, LargeRandomData) {
  4730. // prepare large random data that is difficult to be compressed and is
  4731. // expected to have large size even when compressed
  4732. std::random_device seed_gen;
  4733. std::mt19937 random(seed_gen());
  4734. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  4735. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  4736. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  4737. std::generate(data.begin(), data.end(), [&]() { return random(); });
  4738. // compress data over 4GiB
  4739. std::string compressed_data;
  4740. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  4741. httplib::detail::gzip_compressor compressor;
  4742. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  4743. data.size() * sizeof(std::uint32_t), true,
  4744. [&](const char *data, size_t size) {
  4745. compressed_data.insert(
  4746. compressed_data.size(), data, size);
  4747. return true;
  4748. });
  4749. ASSERT_TRUE(result);
  4750. // FIXME: compressed data size is expected to be greater than 4GiB,
  4751. // but there is no guarantee
  4752. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  4753. // decompress data over 4GiB
  4754. std::string decompressed_data;
  4755. decompressed_data.reserve(data_size);
  4756. httplib::detail::gzip_decompressor decompressor;
  4757. result = decompressor.decompress(
  4758. compressed_data.data(), compressed_data.size(),
  4759. [&](const char *data, size_t size) {
  4760. decompressed_data.insert(decompressed_data.size(), data, size);
  4761. return true;
  4762. });
  4763. ASSERT_TRUE(result);
  4764. // compare
  4765. ASSERT_EQ(data_size, decompressed_data.size());
  4766. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  4767. 0);
  4768. }
  4769. #endif
  4770. #endif
  4771. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4772. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  4773. Headers headers;
  4774. headers.emplace("Accept-Encoding", "br");
  4775. auto res = cli_.Get("/streamed-chunked", headers);
  4776. ASSERT_TRUE(res);
  4777. EXPECT_EQ(StatusCode::OK_200, res->status);
  4778. EXPECT_EQ(std::string("123456789"), res->body);
  4779. }
  4780. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  4781. Headers headers;
  4782. headers.emplace("Accept-Encoding", "br");
  4783. auto res = cli_.Get("/streamed-chunked2", headers);
  4784. ASSERT_TRUE(res);
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. EXPECT_EQ(std::string("123456789"), res->body);
  4787. }
  4788. #endif
  4789. TEST_F(ServerTest, Patch) {
  4790. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  4791. ASSERT_TRUE(res);
  4792. EXPECT_EQ(StatusCode::OK_200, res->status);
  4793. EXPECT_EQ("PATCH", res->body);
  4794. }
  4795. TEST_F(ServerTest, Delete) {
  4796. auto res = cli_.Delete("/delete");
  4797. ASSERT_TRUE(res);
  4798. EXPECT_EQ(StatusCode::OK_200, res->status);
  4799. EXPECT_EQ("DELETE", res->body);
  4800. }
  4801. TEST_F(ServerTest, DeleteContentReceiver) {
  4802. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  4803. ASSERT_TRUE(res);
  4804. EXPECT_EQ(StatusCode::OK_200, res->status);
  4805. EXPECT_EQ("content", res->body);
  4806. }
  4807. TEST_F(ServerTest, Options) {
  4808. auto res = cli_.Options("*");
  4809. ASSERT_TRUE(res);
  4810. EXPECT_EQ(StatusCode::OK_200, res->status);
  4811. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  4812. EXPECT_TRUE(res->body.empty());
  4813. }
  4814. TEST_F(ServerTest, URL) {
  4815. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  4816. ASSERT_TRUE(res);
  4817. EXPECT_EQ(StatusCode::OK_200, res->status);
  4818. }
  4819. TEST_F(ServerTest, ArrayParam) {
  4820. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  4821. ASSERT_TRUE(res);
  4822. EXPECT_EQ(StatusCode::OK_200, res->status);
  4823. }
  4824. TEST_F(ServerTest, NoMultipleHeaders) {
  4825. Headers headers = {{"Content-Length", "5"}};
  4826. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  4827. "text/plain");
  4828. ASSERT_TRUE(res);
  4829. EXPECT_EQ(StatusCode::OK_200, res->status);
  4830. }
  4831. TEST_F(ServerTest, PostContentReceiver) {
  4832. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4833. ASSERT_TRUE(res);
  4834. ASSERT_EQ(StatusCode::OK_200, res->status);
  4835. ASSERT_EQ("content", res->body);
  4836. }
  4837. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  4838. UploadFormDataItems items = {
  4839. {"text1", "text default", "", ""},
  4840. {"text2", "aωb", "", ""},
  4841. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4842. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4843. {"file3", "", "", "application/octet-stream"},
  4844. };
  4845. auto res = cli_.Post("/content_receiver", items);
  4846. ASSERT_TRUE(res);
  4847. EXPECT_EQ(StatusCode::OK_200, res->status);
  4848. }
  4849. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  4850. UploadFormDataItems items = {
  4851. {"text1", "text default", "", ""},
  4852. {"text2", "aωb", "", ""},
  4853. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  4854. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  4855. {"file3", "", "", "application/octet-stream"},
  4856. };
  4857. auto boundary = std::string("+++++");
  4858. std::string body;
  4859. for (const auto &item : items) {
  4860. body += "--" + boundary + "\r\n";
  4861. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  4862. if (!item.filename.empty()) {
  4863. body += "; filename=\"" + item.filename + "\"";
  4864. }
  4865. body += "\r\n";
  4866. if (!item.content_type.empty()) {
  4867. body += "Content-Type: " + item.content_type + "\r\n";
  4868. }
  4869. body += "\r\n";
  4870. body += item.content + "\r\n";
  4871. }
  4872. body += "--" + boundary + "--\r\n";
  4873. std::string content_type = "multipart/form-data; boundary=" + boundary;
  4874. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  4875. ASSERT_TRUE(res);
  4876. EXPECT_EQ(StatusCode::OK_200, res->status);
  4877. }
  4878. TEST_F(ServerTest, PostContentReceiverGzip) {
  4879. cli_.set_compress(true);
  4880. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  4881. ASSERT_TRUE(res);
  4882. ASSERT_EQ(StatusCode::OK_200, res->status);
  4883. ASSERT_EQ("content", res->body);
  4884. }
  4885. TEST_F(ServerTest, PutContentReceiver) {
  4886. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  4887. ASSERT_TRUE(res);
  4888. ASSERT_EQ(StatusCode::OK_200, res->status);
  4889. ASSERT_EQ("content", res->body);
  4890. }
  4891. TEST_F(ServerTest, PatchContentReceiver) {
  4892. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  4893. ASSERT_TRUE(res);
  4894. ASSERT_EQ(StatusCode::OK_200, res->status);
  4895. ASSERT_EQ("content", res->body);
  4896. }
  4897. template <typename ClientType>
  4898. void TestWithHeadersAndContentReceiver(
  4899. ClientType &cli,
  4900. std::function<Result(ClientType &, const std::string &, const Headers &,
  4901. const std::string &, const std::string &,
  4902. ContentReceiver, DownloadProgress)>
  4903. request_func) {
  4904. Headers headers;
  4905. headers.emplace("X-Custom-Header", "test-value");
  4906. std::string received_body;
  4907. auto res = request_func(
  4908. cli, "/content_receiver", headers, "content", "application/json",
  4909. [&](const char *data, size_t data_length) {
  4910. received_body.append(data, data_length);
  4911. return true;
  4912. },
  4913. nullptr);
  4914. ASSERT_TRUE(res);
  4915. EXPECT_EQ(StatusCode::OK_200, res->status);
  4916. EXPECT_EQ("content", received_body);
  4917. }
  4918. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  4919. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4920. using ClientT = SSLClient;
  4921. #else
  4922. using ClientT = Client;
  4923. #endif
  4924. TestWithHeadersAndContentReceiver<ClientT>(
  4925. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4926. const std::string &body, const std::string &content_type,
  4927. ContentReceiver receiver, DownloadProgress progress) {
  4928. return cli.Post(path, headers, body, content_type, receiver, progress);
  4929. });
  4930. }
  4931. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  4932. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4933. using ClientT = SSLClient;
  4934. #else
  4935. using ClientT = Client;
  4936. #endif
  4937. TestWithHeadersAndContentReceiver<ClientT>(
  4938. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4939. const std::string &body, const std::string &content_type,
  4940. ContentReceiver receiver, DownloadProgress progress) {
  4941. return cli.Put(path, headers, body, content_type, receiver, progress);
  4942. });
  4943. }
  4944. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  4945. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4946. using ClientT = SSLClient;
  4947. #else
  4948. using ClientT = Client;
  4949. #endif
  4950. TestWithHeadersAndContentReceiver<ClientT>(
  4951. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4952. const std::string &body, const std::string &content_type,
  4953. ContentReceiver receiver, DownloadProgress progress) {
  4954. return cli.Patch(path, headers, body, content_type, receiver, progress);
  4955. });
  4956. }
  4957. template <typename ClientType>
  4958. void TestWithHeadersAndContentReceiverWithProgress(
  4959. ClientType &cli,
  4960. std::function<Result(ClientType &, const std::string &, const Headers &,
  4961. const std::string &, const std::string &,
  4962. ContentReceiver, DownloadProgress)>
  4963. request_func) {
  4964. Headers headers;
  4965. headers.emplace("X-Test-Header", "progress-test");
  4966. std::string received_body;
  4967. auto progress_called = false;
  4968. auto res = request_func(
  4969. cli, "/content_receiver", headers, "content", "text/plain",
  4970. [&](const char *data, size_t data_length) {
  4971. received_body.append(data, data_length);
  4972. return true;
  4973. },
  4974. [&](uint64_t /*current*/, uint64_t /*total*/) {
  4975. progress_called = true;
  4976. return true;
  4977. });
  4978. ASSERT_TRUE(res);
  4979. EXPECT_EQ(StatusCode::OK_200, res->status);
  4980. EXPECT_EQ("content", received_body);
  4981. EXPECT_TRUE(progress_called);
  4982. }
  4983. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  4984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4985. using ClientT = SSLClient;
  4986. #else
  4987. using ClientT = Client;
  4988. #endif
  4989. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  4990. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  4991. const std::string &body, const std::string &content_type,
  4992. ContentReceiver receiver, DownloadProgress progress) {
  4993. return cli.Post(path, headers, body, content_type, receiver, progress);
  4994. });
  4995. }
  4996. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  4997. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4998. using ClientT = SSLClient;
  4999. #else
  5000. using ClientT = Client;
  5001. #endif
  5002. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5003. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5004. const std::string &body, const std::string &content_type,
  5005. ContentReceiver receiver, DownloadProgress progress) {
  5006. return cli.Put(path, headers, body, content_type, receiver, progress);
  5007. });
  5008. }
  5009. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  5010. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5011. using ClientT = SSLClient;
  5012. #else
  5013. using ClientT = Client;
  5014. #endif
  5015. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  5016. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5017. const std::string &body, const std::string &content_type,
  5018. ContentReceiver receiver, DownloadProgress progress) {
  5019. return cli.Patch(path, headers, body, content_type, receiver, progress);
  5020. });
  5021. }
  5022. template <typename ClientType>
  5023. void TestWithHeadersAndContentReceiverError(
  5024. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  5025. const Headers &, const std::string &,
  5026. const std::string &, ContentReceiver)>
  5027. request_func) {
  5028. Headers headers;
  5029. headers.emplace("X-Error-Test", "true");
  5030. std::string received_body;
  5031. auto receiver_failed = false;
  5032. auto res =
  5033. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  5034. [&](const char *data, size_t data_length) {
  5035. received_body.append(data, data_length);
  5036. receiver_failed = true;
  5037. return false;
  5038. });
  5039. ASSERT_FALSE(res);
  5040. EXPECT_TRUE(receiver_failed);
  5041. }
  5042. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  5043. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5044. using ClientT = SSLClient;
  5045. #else
  5046. using ClientT = Client;
  5047. #endif
  5048. TestWithHeadersAndContentReceiverError<ClientT>(
  5049. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5050. const std::string &body, const std::string &content_type,
  5051. ContentReceiver receiver) {
  5052. return cli.Post(path, headers, body, content_type, receiver);
  5053. });
  5054. }
  5055. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  5056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5057. using ClientT = SSLClient;
  5058. #else
  5059. using ClientT = Client;
  5060. #endif
  5061. TestWithHeadersAndContentReceiverError<ClientT>(
  5062. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5063. const std::string &body, const std::string &content_type,
  5064. ContentReceiver receiver) {
  5065. return cli.Put(path, headers, body, content_type, receiver);
  5066. });
  5067. }
  5068. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  5069. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5070. using ClientT = SSLClient;
  5071. #else
  5072. using ClientT = Client;
  5073. #endif
  5074. TestWithHeadersAndContentReceiverError<ClientT>(
  5075. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  5076. const std::string &body, const std::string &content_type,
  5077. ContentReceiver receiver) {
  5078. return cli.Patch(path, headers, body, content_type, receiver);
  5079. });
  5080. }
  5081. TEST_F(ServerTest, PostQueryStringAndBody) {
  5082. auto res =
  5083. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  5084. ASSERT_TRUE(res);
  5085. ASSERT_EQ(StatusCode::OK_200, res->status);
  5086. }
  5087. TEST_F(ServerTest, HTTP2Magic) {
  5088. Request req;
  5089. req.method = "PRI";
  5090. req.path = "*";
  5091. req.body = "SM";
  5092. auto res = std::make_shared<Response>();
  5093. auto error = Error::Success;
  5094. auto ret = cli_.send(req, *res, error);
  5095. ASSERT_TRUE(ret);
  5096. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5097. }
  5098. TEST_F(ServerTest, KeepAlive) {
  5099. auto res = cli_.Get("/hi");
  5100. ASSERT_TRUE(res);
  5101. EXPECT_EQ(StatusCode::OK_200, res->status);
  5102. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5103. EXPECT_EQ("Hello World!", res->body);
  5104. res = cli_.Get("/hi");
  5105. ASSERT_TRUE(res);
  5106. EXPECT_EQ(StatusCode::OK_200, res->status);
  5107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5108. EXPECT_EQ("Hello World!", res->body);
  5109. res = cli_.Get("/hi");
  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("Hello World!", res->body);
  5114. res = cli_.Get("/not-exist");
  5115. ASSERT_TRUE(res);
  5116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5117. res = cli_.Post("/empty", "", "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. EXPECT_EQ("close", res->get_header_value("Connection"));
  5123. res = cli_.Post(
  5124. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  5125. "text/plain");
  5126. ASSERT_TRUE(res);
  5127. EXPECT_EQ(StatusCode::OK_200, res->status);
  5128. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5129. EXPECT_EQ("empty", res->body);
  5130. cli_.set_keep_alive(false);
  5131. res = cli_.Get("/last-request");
  5132. ASSERT_TRUE(res);
  5133. EXPECT_EQ(StatusCode::OK_200, res->status);
  5134. EXPECT_EQ("close", res->get_header_value("Connection"));
  5135. }
  5136. TEST_F(ServerTest, TooManyRedirect) {
  5137. cli_.set_follow_location(true);
  5138. auto res = cli_.Get("/redirect/0");
  5139. ASSERT_TRUE(!res);
  5140. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  5141. }
  5142. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  5143. Request req;
  5144. req.method = "FOOBAR";
  5145. req.path = "/hi";
  5146. cli_.set_keep_alive(true);
  5147. auto res = cli_.send(req);
  5148. ASSERT_TRUE(res);
  5149. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5150. EXPECT_EQ("close", res->get_header_value("Connection"));
  5151. EXPECT_FALSE(cli_.is_socket_open());
  5152. }
  5153. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  5154. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  5155. TEST_F(ServerTest, Gzip) {
  5156. Headers headers;
  5157. headers.emplace("Accept-Encoding", "gzip, deflate");
  5158. auto res = cli_.Get("/compress", headers);
  5159. ASSERT_TRUE(res);
  5160. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5161. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5162. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5163. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5164. "7890123456789012345678901234567890",
  5165. res->body);
  5166. EXPECT_EQ(StatusCode::OK_200, res->status);
  5167. }
  5168. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  5169. Headers headers;
  5170. headers.emplace("Accept-Encoding", "");
  5171. auto res = cli_.Get("/compress", headers);
  5172. ASSERT_TRUE(res);
  5173. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5174. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5175. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5176. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5177. "7890123456789012345678901234567890",
  5178. res->body);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. }
  5181. TEST_F(ServerTest, GzipWithContentReceiver) {
  5182. Headers headers;
  5183. headers.emplace("Accept-Encoding", "gzip, deflate");
  5184. std::string body;
  5185. auto res = cli_.Get("/compress", headers,
  5186. [&](const char *data, uint64_t data_length) {
  5187. EXPECT_EQ(100U, data_length);
  5188. body.append(data, data_length);
  5189. return true;
  5190. });
  5191. ASSERT_TRUE(res);
  5192. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5196. "7890123456789012345678901234567890",
  5197. body);
  5198. EXPECT_EQ(StatusCode::OK_200, res->status);
  5199. }
  5200. TEST_F(ServerTest, GzipWithoutDecompressing) {
  5201. Headers headers;
  5202. headers.emplace("Accept-Encoding", "gzip, deflate");
  5203. cli_.set_decompress(false);
  5204. auto res = cli_.Get("/compress", headers);
  5205. ASSERT_TRUE(res);
  5206. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5208. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  5209. EXPECT_EQ(33U, res->body.size());
  5210. EXPECT_EQ(StatusCode::OK_200, res->status);
  5211. }
  5212. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  5213. Headers headers;
  5214. headers.emplace("Accept-Encoding", "");
  5215. std::string body;
  5216. auto res = cli_.Get("/compress", headers,
  5217. [&](const char *data, uint64_t data_length) {
  5218. EXPECT_EQ(100U, data_length);
  5219. body.append(data, data_length);
  5220. return true;
  5221. });
  5222. ASSERT_TRUE(res);
  5223. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5225. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5226. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5227. "7890123456789012345678901234567890",
  5228. body);
  5229. EXPECT_EQ(StatusCode::OK_200, res->status);
  5230. }
  5231. TEST_F(ServerTest, NoGzip) {
  5232. Headers headers;
  5233. headers.emplace("Accept-Encoding", "gzip, deflate");
  5234. auto res = cli_.Get("/nocompress", headers);
  5235. ASSERT_TRUE(res);
  5236. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5237. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5238. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5239. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5240. "7890123456789012345678901234567890",
  5241. res->body);
  5242. EXPECT_EQ(StatusCode::OK_200, res->status);
  5243. }
  5244. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  5245. Headers headers;
  5246. headers.emplace("Accept-Encoding", "gzip, deflate");
  5247. std::string body;
  5248. auto res = cli_.Get("/nocompress", headers,
  5249. [&](const char *data, uint64_t data_length) {
  5250. EXPECT_EQ(100U, data_length);
  5251. body.append(data, data_length);
  5252. return true;
  5253. });
  5254. ASSERT_TRUE(res);
  5255. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5256. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5257. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5258. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5259. "7890123456789012345678901234567890",
  5260. body);
  5261. EXPECT_EQ(StatusCode::OK_200, res->status);
  5262. }
  5263. TEST_F(ServerTest, MultipartFormDataGzip) {
  5264. UploadFormDataItems items = {
  5265. {"key1", "test", "", ""},
  5266. {"key2", "--abcdefg123", "", ""},
  5267. };
  5268. cli_.set_compress(true);
  5269. auto res = cli_.Post("/compress-multipart", items);
  5270. ASSERT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. }
  5273. #endif
  5274. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5275. TEST_F(ServerTest, Brotli) {
  5276. Headers headers;
  5277. headers.emplace("Accept-Encoding", "br");
  5278. auto res = cli_.Get("/compress", headers);
  5279. ASSERT_TRUE(res);
  5280. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5281. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5282. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5283. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5284. "7890123456789012345678901234567890",
  5285. res->body);
  5286. EXPECT_EQ(StatusCode::OK_200, res->status);
  5287. }
  5288. #endif
  5289. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  5290. TEST_F(ServerTest, Zstd) {
  5291. Headers headers;
  5292. headers.emplace("Accept-Encoding", "zstd");
  5293. auto res = cli_.Get("/compress", headers);
  5294. ASSERT_TRUE(res);
  5295. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5297. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5299. "7890123456789012345678901234567890",
  5300. res->body);
  5301. EXPECT_EQ(StatusCode::OK_200, res->status);
  5302. }
  5303. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  5304. Headers headers;
  5305. headers.emplace("Accept-Encoding", "");
  5306. auto res = cli_.Get("/compress", headers);
  5307. ASSERT_TRUE(res);
  5308. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5309. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5310. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5311. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5312. "7890123456789012345678901234567890",
  5313. res->body);
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. }
  5316. TEST_F(ServerTest, ZstdWithContentReceiver) {
  5317. Headers headers;
  5318. headers.emplace("Accept-Encoding", "zstd");
  5319. std::string body;
  5320. auto res = cli_.Get("/compress", headers,
  5321. [&](const char *data, uint64_t data_length) {
  5322. EXPECT_EQ(100U, data_length);
  5323. body.append(data, data_length);
  5324. return true;
  5325. });
  5326. ASSERT_TRUE(res);
  5327. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5328. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5329. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5330. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5331. "7890123456789012345678901234567890",
  5332. body);
  5333. EXPECT_EQ(StatusCode::OK_200, res->status);
  5334. }
  5335. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  5336. Headers headers;
  5337. headers.emplace("Accept-Encoding", "zstd");
  5338. cli_.set_decompress(false);
  5339. auto res = cli_.Get("/compress", headers);
  5340. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  5341. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  5342. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  5343. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  5344. ASSERT_TRUE(res);
  5345. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  5346. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5347. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5348. EXPECT_EQ(StatusCode::OK_200, res->status);
  5349. ASSERT_EQ(26U, res->body.size());
  5350. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  5351. 0);
  5352. }
  5353. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  5354. Headers headers;
  5355. headers.emplace("Accept-Encoding", "");
  5356. std::string body;
  5357. auto res = cli_.Get("/compress", headers,
  5358. [&](const char *data, uint64_t data_length) {
  5359. EXPECT_EQ(100U, data_length);
  5360. body.append(data, data_length);
  5361. return true;
  5362. });
  5363. ASSERT_TRUE(res);
  5364. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5365. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5366. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5367. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5368. "7890123456789012345678901234567890",
  5369. body);
  5370. EXPECT_EQ(StatusCode::OK_200, res->status);
  5371. }
  5372. TEST_F(ServerTest, NoZstd) {
  5373. Headers headers;
  5374. headers.emplace("Accept-Encoding", "zstd");
  5375. auto res = cli_.Get("/nocompress", headers);
  5376. ASSERT_TRUE(res);
  5377. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5378. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5379. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5380. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5381. "7890123456789012345678901234567890",
  5382. res->body);
  5383. EXPECT_EQ(StatusCode::OK_200, res->status);
  5384. }
  5385. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  5386. Headers headers;
  5387. headers.emplace("Accept-Encoding", "zstd");
  5388. std::string body;
  5389. auto res = cli_.Get("/nocompress", headers,
  5390. [&](const char *data, uint64_t data_length) {
  5391. EXPECT_EQ(100U, data_length);
  5392. body.append(data, data_length);
  5393. return true;
  5394. });
  5395. ASSERT_TRUE(res);
  5396. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  5397. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5398. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  5399. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  5400. "7890123456789012345678901234567890",
  5401. body);
  5402. EXPECT_EQ(StatusCode::OK_200, res->status);
  5403. }
  5404. // TODO: How to enable zstd ??
  5405. TEST_F(ServerTest, MultipartFormDataZstd) {
  5406. UploadFormDataItems items = {
  5407. {"key1", "test", "", ""},
  5408. {"key2", "--abcdefg123", "", ""},
  5409. };
  5410. Headers headers;
  5411. headers.emplace("Accept-Encoding", "zstd");
  5412. cli_.set_compress(true);
  5413. auto res = cli_.Post("/compress-multipart", headers, items);
  5414. ASSERT_TRUE(res);
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. }
  5417. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  5418. Headers headers;
  5419. headers.emplace("Accept-Encoding", "zstd");
  5420. cli_.set_compress(true);
  5421. auto res = cli_.Put(
  5422. "/put", headers, 3,
  5423. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5424. sink.os << "PUT";
  5425. return true;
  5426. },
  5427. "text/plain");
  5428. ASSERT_TRUE(res);
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("PUT", res->body);
  5431. }
  5432. // Pre-compression logging tests
  5433. TEST_F(ServerTest, PreCompressionLogging) {
  5434. // Test data for compression (matches the actual /compress endpoint content)
  5435. const std::string test_content =
  5436. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5437. "3456789012345678901234567890";
  5438. // Variables to capture logging data
  5439. std::string pre_compression_body;
  5440. std::string pre_compression_content_type;
  5441. std::string pre_compression_content_encoding;
  5442. std::string post_compression_body;
  5443. std::string post_compression_content_type;
  5444. std::string post_compression_content_encoding;
  5445. // Set up pre-compression logger
  5446. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  5447. const Response &res) {
  5448. pre_compression_body = res.body;
  5449. pre_compression_content_type = res.get_header_value("Content-Type");
  5450. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  5451. });
  5452. // Set up post-compression logger
  5453. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5454. post_compression_body = res.body;
  5455. post_compression_content_type = res.get_header_value("Content-Type");
  5456. post_compression_content_encoding =
  5457. res.get_header_value("Content-Encoding");
  5458. });
  5459. // Test with gzip compression
  5460. Headers headers;
  5461. headers.emplace("Accept-Encoding", "gzip");
  5462. auto res = cli_.Get("/compress", headers);
  5463. // Verify response was compressed
  5464. ASSERT_TRUE(res);
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5467. // Verify pre-compression logger captured uncompressed content
  5468. EXPECT_EQ(test_content, pre_compression_body);
  5469. EXPECT_EQ("text/plain", pre_compression_content_type);
  5470. EXPECT_TRUE(pre_compression_content_encoding
  5471. .empty()); // No encoding header before compression
  5472. // Verify post-compression logger captured compressed content
  5473. EXPECT_NE(test_content,
  5474. post_compression_body); // Should be different after compression
  5475. EXPECT_EQ("text/plain", post_compression_content_type);
  5476. EXPECT_EQ("gzip", post_compression_content_encoding);
  5477. // Verify compressed content is smaller
  5478. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5479. }
  5480. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  5481. const std::string test_content =
  5482. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5483. "3456789012345678901234567890";
  5484. std::string pre_compression_body;
  5485. std::string post_compression_body;
  5486. svr_.set_pre_compression_logger(
  5487. [&](const Request & /*req*/, const Response &res) {
  5488. pre_compression_body = res.body;
  5489. });
  5490. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5491. post_compression_body = res.body;
  5492. });
  5493. Headers headers;
  5494. headers.emplace("Accept-Encoding", "br");
  5495. auto res = cli_.Get("/compress", headers);
  5496. ASSERT_TRUE(res);
  5497. EXPECT_EQ(StatusCode::OK_200, res->status);
  5498. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  5499. // Verify pre-compression content is uncompressed
  5500. EXPECT_EQ(test_content, pre_compression_body);
  5501. // Verify post-compression content is compressed
  5502. EXPECT_NE(test_content, post_compression_body);
  5503. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  5504. }
  5505. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  5506. const std::string test_content =
  5507. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5508. "3456789012345678901234567890";
  5509. std::string pre_compression_body;
  5510. std::string post_compression_body;
  5511. svr_.set_pre_compression_logger(
  5512. [&](const Request & /*req*/, const Response &res) {
  5513. pre_compression_body = res.body;
  5514. });
  5515. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  5516. post_compression_body = res.body;
  5517. });
  5518. // Request without compression (use /nocompress endpoint)
  5519. Headers headers;
  5520. auto res = cli_.Get("/nocompress", headers);
  5521. ASSERT_TRUE(res);
  5522. EXPECT_EQ(StatusCode::OK_200, res->status);
  5523. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  5524. // Pre-compression logger should not be called when no compression is applied
  5525. EXPECT_TRUE(
  5526. pre_compression_body.empty()); // Pre-compression logger not called
  5527. EXPECT_EQ(
  5528. test_content,
  5529. post_compression_body); // Post-compression logger captures final content
  5530. }
  5531. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  5532. const std::string test_content =
  5533. "123456789012345678901234567890123456789012345678901234567890123456789012"
  5534. "3456789012345678901234567890";
  5535. std::string pre_compression_body;
  5536. bool pre_logger_called = false;
  5537. // Set only pre-compression logger
  5538. svr_.set_pre_compression_logger(
  5539. [&](const Request & /*req*/, const Response &res) {
  5540. pre_compression_body = res.body;
  5541. pre_logger_called = true;
  5542. });
  5543. Headers headers;
  5544. headers.emplace("Accept-Encoding", "gzip");
  5545. auto res = cli_.Get("/compress", headers);
  5546. ASSERT_TRUE(res);
  5547. EXPECT_EQ(StatusCode::OK_200, res->status);
  5548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  5549. // Verify pre-compression logger was called
  5550. EXPECT_TRUE(pre_logger_called);
  5551. EXPECT_EQ(test_content, pre_compression_body);
  5552. }
  5553. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  5554. {
  5555. Request req;
  5556. req.method = "POST";
  5557. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  5558. req.body = LARGE_DATA;
  5559. Response res;
  5560. auto error = Error::Success;
  5561. auto start = std::chrono::high_resolution_clock::now();
  5562. cli_.set_keep_alive(true);
  5563. auto ret = cli_.send(req, res, error);
  5564. auto end = std::chrono::high_resolution_clock::now();
  5565. auto elapsed =
  5566. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5567. .count();
  5568. EXPECT_FALSE(ret);
  5569. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  5570. EXPECT_EQ("close", res.get_header_value("Connection"));
  5571. EXPECT_FALSE(cli_.is_socket_open());
  5572. EXPECT_LE(elapsed, 200);
  5573. }
  5574. {
  5575. // Send an extra GET request to ensure error recovery without hanging
  5576. Request req;
  5577. req.method = "GET";
  5578. req.path = "/hi";
  5579. auto start = std::chrono::high_resolution_clock::now();
  5580. auto res = cli_.send(req);
  5581. auto end = std::chrono::high_resolution_clock::now();
  5582. auto elapsed =
  5583. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5584. .count();
  5585. ASSERT_TRUE(res);
  5586. EXPECT_EQ(StatusCode::OK_200, res->status);
  5587. EXPECT_EQ("Hello World!", res->body);
  5588. EXPECT_LE(elapsed, 100);
  5589. }
  5590. }
  5591. TEST(ZstdDecompressor, ChunkedDecompression) {
  5592. std::string data;
  5593. for (size_t i = 0; i < 32 * 1024; ++i) {
  5594. data.push_back(static_cast<char>('a' + i % 26));
  5595. }
  5596. std::string compressed_data;
  5597. {
  5598. httplib::detail::zstd_compressor compressor;
  5599. bool result = compressor.compress(
  5600. data.data(), data.size(),
  5601. /*last=*/true,
  5602. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  5603. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  5604. compressed_data_size);
  5605. return true;
  5606. });
  5607. ASSERT_TRUE(result);
  5608. }
  5609. std::string decompressed_data;
  5610. {
  5611. httplib::detail::zstd_decompressor decompressor;
  5612. // Chunk size is chosen specifically to have a decompressed chunk size equal
  5613. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  5614. size_t chunk_size = 130;
  5615. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  5616. chunk_begin += chunk_size) {
  5617. size_t current_chunk_size =
  5618. std::min(compressed_data.size() - chunk_begin, chunk_size);
  5619. bool result = decompressor.decompress(
  5620. compressed_data.data() + chunk_begin, current_chunk_size,
  5621. [&](const char *decompressed_data_chunk,
  5622. size_t decompressed_data_chunk_size) {
  5623. decompressed_data.insert(decompressed_data.size(),
  5624. decompressed_data_chunk,
  5625. decompressed_data_chunk_size);
  5626. return true;
  5627. });
  5628. ASSERT_TRUE(result);
  5629. }
  5630. }
  5631. ASSERT_EQ(data, decompressed_data);
  5632. }
  5633. TEST(ZstdDecompressor, Decompress) {
  5634. std::string original_text = "Compressed with ZSTD";
  5635. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  5636. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  5637. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  5638. 0x20, 0x5a, 0x53, 0x54, 0x44};
  5639. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  5640. std::string decompressed_data;
  5641. {
  5642. httplib::detail::zstd_decompressor decompressor;
  5643. bool result = decompressor.decompress(
  5644. compressed_data.data(), compressed_data.size(),
  5645. [&](const char *decompressed_data_chunk,
  5646. size_t decompressed_data_chunk_size) {
  5647. decompressed_data.insert(decompressed_data.size(),
  5648. decompressed_data_chunk,
  5649. decompressed_data_chunk_size);
  5650. return true;
  5651. });
  5652. ASSERT_TRUE(result);
  5653. }
  5654. ASSERT_EQ(original_text, decompressed_data);
  5655. }
  5656. #endif
  5657. // Sends a raw request to a server listening at HOST:PORT.
  5658. static bool send_request(time_t read_timeout_sec, const std::string &req,
  5659. std::string *resp = nullptr) {
  5660. auto error = Error::Success;
  5661. auto client_sock = detail::create_client_socket(
  5662. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5663. /*connection_timeout_sec=*/5, 0,
  5664. /*read_timeout_sec=*/5, 0,
  5665. /*write_timeout_sec=*/5, 0, std::string(), error);
  5666. if (client_sock == INVALID_SOCKET) { return false; }
  5667. auto ret = detail::process_client_socket(
  5668. client_sock, read_timeout_sec, 0, 0, 0, 0,
  5669. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  5670. if (req.size() !=
  5671. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  5672. return false;
  5673. }
  5674. char buf[512];
  5675. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  5676. while (line_reader.getline()) {
  5677. if (resp) { *resp += line_reader.ptr(); }
  5678. }
  5679. return true;
  5680. });
  5681. detail::close_socket(client_sock);
  5682. return ret;
  5683. }
  5684. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  5685. Server svr;
  5686. std::string header_value;
  5687. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  5688. header_value = req.get_header_value("foo");
  5689. res.set_content("ok", "text/plain");
  5690. });
  5691. thread t = thread([&] { svr.listen(HOST, PORT); });
  5692. auto se = detail::scope_exit([&] {
  5693. svr.stop();
  5694. t.join();
  5695. ASSERT_FALSE(svr.is_running());
  5696. });
  5697. svr.wait_until_ready();
  5698. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  5699. // like characters are not treated the same - use vertical tab and escape.
  5700. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  5701. "foo: \t \v bar \x1B\t \r\n"
  5702. "Connection: close\r\n"
  5703. "\r\n";
  5704. std::string res;
  5705. ASSERT_TRUE(send_request(5, req, &res));
  5706. EXPECT_EQ(header_value, "");
  5707. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  5708. }
  5709. // Sends a raw request and verifies that there isn't a crash or exception.
  5710. static void test_raw_request(const std::string &req,
  5711. std::string *out = nullptr) {
  5712. Server svr;
  5713. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  5714. res.set_content("ok", "text/plain");
  5715. });
  5716. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  5717. res.set_content("ok", "text/plain");
  5718. });
  5719. svr.Get("/header_field_value_check",
  5720. [&](const Request & /*req*/, Response &res) {
  5721. res.set_content("ok", "text/plain");
  5722. });
  5723. // Server read timeout must be longer than the client read timeout for the
  5724. // bug to reproduce, probably to force the server to process a request
  5725. // without a trailing blank line.
  5726. const time_t client_read_timeout_sec = 1;
  5727. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  5728. bool listen_thread_ok = false;
  5729. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  5730. auto se = detail::scope_exit([&] {
  5731. svr.stop();
  5732. t.join();
  5733. ASSERT_FALSE(svr.is_running());
  5734. EXPECT_TRUE(listen_thread_ok);
  5735. });
  5736. svr.wait_until_ready();
  5737. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  5738. }
  5739. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  5740. // A certain header line causes an exception if the header property is parsed
  5741. // naively with a single regex. This occurs with libc++ but not libstdc++.
  5742. test_raw_request(
  5743. "GET /hi HTTP/1.1\r\n"
  5744. " : "
  5745. " "
  5746. " ");
  5747. }
  5748. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  5749. // A certain header line causes an exception if the header property *name* is
  5750. // parsed with a regular expression starting with "(.+?):" - this is a non-
  5751. // greedy matcher and requires backtracking when there are a lot of ":"
  5752. // characters.
  5753. // This occurs with libc++ but not libstdc++.
  5754. test_raw_request(
  5755. "GET /hi HTTP/1.1\r\n"
  5756. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  5757. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5758. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  5759. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  5760. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  5761. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  5762. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  5763. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  5764. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5765. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5766. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  5767. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5768. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  5769. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  5770. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  5771. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  5772. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  5773. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  5774. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  5775. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  5776. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  5777. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  5778. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  5779. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  5780. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  5781. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  5782. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  5783. "&&&%%%");
  5784. }
  5785. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  5786. // Make sure this doesn't crash the server.
  5787. // In a previous version of the header line regex, the "\r" rendered the line
  5788. // unparsable and the regex engine repeatedly backtracked, trying to look for
  5789. // a new position where the leading white space ended and the field value
  5790. // began.
  5791. // The crash occurs with libc++ but not libstdc++.
  5792. test_raw_request("GET /hi HTTP/1.1\r\n"
  5793. "a:" +
  5794. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  5795. "\r\n"
  5796. "\r\n");
  5797. }
  5798. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  5799. std::string out;
  5800. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5801. "Content-Type: text/plain\r\n"
  5802. "Transfer-Encoding: chunked\r\n"
  5803. "\r\n"
  5804. "nothex\r\n",
  5805. &out);
  5806. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5807. }
  5808. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  5809. std::string out;
  5810. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5811. "Content-Type: text/plain\r\n"
  5812. "Transfer-Encoding: chunked\r\n"
  5813. "\r\n"
  5814. "3\r\n"
  5815. "xyz\r\n"
  5816. "NaN\r\n",
  5817. &out);
  5818. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5819. }
  5820. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  5821. std::string out;
  5822. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  5823. "Content-Type: text/plain\r\n"
  5824. "Transfer-Encoding: chunked\r\n"
  5825. "\r\n"
  5826. // Length is too large for 64 bits.
  5827. "1ffffffffffffffff\r\n"
  5828. "xyz\r\n",
  5829. &out);
  5830. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5831. }
  5832. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  5833. test_raw_request("GET /hi HTTP/1.1\r\n"
  5834. "Content-Type: text/plain\r\n\r");
  5835. }
  5836. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  5837. std::string out;
  5838. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  5839. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5840. }
  5841. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  5842. Server svr;
  5843. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  5844. EXPECT_TRUE(!req.remote_addr.empty());
  5845. });
  5846. thread t = thread([&] { svr.listen(HOST, PORT); });
  5847. auto se = detail::scope_exit([&] {
  5848. svr.stop();
  5849. t.join();
  5850. ASSERT_FALSE(svr.is_running());
  5851. });
  5852. svr.wait_until_ready();
  5853. // Send an invalid request line to trigger Bad Request
  5854. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  5855. std::string out;
  5856. ASSERT_TRUE(send_request(5, bad_req, &out));
  5857. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5858. }
  5859. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  5860. std::string out;
  5861. std::string request(
  5862. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  5863. test_raw_request(request, &out);
  5864. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5865. }
  5866. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  5867. std::string out;
  5868. std::string request(
  5869. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  5870. test_raw_request(request, &out);
  5871. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5872. }
  5873. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  5874. std::string out;
  5875. std::string request(
  5876. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  5877. test_raw_request(request, &out);
  5878. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  5879. }
  5880. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  5881. std::string out;
  5882. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  5883. "Test: \r\n\r\n",
  5884. &out);
  5885. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  5886. }
  5887. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  5888. Server svr;
  5889. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  5890. res.set_header("Cache-Control", "no-cache");
  5891. res.set_chunked_content_provider(
  5892. "text/event-stream", [](size_t offset, DataSink &sink) {
  5893. std::string s = "data:";
  5894. s += std::to_string(offset);
  5895. s += "\n\n";
  5896. auto ret = sink.write(s.data(), s.size());
  5897. EXPECT_TRUE(ret);
  5898. std::this_thread::sleep_for(std::chrono::seconds(1));
  5899. return true;
  5900. });
  5901. });
  5902. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5903. svr.wait_until_ready();
  5904. Client client(HOST, PORT);
  5905. const Headers headers = {{"Accept", "text/event-stream"}};
  5906. auto get_thread = std::thread([&client, &headers]() {
  5907. auto res = client.Get(
  5908. "/events", headers,
  5909. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  5910. });
  5911. auto se = detail::scope_exit([&] {
  5912. svr.stop();
  5913. get_thread.join();
  5914. listen_thread.join();
  5915. ASSERT_FALSE(svr.is_running());
  5916. });
  5917. // Give GET time to get a few messages.
  5918. std::this_thread::sleep_for(std::chrono::seconds(2));
  5919. }
  5920. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  5921. httplib::Server svr;
  5922. svr.Post("/hi",
  5923. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5924. res.status = StatusCode::OK_200;
  5925. });
  5926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5927. svr.wait_until_ready();
  5928. Client cli(HOST, PORT);
  5929. auto res = cli.Post("/hi", "data", "text/plain");
  5930. ASSERT_TRUE(res);
  5931. EXPECT_EQ(StatusCode::OK_200, res->status);
  5932. svr.stop();
  5933. thread.join();
  5934. ASSERT_FALSE(svr.is_running());
  5935. res = cli.Post("/hi", "data", "text/plain");
  5936. ASSERT_FALSE(res);
  5937. }
  5938. TEST(ServerStopTest, ListenFailure) {
  5939. Server svr;
  5940. auto t = thread([&]() {
  5941. auto ret = svr.listen("????", PORT);
  5942. EXPECT_FALSE(ret);
  5943. });
  5944. svr.wait_until_ready();
  5945. svr.stop();
  5946. t.join();
  5947. }
  5948. TEST(ServerStopTest, Decommision) {
  5949. Server svr;
  5950. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  5951. for (int i = 0; i < 4; i++) {
  5952. auto is_even = !(i % 2);
  5953. std::thread t{[&] {
  5954. try {
  5955. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5956. if (is_even) {
  5957. throw std::runtime_error("Some thing that happens to go wrong.");
  5958. }
  5959. svr.listen(HOST, PORT);
  5960. } catch (...) { svr.decommission(); }
  5961. }};
  5962. svr.wait_until_ready();
  5963. // Server is up
  5964. {
  5965. Client cli(HOST, PORT);
  5966. auto res = cli.Get("/hi");
  5967. if (is_even) {
  5968. EXPECT_FALSE(res);
  5969. } else {
  5970. EXPECT_TRUE(res);
  5971. EXPECT_EQ("hi...", res->body);
  5972. }
  5973. }
  5974. svr.stop();
  5975. t.join();
  5976. // Server is down...
  5977. {
  5978. Client cli(HOST, PORT);
  5979. auto res = cli.Get("/hi");
  5980. EXPECT_FALSE(res);
  5981. }
  5982. }
  5983. }
  5984. // Helper function for string body upload progress tests
  5985. template <typename SetupHandler, typename ClientCall>
  5986. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  5987. ClientCall &&client_call,
  5988. const string &body) {
  5989. Server svr;
  5990. setup_handler(svr);
  5991. thread t = thread([&]() { svr.listen(HOST, PORT); });
  5992. auto se = detail::scope_exit([&] {
  5993. svr.stop();
  5994. t.join();
  5995. });
  5996. svr.wait_until_ready();
  5997. Client cli(HOST, PORT);
  5998. vector<uint64_t> progress_values;
  5999. bool progress_called = false;
  6000. auto res =
  6001. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  6002. progress_values.push_back(current);
  6003. progress_called = true;
  6004. return true;
  6005. });
  6006. ASSERT_TRUE(res);
  6007. EXPECT_EQ(200, res->status);
  6008. EXPECT_TRUE(progress_called);
  6009. }
  6010. TEST(UploadProgressTest, PostStringBodyBasic) {
  6011. TestStringBodyUploadProgress(
  6012. [](Server &svr) {
  6013. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6014. res.set_content("received", "text/plain");
  6015. });
  6016. },
  6017. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6018. return cli.Post("/test", body, "text/plain", progress_callback);
  6019. },
  6020. "test data for upload progress");
  6021. }
  6022. TEST(UploadProgressTest, PutStringBodyBasic) {
  6023. TestStringBodyUploadProgress(
  6024. [](Server &svr) {
  6025. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  6026. res.set_content("put received", "text/plain");
  6027. });
  6028. },
  6029. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6030. return cli.Put("/test", body, "text/plain", progress_callback);
  6031. },
  6032. "put test data for upload progress");
  6033. }
  6034. TEST(UploadProgressTest, PatchStringBodyBasic) {
  6035. TestStringBodyUploadProgress(
  6036. [](Server &svr) {
  6037. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  6038. res.set_content("patch received", "text/plain");
  6039. });
  6040. },
  6041. [](Client &cli, const string &body, UploadProgress progress_callback) {
  6042. return cli.Patch("/test", body, "text/plain", progress_callback);
  6043. },
  6044. "patch test data for upload progress");
  6045. }
  6046. // Helper function for content provider upload progress tests
  6047. template <typename SetupHandler, typename ClientCall>
  6048. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  6049. ClientCall &&client_call) {
  6050. Server svr;
  6051. setup_handler(svr);
  6052. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6053. auto se = detail::scope_exit([&] {
  6054. svr.stop();
  6055. t.join();
  6056. });
  6057. svr.wait_until_ready();
  6058. Client cli(HOST, PORT);
  6059. vector<uint64_t> progress_values;
  6060. auto res =
  6061. client_call(cli, [&](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, PostContentProviderProgress) {
  6070. TestContentProviderUploadProgress(
  6071. [](Server &svr) {
  6072. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  6073. res.set_content("provider received", "text/plain");
  6074. });
  6075. },
  6076. [](Client &cli, UploadProgress progress_callback) {
  6077. return cli.Post(
  6078. "/test", 10,
  6079. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  6080. sink.os << "test data";
  6081. return true;
  6082. },
  6083. "text/plain", progress_callback);
  6084. });
  6085. }
  6086. // Helper function for multipart upload progress tests
  6087. template <typename SetupHandler, typename ClientCall>
  6088. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  6089. ClientCall &&client_call,
  6090. const string &endpoint) {
  6091. Server svr;
  6092. setup_handler(svr);
  6093. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6094. auto se = detail::scope_exit([&] {
  6095. svr.stop();
  6096. t.join();
  6097. });
  6098. svr.wait_until_ready();
  6099. Client cli(HOST, PORT);
  6100. vector<uint64_t> progress_values;
  6101. UploadFormDataItems items = {
  6102. {"field1", "value1", "", ""},
  6103. {"field2", "longer value for progress tracking test", "", ""},
  6104. {"file1", "file content data for upload progress", "test.txt",
  6105. "text/plain"}};
  6106. auto res = client_call(cli, endpoint, items,
  6107. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6108. progress_values.push_back(current);
  6109. return true;
  6110. });
  6111. ASSERT_TRUE(res);
  6112. EXPECT_EQ(200, res->status);
  6113. EXPECT_FALSE(progress_values.empty());
  6114. }
  6115. TEST(UploadProgressTest, PostMultipartProgress) {
  6116. TestMultipartUploadProgress(
  6117. [](Server &svr) {
  6118. svr.Post("/multipart", [](const Request &req, Response &res) {
  6119. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  6120. res.set_content("multipart received", "text/plain");
  6121. });
  6122. },
  6123. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  6124. UploadProgress progress_callback) {
  6125. return cli.Post(endpoint, items, progress_callback);
  6126. },
  6127. "/multipart");
  6128. }
  6129. // Helper function for basic download progress tests
  6130. template <typename SetupHandler, typename ClientCall>
  6131. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  6132. ClientCall &&client_call, const string &endpoint,
  6133. size_t expected_content_size) {
  6134. Server svr;
  6135. setup_handler(svr);
  6136. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6137. auto se = detail::scope_exit([&] {
  6138. svr.stop();
  6139. t.join();
  6140. });
  6141. svr.wait_until_ready();
  6142. Client cli(HOST, PORT);
  6143. vector<uint64_t> progress_values;
  6144. auto res = client_call(cli, endpoint,
  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, res->body.size());
  6153. }
  6154. TEST(DownloadProgressTest, GetBasic) {
  6155. TestBasicDownloadProgress(
  6156. [](Server &svr) {
  6157. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  6158. string content(1000, 'D');
  6159. res.set_content(content, "text/plain");
  6160. });
  6161. },
  6162. [](Client &cli, const string &endpoint,
  6163. DownloadProgress progress_callback) {
  6164. return cli.Get(endpoint, progress_callback);
  6165. },
  6166. "/download", 1000u);
  6167. }
  6168. // Helper function for content receiver download progress tests
  6169. template <typename SetupHandler, typename ClientCall>
  6170. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  6171. ClientCall &&client_call,
  6172. const string &endpoint,
  6173. size_t expected_content_size) {
  6174. Server svr;
  6175. setup_handler(svr);
  6176. thread t = thread([&]() { svr.listen(HOST, PORT); });
  6177. auto se = detail::scope_exit([&] {
  6178. svr.stop();
  6179. t.join();
  6180. });
  6181. svr.wait_until_ready();
  6182. Client cli(HOST, PORT);
  6183. vector<uint64_t> progress_values;
  6184. string received_body;
  6185. auto res = client_call(
  6186. cli, endpoint,
  6187. [&](const char *data, size_t data_length) -> bool {
  6188. received_body.append(data, data_length);
  6189. return true;
  6190. },
  6191. [&](uint64_t current, uint64_t /*total*/) -> bool {
  6192. progress_values.push_back(current);
  6193. return true;
  6194. });
  6195. ASSERT_TRUE(res);
  6196. EXPECT_EQ(200, res->status);
  6197. EXPECT_FALSE(progress_values.empty());
  6198. EXPECT_EQ(expected_content_size, received_body.size());
  6199. EXPECT_TRUE(res->body.empty());
  6200. }
  6201. TEST(DownloadProgressTest, GetWithContentReceiver) {
  6202. TestContentReceiverDownloadProgress(
  6203. [](Server &svr) {
  6204. svr.Get("/download-receiver",
  6205. [](const Request & /*req*/, Response &res) {
  6206. string content(2000, 'R');
  6207. res.set_content(content, "text/plain");
  6208. });
  6209. },
  6210. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  6211. DownloadProgress progress_callback) {
  6212. return cli.Get(endpoint, content_receiver, progress_callback);
  6213. },
  6214. "/download-receiver", 2000u);
  6215. }
  6216. TEST(StreamingTest, NoContentLengthStreaming) {
  6217. Server svr;
  6218. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  6219. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  6220. if (offset < 6) {
  6221. sink.os << (offset < 3 ? "a" : "b");
  6222. } else {
  6223. sink.done();
  6224. }
  6225. return true;
  6226. });
  6227. });
  6228. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6229. auto listen_se = detail::scope_exit([&] {
  6230. svr.stop();
  6231. listen_thread.join();
  6232. ASSERT_FALSE(svr.is_running());
  6233. });
  6234. svr.wait_until_ready();
  6235. Client client(HOST, PORT);
  6236. auto get_thread = std::thread([&client]() {
  6237. std::string s;
  6238. auto res =
  6239. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  6240. s += std::string(data, len);
  6241. return true;
  6242. });
  6243. ASSERT_TRUE(res);
  6244. EXPECT_EQ(StatusCode::OK_200, res->status);
  6245. EXPECT_EQ("aaabbb", s);
  6246. });
  6247. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  6248. // Give GET time to get a few messages.
  6249. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6250. }
  6251. TEST(MountTest, Unmount) {
  6252. Server svr;
  6253. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6254. auto se = detail::scope_exit([&] {
  6255. svr.stop();
  6256. listen_thread.join();
  6257. ASSERT_FALSE(svr.is_running());
  6258. });
  6259. svr.wait_until_ready();
  6260. Client cli("localhost", PORT);
  6261. svr.set_mount_point("/mount2", "./www2");
  6262. auto res = cli.Get("/");
  6263. ASSERT_TRUE(res);
  6264. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6265. res = cli.Get("/mount2/dir/test.html");
  6266. ASSERT_TRUE(res);
  6267. EXPECT_EQ(StatusCode::OK_200, res->status);
  6268. svr.set_mount_point("/", "./www");
  6269. res = cli.Get("/dir/");
  6270. ASSERT_TRUE(res);
  6271. EXPECT_EQ(StatusCode::OK_200, res->status);
  6272. svr.remove_mount_point("/");
  6273. res = cli.Get("/dir/");
  6274. ASSERT_TRUE(res);
  6275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6276. svr.remove_mount_point("/mount2");
  6277. res = cli.Get("/mount2/dir/test.html");
  6278. ASSERT_TRUE(res);
  6279. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6280. }
  6281. TEST(MountTest, Redicect) {
  6282. Server svr;
  6283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6284. auto se = detail::scope_exit([&] {
  6285. svr.stop();
  6286. listen_thread.join();
  6287. ASSERT_FALSE(svr.is_running());
  6288. });
  6289. svr.set_mount_point("/", "./www");
  6290. svr.wait_until_ready();
  6291. Client cli("localhost", PORT);
  6292. auto res = cli.Get("/dir/");
  6293. ASSERT_TRUE(res);
  6294. EXPECT_EQ(StatusCode::OK_200, res->status);
  6295. res = cli.Get("/dir");
  6296. ASSERT_TRUE(res);
  6297. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6298. res = cli.Get("/file");
  6299. ASSERT_TRUE(res);
  6300. EXPECT_EQ(StatusCode::OK_200, res->status);
  6301. res = cli.Get("/file/");
  6302. ASSERT_TRUE(res);
  6303. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6304. cli.set_follow_location(true);
  6305. res = cli.Get("/dir");
  6306. ASSERT_TRUE(res);
  6307. EXPECT_EQ(StatusCode::OK_200, res->status);
  6308. }
  6309. TEST(MountTest, MultibytesPathName) {
  6310. Server svr;
  6311. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6312. auto se = detail::scope_exit([&] {
  6313. svr.stop();
  6314. listen_thread.join();
  6315. ASSERT_FALSE(svr.is_running());
  6316. });
  6317. svr.set_mount_point("/", "./www");
  6318. svr.wait_until_ready();
  6319. Client cli("localhost", PORT);
  6320. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  6321. ASSERT_TRUE(res);
  6322. EXPECT_EQ(StatusCode::OK_200, res->status);
  6323. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  6324. }
  6325. TEST(KeepAliveTest, ReadTimeout) {
  6326. Server svr;
  6327. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6328. std::this_thread::sleep_for(std::chrono::seconds(2));
  6329. res.set_content("a", "text/plain");
  6330. });
  6331. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6332. res.set_content("b", "text/plain");
  6333. });
  6334. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6335. auto se = detail::scope_exit([&] {
  6336. svr.stop();
  6337. listen_thread.join();
  6338. ASSERT_FALSE(svr.is_running());
  6339. });
  6340. svr.wait_until_ready();
  6341. Client cli("localhost", PORT);
  6342. cli.set_keep_alive(true);
  6343. cli.set_read_timeout(std::chrono::seconds(1));
  6344. auto resa = cli.Get("/a");
  6345. ASSERT_FALSE(resa);
  6346. EXPECT_EQ(Error::Read, resa.error());
  6347. auto resb = cli.Get("/b");
  6348. ASSERT_TRUE(resb);
  6349. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6350. EXPECT_EQ("b", resb->body);
  6351. }
  6352. TEST(KeepAliveTest, MaxCount) {
  6353. size_t keep_alive_max_count = 3;
  6354. Server svr;
  6355. svr.set_keep_alive_max_count(keep_alive_max_count);
  6356. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6357. res.set_content("Hello World!", "text/plain");
  6358. });
  6359. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6360. auto se = detail::scope_exit([&] {
  6361. svr.stop();
  6362. listen_thread.join();
  6363. ASSERT_FALSE(svr.is_running());
  6364. });
  6365. svr.wait_until_ready();
  6366. Client cli(HOST, PORT);
  6367. cli.set_keep_alive(true);
  6368. for (size_t i = 0; i < 5; i++) {
  6369. auto result = cli.Get("/hi");
  6370. ASSERT_TRUE(result);
  6371. EXPECT_EQ(StatusCode::OK_200, result->status);
  6372. if (i == keep_alive_max_count - 1) {
  6373. EXPECT_EQ("close", result->get_header_value("Connection"));
  6374. } else {
  6375. EXPECT_FALSE(result->has_header("Connection"));
  6376. }
  6377. }
  6378. }
  6379. TEST(KeepAliveTest, Issue1041) {
  6380. Server svr;
  6381. svr.set_keep_alive_timeout(3);
  6382. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6383. res.set_content("Hello World!", "text/plain");
  6384. });
  6385. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6386. auto se = detail::scope_exit([&] {
  6387. svr.stop();
  6388. listen_thread.join();
  6389. ASSERT_FALSE(svr.is_running());
  6390. });
  6391. svr.wait_until_ready();
  6392. Client cli(HOST, PORT);
  6393. cli.set_keep_alive(true);
  6394. auto result = cli.Get("/hi");
  6395. ASSERT_TRUE(result);
  6396. EXPECT_EQ(StatusCode::OK_200, result->status);
  6397. std::this_thread::sleep_for(std::chrono::seconds(5));
  6398. result = cli.Get("/hi");
  6399. ASSERT_TRUE(result);
  6400. EXPECT_EQ(StatusCode::OK_200, result->status);
  6401. }
  6402. TEST(KeepAliveTest, Issue1959) {
  6403. Server svr;
  6404. svr.set_keep_alive_timeout(5);
  6405. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6406. res.set_content("a", "text/plain");
  6407. });
  6408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6409. auto se = detail::scope_exit([&] {
  6410. if (!svr.is_running()) return;
  6411. svr.stop();
  6412. listen_thread.join();
  6413. ASSERT_FALSE(svr.is_running());
  6414. });
  6415. svr.wait_until_ready();
  6416. Client cli("localhost", PORT);
  6417. cli.set_keep_alive(true);
  6418. using namespace std::chrono;
  6419. auto start = steady_clock::now();
  6420. cli.Get("/a");
  6421. svr.stop();
  6422. listen_thread.join();
  6423. auto end = steady_clock::now();
  6424. auto elapsed = duration_cast<milliseconds>(end - start).count();
  6425. EXPECT_LT(elapsed, 5000);
  6426. }
  6427. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6428. TEST(KeepAliveTest, SSLClientReconnection) {
  6429. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6430. ASSERT_TRUE(svr.is_valid());
  6431. svr.set_keep_alive_timeout(1);
  6432. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  6433. res.set_content("Hello World!", "text/plain");
  6434. });
  6435. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6436. auto se = detail::scope_exit([&] {
  6437. svr.stop();
  6438. listen_thread.join();
  6439. ASSERT_FALSE(svr.is_running());
  6440. });
  6441. svr.wait_until_ready();
  6442. SSLClient cli(HOST, PORT);
  6443. cli.enable_server_certificate_verification(false);
  6444. cli.set_keep_alive(true);
  6445. auto result = cli.Get("/hi");
  6446. ASSERT_TRUE(result);
  6447. EXPECT_EQ(StatusCode::OK_200, result->status);
  6448. result = cli.Get("/hi");
  6449. ASSERT_TRUE(result);
  6450. EXPECT_EQ(StatusCode::OK_200, result->status);
  6451. std::this_thread::sleep_for(std::chrono::seconds(2));
  6452. // Recoonect
  6453. result = cli.Get("/hi");
  6454. ASSERT_TRUE(result);
  6455. EXPECT_EQ(StatusCode::OK_200, result->status);
  6456. result = cli.Get("/hi");
  6457. ASSERT_TRUE(result);
  6458. EXPECT_EQ(StatusCode::OK_200, result->status);
  6459. }
  6460. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  6461. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6462. ASSERT_TRUE(svr.is_valid());
  6463. svr.set_keep_alive_timeout(1);
  6464. std::string content = "reconnect";
  6465. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  6466. res.set_content("Hello World!", "text/plain");
  6467. });
  6468. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6469. auto se = detail::scope_exit([&] {
  6470. svr.stop();
  6471. listen_thread.join();
  6472. ASSERT_FALSE(svr.is_running());
  6473. });
  6474. svr.wait_until_ready();
  6475. SSLClient cli(HOST, PORT);
  6476. cli.enable_server_certificate_verification(false);
  6477. cli.set_keep_alive(true);
  6478. auto result = cli.Post(
  6479. "/hi", content.size(),
  6480. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6481. sink.write(content.c_str(), content.size());
  6482. return true;
  6483. },
  6484. "text/plain");
  6485. ASSERT_TRUE(result);
  6486. EXPECT_EQ(200, result->status);
  6487. std::this_thread::sleep_for(std::chrono::seconds(2));
  6488. // Recoonect
  6489. result = cli.Post(
  6490. "/hi", content.size(),
  6491. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6492. sink.write(content.c_str(), content.size());
  6493. return true;
  6494. },
  6495. "text/plain");
  6496. ASSERT_TRUE(result);
  6497. EXPECT_EQ(200, result->status);
  6498. result = cli.Post(
  6499. "/hi", content.size(),
  6500. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6501. sink.write(content.c_str(), content.size());
  6502. return true;
  6503. },
  6504. "text/plain");
  6505. ASSERT_TRUE(result);
  6506. EXPECT_EQ(200, result->status);
  6507. }
  6508. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  6509. {
  6510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6511. ASSERT_TRUE(svr.is_valid());
  6512. svr.Get("/sni", [&](const Request &req, Response &res) {
  6513. std::string expected;
  6514. if (req.ssl) {
  6515. if (const char *sni =
  6516. SSL_get_servername(req.ssl, TLSEXT_NAMETYPE_host_name)) {
  6517. expected = sni;
  6518. }
  6519. }
  6520. EXPECT_EQ(expected, req.get_param_value("expected"));
  6521. res.set_content("ok", "text/plain");
  6522. });
  6523. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  6524. auto se = detail::scope_exit([&] {
  6525. svr.stop();
  6526. listen_thread.join();
  6527. ASSERT_FALSE(svr.is_running());
  6528. });
  6529. svr.wait_until_ready();
  6530. {
  6531. SSLClient cli("localhost", PORT);
  6532. cli.enable_server_certificate_verification(false);
  6533. auto res = cli.Get("/sni?expected=localhost");
  6534. ASSERT_TRUE(res);
  6535. }
  6536. {
  6537. SSLClient cli("::1", PORT);
  6538. cli.enable_server_certificate_verification(false);
  6539. auto res = cli.Get("/sni?expected=");
  6540. // NOTE: This may fail if the server is listening on IPv4 only
  6541. // (e.g., when localhost resolves to 127.0.0.1 only)
  6542. if (res) {
  6543. EXPECT_EQ(StatusCode::OK_200, res->status);
  6544. } else {
  6545. EXPECT_EQ(Error::Connection, res.error());
  6546. }
  6547. }
  6548. }
  6549. }
  6550. #endif
  6551. TEST(ClientProblemDetectionTest, ContentProvider) {
  6552. Server svr;
  6553. size_t content_length = 1024 * 1024;
  6554. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6555. res.set_content_provider(
  6556. content_length, "text/plain",
  6557. [&](size_t offset, size_t length, DataSink &sink) {
  6558. auto out_len = std::min(length, static_cast<size_t>(1024));
  6559. std::string out(out_len, '@');
  6560. sink.write(out.data(), out_len);
  6561. return offset < 4096;
  6562. },
  6563. [](bool success) { ASSERT_FALSE(success); });
  6564. });
  6565. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  6566. res.set_content_provider(
  6567. 0, "text/plain",
  6568. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  6569. EXPECT_TRUE(false);
  6570. return true;
  6571. },
  6572. [](bool success) { ASSERT_FALSE(success); });
  6573. });
  6574. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6575. auto se = detail::scope_exit([&] {
  6576. svr.stop();
  6577. listen_thread.join();
  6578. ASSERT_FALSE(svr.is_running());
  6579. });
  6580. svr.wait_until_ready();
  6581. Client cli("localhost", PORT);
  6582. {
  6583. auto res = cli.Get("/hi", [&](const char * /*data*/,
  6584. size_t /*data_length*/) { return false; });
  6585. ASSERT_FALSE(res);
  6586. }
  6587. {
  6588. auto res = cli.Get("/empty", [&](const char * /*data*/,
  6589. size_t /*data_length*/) { return false; });
  6590. ASSERT_TRUE(res);
  6591. }
  6592. }
  6593. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  6594. Server svr;
  6595. svr.set_error_handler([](Request const &, Response &res) -> void {
  6596. res.set_chunked_content_provider(
  6597. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6598. sink.os << "hello";
  6599. sink.os << "world";
  6600. sink.done();
  6601. return true;
  6602. });
  6603. });
  6604. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6605. auto se = detail::scope_exit([&] {
  6606. svr.stop();
  6607. listen_thread.join();
  6608. ASSERT_FALSE(svr.is_running());
  6609. });
  6610. svr.wait_until_ready();
  6611. Client cli("localhost", PORT);
  6612. auto res = cli.Get("/");
  6613. ASSERT_TRUE(res);
  6614. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6615. EXPECT_EQ("helloworld", res->body);
  6616. }
  6617. TEST(LongPollingTest, ClientCloseDetection) {
  6618. Server svr;
  6619. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  6620. res.set_chunked_content_provider(
  6621. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  6622. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  6623. sink.os << "hello";
  6624. auto count = 10;
  6625. while (count > 0 && sink.is_writable()) {
  6626. this_thread::sleep_for(chrono::milliseconds(10));
  6627. count--;
  6628. }
  6629. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  6630. return true;
  6631. });
  6632. });
  6633. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6634. auto se = detail::scope_exit([&] {
  6635. svr.stop();
  6636. listen_thread.join();
  6637. ASSERT_FALSE(svr.is_running());
  6638. });
  6639. svr.wait_until_ready();
  6640. Client cli("localhost", PORT);
  6641. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  6642. EXPECT_EQ("hello", string(data, data_length));
  6643. return false; // close the socket immediately.
  6644. });
  6645. ASSERT_FALSE(res);
  6646. }
  6647. TEST(GetWithParametersTest, GetWithParameters) {
  6648. Server svr;
  6649. svr.Get("/", [&](const Request &req, Response &) {
  6650. EXPECT_EQ("world", req.get_param_value("hello"));
  6651. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6652. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6653. });
  6654. svr.Get("/params", [&](const Request &req, Response &) {
  6655. EXPECT_EQ("world", req.get_param_value("hello"));
  6656. EXPECT_EQ("world2", req.get_param_value("hello2"));
  6657. EXPECT_EQ("world3", req.get_param_value("hello3"));
  6658. });
  6659. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  6660. EXPECT_EQ("resource-id", req.matches[1]);
  6661. EXPECT_EQ("foo", req.get_param_value("param1"));
  6662. EXPECT_EQ("bar", req.get_param_value("param2"));
  6663. });
  6664. svr.Get("/users/:id", [&](const Request &req, Response &) {
  6665. EXPECT_EQ("user-id", req.path_params.at("id"));
  6666. EXPECT_EQ("foo", req.get_param_value("param1"));
  6667. EXPECT_EQ("bar", req.get_param_value("param2"));
  6668. });
  6669. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  6670. auto se = detail::scope_exit([&] {
  6671. svr.stop();
  6672. listen_thread.join();
  6673. ASSERT_FALSE(svr.is_running());
  6674. });
  6675. svr.wait_until_ready();
  6676. {
  6677. Client cli(HOST, PORT);
  6678. Params params;
  6679. params.emplace("hello", "world");
  6680. params.emplace("hello2", "world2");
  6681. params.emplace("hello3", "world3");
  6682. auto res = cli.Get("/", params, Headers{});
  6683. ASSERT_TRUE(res);
  6684. EXPECT_EQ(StatusCode::OK_200, res->status);
  6685. }
  6686. {
  6687. Client cli(HOST, PORT);
  6688. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  6689. ASSERT_TRUE(res);
  6690. EXPECT_EQ(StatusCode::OK_200, res->status);
  6691. }
  6692. {
  6693. Client cli(HOST, PORT);
  6694. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  6695. ASSERT_TRUE(res);
  6696. EXPECT_EQ(StatusCode::OK_200, res->status);
  6697. }
  6698. {
  6699. Client cli(HOST, PORT);
  6700. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  6701. ASSERT_TRUE(res);
  6702. EXPECT_EQ(StatusCode::OK_200, res->status);
  6703. }
  6704. }
  6705. TEST(GetWithParametersTest, GetWithParameters2) {
  6706. Server svr;
  6707. svr.Get("/", [&](const Request &req, Response &res) {
  6708. auto text = req.get_param_value("hello");
  6709. res.set_content(text, "text/plain");
  6710. });
  6711. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6712. auto se = detail::scope_exit([&] {
  6713. svr.stop();
  6714. listen_thread.join();
  6715. ASSERT_FALSE(svr.is_running());
  6716. });
  6717. svr.wait_until_ready();
  6718. Client cli("localhost", PORT);
  6719. Params params;
  6720. params.emplace("hello", "world");
  6721. std::string body;
  6722. auto res = cli.Get("/", params, Headers{},
  6723. [&](const char *data, size_t data_length) {
  6724. body.append(data, data_length);
  6725. return true;
  6726. });
  6727. ASSERT_TRUE(res);
  6728. EXPECT_EQ(StatusCode::OK_200, res->status);
  6729. EXPECT_EQ("world", body);
  6730. }
  6731. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  6732. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  6733. auto host = "httpcan.org";
  6734. auto path = std::string{"/range/32"};
  6735. #else
  6736. auto host = "nghttp2.org";
  6737. auto path = std::string{"/httpbin/range/32"};
  6738. #endif
  6739. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6740. SSLClient cli(host);
  6741. #else
  6742. Client cli(host);
  6743. #endif
  6744. cli.set_default_headers({make_range_header({{1, 10}})});
  6745. cli.set_connection_timeout(5);
  6746. {
  6747. auto res = cli.Get(path);
  6748. ASSERT_TRUE(res);
  6749. EXPECT_EQ("bcdefghijk", res->body);
  6750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6751. }
  6752. {
  6753. auto res = cli.Get(path);
  6754. ASSERT_TRUE(res);
  6755. EXPECT_EQ("bcdefghijk", res->body);
  6756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6757. }
  6758. }
  6759. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  6760. Server svr;
  6761. svr.set_default_headers({{"Hello", "World"}});
  6762. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  6763. res.set_content("ok", "text/plain");
  6764. });
  6765. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6766. auto se = detail::scope_exit([&] {
  6767. svr.stop();
  6768. listen_thread.join();
  6769. ASSERT_FALSE(svr.is_running());
  6770. });
  6771. svr.wait_until_ready();
  6772. Client cli("localhost", PORT);
  6773. auto res = cli.Get("/");
  6774. ASSERT_TRUE(res);
  6775. EXPECT_EQ(StatusCode::OK_200, res->status);
  6776. EXPECT_EQ("ok", res->body);
  6777. EXPECT_EQ("World", res->get_header_value("Hello"));
  6778. }
  6779. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6780. TEST(KeepAliveTest, ReadTimeoutSSL) {
  6781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  6782. ASSERT_TRUE(svr.is_valid());
  6783. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  6784. std::this_thread::sleep_for(std::chrono::seconds(2));
  6785. res.set_content("a", "text/plain");
  6786. });
  6787. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  6788. res.set_content("b", "text/plain");
  6789. });
  6790. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  6791. auto se = detail::scope_exit([&] {
  6792. svr.stop();
  6793. listen_thread.join();
  6794. ASSERT_FALSE(svr.is_running());
  6795. });
  6796. svr.wait_until_ready();
  6797. SSLClient cli("localhost", PORT);
  6798. cli.enable_server_certificate_verification(false);
  6799. cli.set_keep_alive(true);
  6800. cli.set_read_timeout(std::chrono::seconds(1));
  6801. auto resa = cli.Get("/a");
  6802. ASSERT_TRUE(!resa);
  6803. EXPECT_EQ(Error::Read, resa.error());
  6804. auto resb = cli.Get("/b");
  6805. ASSERT_TRUE(resb);
  6806. EXPECT_EQ(StatusCode::OK_200, resb->status);
  6807. EXPECT_EQ("b", resb->body);
  6808. }
  6809. #endif
  6810. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  6811. protected:
  6812. ServerTestWithAI_PASSIVE()
  6813. : cli_(HOST, PORT)
  6814. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6815. ,
  6816. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6817. #endif
  6818. {
  6819. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6820. cli_.enable_server_certificate_verification(false);
  6821. #endif
  6822. }
  6823. virtual void SetUp() {
  6824. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  6825. res.set_content("Hello World!", "text/plain");
  6826. });
  6827. t_ = thread(
  6828. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  6829. svr_.wait_until_ready();
  6830. }
  6831. virtual void TearDown() {
  6832. svr_.stop();
  6833. t_.join();
  6834. }
  6835. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6836. SSLClient cli_;
  6837. SSLServer svr_;
  6838. #else
  6839. Client cli_;
  6840. Server svr_;
  6841. #endif
  6842. thread t_;
  6843. };
  6844. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  6845. auto res = cli_.Get("/hi");
  6846. ASSERT_TRUE(res);
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6849. EXPECT_EQ("Hello World!", res->body);
  6850. }
  6851. class ServerUpDownTest : public ::testing::Test {
  6852. protected:
  6853. ServerUpDownTest() : cli_(HOST, PORT) {}
  6854. virtual void SetUp() {
  6855. t_ = thread([&]() {
  6856. svr_.bind_to_any_port(HOST);
  6857. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  6858. ASSERT_TRUE(svr_.listen_after_bind());
  6859. });
  6860. svr_.wait_until_ready();
  6861. }
  6862. virtual void TearDown() {
  6863. svr_.stop();
  6864. t_.join();
  6865. }
  6866. Client cli_;
  6867. Server svr_;
  6868. thread t_;
  6869. };
  6870. TEST_F(ServerUpDownTest, QuickStartStop) {
  6871. // Should not crash, especially when run with
  6872. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  6873. }
  6874. class PayloadMaxLengthTest : public ::testing::Test {
  6875. protected:
  6876. PayloadMaxLengthTest()
  6877. : cli_(HOST, PORT)
  6878. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6879. ,
  6880. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6881. #endif
  6882. {
  6883. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6884. cli_.enable_server_certificate_verification(false);
  6885. #endif
  6886. }
  6887. virtual void SetUp() {
  6888. svr_.set_payload_max_length(8);
  6889. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  6890. res.set_content("test", "text/plain");
  6891. });
  6892. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6893. svr_.wait_until_ready();
  6894. }
  6895. virtual void TearDown() {
  6896. svr_.stop();
  6897. t_.join();
  6898. }
  6899. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  6900. SSLClient cli_;
  6901. SSLServer svr_;
  6902. #else
  6903. Client cli_;
  6904. Server svr_;
  6905. #endif
  6906. thread t_;
  6907. };
  6908. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  6909. auto res = cli_.Post("/test", "123456789", "text/plain");
  6910. ASSERT_TRUE(res);
  6911. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6912. res = cli_.Post("/test", "12345678", "text/plain");
  6913. ASSERT_TRUE(res);
  6914. EXPECT_EQ(StatusCode::OK_200, res->status);
  6915. }
  6916. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  6917. // Test chunked encoding with payload exceeding the 8-byte limit
  6918. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  6919. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  6920. ASSERT_TRUE(res);
  6921. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  6922. }
  6923. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  6924. // Test chunked encoding with payload within the 8-byte limit
  6925. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  6926. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  6927. ASSERT_TRUE(res);
  6928. EXPECT_EQ(StatusCode::OK_200, res->status);
  6929. }
  6930. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  6931. // Test using send_request to send chunked data exceeding payload limit
  6932. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  6933. "Host: " +
  6934. std::string(HOST) + ":" + std::to_string(PORT) +
  6935. "\r\n"
  6936. "Transfer-Encoding: chunked\r\n"
  6937. "Connection: close\r\n"
  6938. "\r\n"
  6939. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  6940. "0123456789\r\n"
  6941. "0\r\n" // End chunk
  6942. "\r\n";
  6943. std::string response;
  6944. bool result = send_request(1, chunked_request, &response);
  6945. if (!result) {
  6946. // If send_request fails, it might be because the server closed the
  6947. // connection due to payload limit enforcement, which is acceptable
  6948. SUCCEED()
  6949. << "Server rejected oversized chunked request (connection closed)";
  6950. } else {
  6951. // If we got a response, check if it's an error response or connection was
  6952. // closed early Short response length indicates connection was closed due to
  6953. // payload limit
  6954. if (response.length() <= 10) {
  6955. SUCCEED() << "Server closed connection for oversized chunked request";
  6956. } else {
  6957. // Check for error status codes
  6958. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6959. response.find("Payload Too Large") != std::string::npos ||
  6960. response.find("400") != std::string::npos);
  6961. }
  6962. }
  6963. }
  6964. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  6965. // Test request without Content-Length header exceeding payload limit
  6966. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6967. "Host: " +
  6968. std::string(HOST) + ":" +
  6969. std::to_string(PORT) +
  6970. "\r\n"
  6971. "Connection: close\r\n"
  6972. "\r\n";
  6973. // Add payload exceeding the 8-byte limit
  6974. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  6975. request_without_content_length += large_payload;
  6976. std::string response;
  6977. bool result = send_request(1, request_without_content_length, &response);
  6978. if (!result) {
  6979. // If send_request fails, server likely closed connection due to payload
  6980. // limit
  6981. SUCCEED() << "Server rejected oversized request without Content-Length "
  6982. "(connection closed)";
  6983. } else {
  6984. // Check if server responded with error or closed connection early
  6985. if (response.length() <= 10) {
  6986. SUCCEED() << "Server closed connection for oversized request without "
  6987. "Content-Length";
  6988. } else {
  6989. // Check for error status codes
  6990. EXPECT_TRUE(response.find("413") != std::string::npos ||
  6991. response.find("Payload Too Large") != std::string::npos ||
  6992. response.find("400") != std::string::npos);
  6993. }
  6994. }
  6995. }
  6996. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  6997. // Test request without Content-Length header within payload limit
  6998. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  6999. "Host: " +
  7000. std::string(HOST) + ":" +
  7001. std::to_string(PORT) +
  7002. "\r\n"
  7003. "Connection: close\r\n"
  7004. "\r\n";
  7005. // Add payload within the 8-byte limit
  7006. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  7007. request_without_content_length += small_payload;
  7008. std::string response;
  7009. bool result = send_request(1, request_without_content_length, &response);
  7010. // For requests without Content-Length, the server may have different behavior
  7011. // The key is that it should not reject due to payload limit for small
  7012. // payloads
  7013. if (result) {
  7014. // Check for any HTTP response (success or error, but not connection closed)
  7015. if (response.length() > 10) {
  7016. SUCCEED()
  7017. << "Server processed request without Content-Length within limit";
  7018. } else {
  7019. // Short response might indicate connection closed, which is acceptable
  7020. SUCCEED() << "Server closed connection for request without "
  7021. "Content-Length (acceptable behavior)";
  7022. }
  7023. } else {
  7024. // Connection failure might be due to protocol requirements
  7025. SUCCEED() << "Connection issue with request without Content-Length "
  7026. "(environment-specific)";
  7027. }
  7028. }
  7029. class LargePayloadMaxLengthTest : public ::testing::Test {
  7030. protected:
  7031. LargePayloadMaxLengthTest()
  7032. : cli_(HOST, PORT)
  7033. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7034. ,
  7035. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  7036. #endif
  7037. {
  7038. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7039. cli_.enable_server_certificate_verification(false);
  7040. #endif
  7041. }
  7042. virtual void SetUp() {
  7043. // Set 10MB payload limit
  7044. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  7045. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  7046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  7047. res.set_content("Large payload test", "text/plain");
  7048. });
  7049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  7050. svr_.wait_until_ready();
  7051. }
  7052. virtual void TearDown() {
  7053. svr_.stop();
  7054. t_.join();
  7055. }
  7056. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7057. SSLClient cli_;
  7058. SSLServer svr_;
  7059. #else
  7060. Client cli_;
  7061. Server svr_;
  7062. #endif
  7063. thread t_;
  7064. };
  7065. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  7066. // Test chunked encoding with payload within 10MB limit
  7067. std::string medium_payload(5 * 1024 * 1024,
  7068. 'A'); // 5MB payload, within 10MB limit
  7069. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  7070. ASSERT_TRUE(res);
  7071. EXPECT_EQ(StatusCode::OK_200, res->status);
  7072. }
  7073. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  7074. // Test chunked encoding with payload exceeding 10MB limit
  7075. std::string large_payload(12 * 1024 * 1024,
  7076. 'B'); // 12MB payload, exceeds 10MB limit
  7077. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  7078. ASSERT_TRUE(res);
  7079. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  7080. }
  7081. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  7082. // Test request without Content-Length header within 10MB limit
  7083. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7084. "Host: " +
  7085. std::string(HOST) + ":" +
  7086. std::to_string(PORT) +
  7087. "\r\n"
  7088. "Connection: close\r\n"
  7089. "\r\n";
  7090. // Add 1MB payload (within 10MB limit)
  7091. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  7092. request_without_content_length += medium_payload;
  7093. std::string response;
  7094. bool result = send_request(5, request_without_content_length, &response);
  7095. if (result) {
  7096. // Should get a proper HTTP response for payloads within limit
  7097. if (response.length() > 10) {
  7098. SUCCEED() << "Server processed 1MB request without Content-Length within "
  7099. "10MB limit";
  7100. } else {
  7101. SUCCEED() << "Server closed connection (acceptable behavior for no "
  7102. "Content-Length)";
  7103. }
  7104. } else {
  7105. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  7106. }
  7107. }
  7108. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  7109. // Test request without Content-Length header exceeding 10MB limit
  7110. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  7111. "Host: " +
  7112. std::string(HOST) + ":" +
  7113. std::to_string(PORT) +
  7114. "\r\n"
  7115. "Connection: close\r\n"
  7116. "\r\n";
  7117. // Add 12MB payload (exceeds 10MB limit)
  7118. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  7119. request_without_content_length += large_payload;
  7120. std::string response;
  7121. bool result = send_request(10, request_without_content_length, &response);
  7122. if (!result) {
  7123. // Server should close connection due to payload limit
  7124. SUCCEED() << "Server rejected 12MB request without Content-Length "
  7125. "(connection closed)";
  7126. } else {
  7127. // Check for error response
  7128. if (response.length() <= 10) {
  7129. SUCCEED()
  7130. << "Server closed connection for 12MB request exceeding 10MB limit";
  7131. } else {
  7132. EXPECT_TRUE(response.find("413") != std::string::npos ||
  7133. response.find("Payload Too Large") != std::string::npos ||
  7134. response.find("400") != std::string::npos);
  7135. }
  7136. }
  7137. }
  7138. TEST(HostAndPortPropertiesTest, NoSSL) {
  7139. httplib::Client cli("www.google.com", 1234);
  7140. ASSERT_EQ("www.google.com", cli.host());
  7141. ASSERT_EQ(1234, cli.port());
  7142. }
  7143. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  7144. httplib::Client cli("www.google.com:1234");
  7145. ASSERT_EQ("www.google.com", cli.host());
  7146. ASSERT_EQ(1234, cli.port());
  7147. }
  7148. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7149. TEST(HostAndPortPropertiesTest, SSL) {
  7150. httplib::SSLClient cli("www.google.com");
  7151. ASSERT_EQ("www.google.com", cli.host());
  7152. ASSERT_EQ(443, cli.port());
  7153. }
  7154. #endif
  7155. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7156. TEST(SSLClientTest, UpdateCAStore) {
  7157. httplib::SSLClient httplib_client("www.google.com");
  7158. auto ca_store_1 = X509_STORE_new();
  7159. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  7160. nullptr);
  7161. httplib_client.set_ca_cert_store(ca_store_1);
  7162. auto ca_store_2 = X509_STORE_new();
  7163. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  7164. nullptr);
  7165. httplib_client.set_ca_cert_store(ca_store_2);
  7166. }
  7167. TEST(SSLClientTest, ServerNameIndication_Online) {
  7168. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  7169. auto host = "httpcan.org";
  7170. auto path = std::string{"/get"};
  7171. #else
  7172. auto host = "nghttp2.org";
  7173. auto path = std::string{"/httpbin/get"};
  7174. #endif
  7175. SSLClient cli(host, 443);
  7176. auto res = cli.Get(path);
  7177. ASSERT_TRUE(res);
  7178. ASSERT_EQ(StatusCode::OK_200, res->status);
  7179. }
  7180. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  7181. // Use a site that will cause SSL verification failure due to self-signed cert
  7182. SSLClient cli("self-signed.badssl.com", 443);
  7183. cli.enable_server_certificate_verification(true);
  7184. auto res = cli.Get("/");
  7185. ASSERT_TRUE(!res);
  7186. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7187. // For SSL server verification errors, ssl_error should be 0, only
  7188. // ssl_openssl_error should be set
  7189. EXPECT_EQ(0, res.ssl_error());
  7190. // Verify OpenSSL error is captured for SSLServerVerification
  7191. // This occurs when SSL_get_verify_result() returns a verification failure
  7192. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  7193. res.ssl_openssl_error());
  7194. }
  7195. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  7196. // Use a site where hostname doesn't match the certificate
  7197. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  7198. SSLClient cli("wrong.host.badssl.com", 443);
  7199. cli.enable_server_certificate_verification(true);
  7200. cli.enable_server_hostname_verification(true);
  7201. auto res = cli.Get("/");
  7202. ASSERT_TRUE(!res);
  7203. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  7204. // For SSL hostname verification errors, ssl_error should be 0, only
  7205. // ssl_openssl_error should be set
  7206. EXPECT_EQ(0, res.ssl_error());
  7207. // Verify OpenSSL error is captured for SSLServerHostnameVerification
  7208. // This occurs when verify_host() fails due to hostname mismatch
  7209. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  7210. res.ssl_openssl_error());
  7211. }
  7212. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  7213. Client cli("https://google.com");
  7214. auto res = cli.Get("/");
  7215. ASSERT_TRUE(res);
  7216. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7217. }
  7218. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  7219. SSLClient cli("google.com");
  7220. cli.set_ca_cert_path(CA_CERT_FILE);
  7221. auto res = cli.Get("/");
  7222. ASSERT_TRUE(res);
  7223. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7224. }
  7225. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  7226. SSLClient cli("google.com");
  7227. cli.enable_server_certificate_verification(true);
  7228. cli.set_ca_cert_path("hello");
  7229. auto res = cli.Get("/");
  7230. ASSERT_TRUE(!res);
  7231. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  7232. // For SSL_CTX operations, ssl_error should be 0, only ssl_openssl_error
  7233. // should be set
  7234. EXPECT_EQ(0, res.ssl_error());
  7235. // Verify OpenSSL error is captured for SSLLoadingCerts
  7236. // This error occurs when SSL_CTX_load_verify_locations() fails
  7237. // > openssl errstr 0x80000002
  7238. // error:80000002:system library::No such file or directory
  7239. // > openssl errstr 0xA000126
  7240. // error:0A000126:SSL routines::unexpected eof while reading
  7241. EXPECT_TRUE(res.ssl_openssl_error() == 0x80000002 ||
  7242. res.ssl_openssl_error() == 0xA000126);
  7243. }
  7244. TEST(SSLClientTest, ServerCertificateVerification4) {
  7245. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  7246. ASSERT_TRUE(svr.is_valid());
  7247. svr.Get("/test", [&](const Request &, Response &res) {
  7248. res.set_content("test", "text/plain");
  7249. svr.stop();
  7250. ASSERT_TRUE(true);
  7251. });
  7252. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  7253. auto se = detail::scope_exit([&] {
  7254. t.join();
  7255. ASSERT_FALSE(svr.is_running());
  7256. });
  7257. svr.wait_until_ready();
  7258. SSLClient cli("127.0.0.1", PORT);
  7259. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  7260. cli.enable_server_certificate_verification(true);
  7261. cli.set_connection_timeout(30);
  7262. auto res = cli.Get("/test");
  7263. ASSERT_TRUE(res);
  7264. ASSERT_EQ(StatusCode::OK_200, res->status);
  7265. }
  7266. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  7267. std::string cert;
  7268. read_file(CA_CERT_FILE, cert);
  7269. SSLClient cli("google.com");
  7270. cli.load_ca_cert_store(cert.data(), cert.size());
  7271. const auto res = cli.Get("/");
  7272. ASSERT_TRUE(res);
  7273. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7274. }
  7275. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  7276. // clang-format off
  7277. static constexpr char cert[] =
  7278. "GlobalSign Root CA\n"
  7279. "==================\n"
  7280. "-----BEGIN CERTIFICATE-----\n"
  7281. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  7282. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  7283. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  7284. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  7285. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  7286. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  7287. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  7288. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  7289. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  7290. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  7291. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  7292. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  7293. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  7294. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  7295. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  7296. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  7297. "-----END CERTIFICATE-----\n";
  7298. // clang-format on
  7299. SSLClient cli("google.com");
  7300. cli.load_ca_cert_store(cert, sizeof(cert));
  7301. const auto res = cli.Get("/");
  7302. ASSERT_TRUE(res);
  7303. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  7304. }
  7305. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  7306. SSLClient cli("www.youtube.com");
  7307. cli.set_ca_cert_path(CA_CERT_FILE);
  7308. cli.enable_server_certificate_verification(true);
  7309. cli.set_follow_location(true);
  7310. auto res = cli.Get("/");
  7311. ASSERT_TRUE(res);
  7312. ASSERT_EQ(StatusCode::OK_200, res->status);
  7313. }
  7314. TEST(SSLClientTest, Issue2004_Online) {
  7315. Client client("https://google.com");
  7316. client.set_follow_location(true);
  7317. auto res = client.Get("/");
  7318. ASSERT_TRUE(res);
  7319. ASSERT_EQ(StatusCode::OK_200, res->status);
  7320. auto body = res->body;
  7321. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  7322. }
  7323. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  7324. // Create SSLClient with invalid cert/key to make is_valid() return false
  7325. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  7326. "nonexistent_key.pem");
  7327. // is_valid() should be false due to cert loading failure
  7328. ASSERT_FALSE(cli.is_valid());
  7329. auto res = cli.Get("/");
  7330. ASSERT_FALSE(res);
  7331. EXPECT_EQ(Error::SSLConnection, res.error());
  7332. }
  7333. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  7334. // Test for Issue #2251: SSL error not properly reported when client cert
  7335. // and key paths are swapped or mismatched
  7336. // This simulates the scenario where user accidentally swaps the cert and key
  7337. // files
  7338. // Using client cert file as private key and vice versa (completely wrong)
  7339. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  7340. // Should fail validation due to cert/key mismatch
  7341. ASSERT_FALSE(cli.is_valid());
  7342. // Attempt to make a request should fail with proper error
  7343. auto res = cli.Get("/");
  7344. ASSERT_FALSE(res);
  7345. EXPECT_EQ(Error::SSLConnection, res.error());
  7346. // SSL error should be recorded in the Result object (this is the key fix for
  7347. // Issue #2251)
  7348. auto openssl_error = res.ssl_openssl_error();
  7349. EXPECT_NE(0u, openssl_error);
  7350. }
  7351. TEST(SSLClientTest, Issue2251_ClientCertFileNotMatchingKey) {
  7352. // Another variant: using valid file paths but with mismatched cert/key pair
  7353. // This tests the case where files exist but contain incompatible key material
  7354. // Using client cert with wrong key (cert2 key)
  7355. SSLClient cli("localhost", 8080, "client.cert.pem", "key.pem");
  7356. // Should fail validation
  7357. ASSERT_FALSE(cli.is_valid());
  7358. auto res = cli.Get("/");
  7359. ASSERT_FALSE(res);
  7360. // Must report error properly, not appear as success
  7361. EXPECT_EQ(Error::SSLConnection, res.error());
  7362. // OpenSSL error should be captured in Result
  7363. EXPECT_NE(0u, res.ssl_openssl_error());
  7364. }
  7365. #if 0
  7366. TEST(SSLClientTest, SetInterfaceWithINET6) {
  7367. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  7368. ASSERT_TRUE(cli != nullptr);
  7369. cli->set_address_family(AF_INET6);
  7370. cli->set_interface("en0");
  7371. auto res = cli->Get("/get");
  7372. ASSERT_TRUE(res);
  7373. ASSERT_EQ(StatusCode::OK_200, res->status);
  7374. }
  7375. #endif
  7376. void ClientCertPresent(
  7377. const std::string &client_cert_file,
  7378. const std::string &client_private_key_file,
  7379. const std::string &client_encrypted_private_key_pass = std::string()) {
  7380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7381. CLIENT_CA_CERT_DIR);
  7382. ASSERT_TRUE(svr.is_valid());
  7383. svr.Get("/test", [&](const Request &req, Response &res) {
  7384. res.set_content("test", "text/plain");
  7385. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7386. ASSERT_TRUE(peer_cert != nullptr);
  7387. auto subject_name = X509_get_subject_name(peer_cert);
  7388. ASSERT_TRUE(subject_name != nullptr);
  7389. std::string common_name;
  7390. {
  7391. char name[BUFSIZ];
  7392. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7393. name, sizeof(name));
  7394. common_name.assign(name, static_cast<size_t>(name_len));
  7395. }
  7396. EXPECT_EQ("Common Name", common_name);
  7397. X509_free(peer_cert);
  7398. });
  7399. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7400. auto se = detail::scope_exit([&] {
  7401. svr.stop();
  7402. t.join();
  7403. ASSERT_FALSE(svr.is_running());
  7404. });
  7405. svr.wait_until_ready();
  7406. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  7407. client_encrypted_private_key_pass);
  7408. cli.enable_server_certificate_verification(false);
  7409. cli.set_connection_timeout(30);
  7410. auto res = cli.Get("/test");
  7411. ASSERT_TRUE(res);
  7412. ASSERT_EQ(StatusCode::OK_200, res->status);
  7413. }
  7414. TEST(SSLClientServerTest, ClientCertPresent) {
  7415. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7416. }
  7417. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  7418. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7419. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7420. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7421. }
  7422. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  7423. void MemoryClientCertPresent(
  7424. const std::string &client_cert_file,
  7425. const std::string &client_private_key_file,
  7426. const std::string &client_encrypted_private_key_pass = std::string()) {
  7427. auto f = fopen(SERVER_CERT_FILE, "r+");
  7428. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7429. fclose(f);
  7430. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  7431. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  7432. fclose(f);
  7433. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  7434. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7435. auto client_ca_cert_store = X509_STORE_new();
  7436. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  7437. X509_free(client_cert);
  7438. fclose(f);
  7439. f = fopen(client_cert_file.c_str(), "r+");
  7440. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  7441. fclose(f);
  7442. f = fopen(client_private_key_file.c_str(), "r+");
  7443. auto client_private_key = PEM_read_PrivateKey(
  7444. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  7445. fclose(f);
  7446. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  7447. ASSERT_TRUE(svr.is_valid());
  7448. svr.Get("/test", [&](const Request &req, Response &res) {
  7449. res.set_content("test", "text/plain");
  7450. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7451. ASSERT_TRUE(peer_cert != nullptr);
  7452. auto subject_name = X509_get_subject_name(peer_cert);
  7453. ASSERT_TRUE(subject_name != nullptr);
  7454. std::string common_name;
  7455. {
  7456. char name[BUFSIZ];
  7457. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7458. name, sizeof(name));
  7459. common_name.assign(name, static_cast<size_t>(name_len));
  7460. }
  7461. EXPECT_EQ("Common Name", common_name);
  7462. X509_free(peer_cert);
  7463. });
  7464. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7465. auto se = detail::scope_exit([&] {
  7466. svr.stop();
  7467. t.join();
  7468. ASSERT_FALSE(svr.is_running());
  7469. });
  7470. svr.wait_until_ready();
  7471. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  7472. client_encrypted_private_key_pass);
  7473. cli.enable_server_certificate_verification(false);
  7474. cli.set_connection_timeout(30);
  7475. auto res = cli.Get("/test");
  7476. ASSERT_TRUE(res);
  7477. ASSERT_EQ(StatusCode::OK_200, res->status);
  7478. X509_free(server_cert);
  7479. EVP_PKEY_free(server_private_key);
  7480. X509_free(client_cert);
  7481. EVP_PKEY_free(client_private_key);
  7482. }
  7483. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  7484. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7485. }
  7486. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  7487. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  7488. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  7489. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  7490. }
  7491. #endif
  7492. TEST(SSLClientServerTest, ClientCertMissing) {
  7493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  7494. CLIENT_CA_CERT_DIR);
  7495. ASSERT_TRUE(svr.is_valid());
  7496. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  7497. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7498. auto se = detail::scope_exit([&] {
  7499. svr.stop();
  7500. t.join();
  7501. ASSERT_FALSE(svr.is_running());
  7502. });
  7503. svr.wait_until_ready();
  7504. SSLClient cli(HOST, PORT);
  7505. cli.set_connection_timeout(30);
  7506. auto res = cli.Get("/test");
  7507. ASSERT_TRUE(!res);
  7508. EXPECT_EQ(Error::SSLServerVerification, res.error());
  7509. // For SSL server verification errors, ssl_error should be 0, only
  7510. // ssl_openssl_error should be set
  7511. EXPECT_EQ(0, res.ssl_error());
  7512. // Verify OpenSSL error is captured for SSLServerVerification
  7513. // Note: This test may have different error codes depending on the exact
  7514. // verification failure
  7515. EXPECT_NE(0UL, res.ssl_openssl_error());
  7516. }
  7517. TEST(SSLClientServerTest, TrustDirOptional) {
  7518. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7519. ASSERT_TRUE(svr.is_valid());
  7520. svr.Get("/test", [&](const Request &, Response &res) {
  7521. res.set_content("test", "text/plain");
  7522. });
  7523. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7524. auto se = detail::scope_exit([&] {
  7525. svr.stop();
  7526. t.join();
  7527. ASSERT_FALSE(svr.is_running());
  7528. });
  7529. svr.wait_until_ready();
  7530. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7531. cli.enable_server_certificate_verification(false);
  7532. cli.set_connection_timeout(30);
  7533. auto res = cli.Get("/test");
  7534. ASSERT_TRUE(res);
  7535. ASSERT_EQ(StatusCode::OK_200, res->status);
  7536. }
  7537. TEST(SSLClientServerTest, SSLConnectTimeout) {
  7538. class NoListenSSLServer : public SSLServer {
  7539. public:
  7540. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  7541. const char *client_ca_cert_file_path,
  7542. const char *client_ca_cert_dir_path = nullptr)
  7543. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  7544. client_ca_cert_dir_path),
  7545. stop_(false) {}
  7546. std::atomic_bool stop_;
  7547. private:
  7548. bool process_and_close_socket(socket_t /*sock*/) override {
  7549. // Don't create SSL context
  7550. while (!stop_.load()) {
  7551. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  7552. }
  7553. return true;
  7554. }
  7555. };
  7556. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7557. CLIENT_CA_CERT_FILE);
  7558. ASSERT_TRUE(svr.is_valid());
  7559. svr.Get("/test", [&](const Request &, Response &res) {
  7560. res.set_content("test", "text/plain");
  7561. });
  7562. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7563. auto se = detail::scope_exit([&] {
  7564. svr.stop_ = true;
  7565. svr.stop();
  7566. t.join();
  7567. ASSERT_FALSE(svr.is_running());
  7568. });
  7569. svr.wait_until_ready();
  7570. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7571. cli.enable_server_certificate_verification(false);
  7572. cli.set_connection_timeout(1);
  7573. auto res = cli.Get("/test");
  7574. ASSERT_TRUE(!res);
  7575. EXPECT_EQ(Error::SSLConnection, res.error());
  7576. EXPECT_EQ(SSL_ERROR_WANT_READ, res.ssl_error());
  7577. }
  7578. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  7579. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  7580. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  7581. SSL_CTX_set_options(&ssl_ctx,
  7582. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  7583. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  7584. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  7585. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  7586. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  7587. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  7588. "ECDHE-DSS-AES128-SHA256:"
  7589. "ECDHE-RSA-AES256-SHA256:"
  7590. "ECDHE-DSS-AES256-SHA256:";
  7591. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  7592. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  7593. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  7594. SSL_FILETYPE_PEM) != 1) {
  7595. return false;
  7596. }
  7597. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  7598. CLIENT_CA_CERT_DIR);
  7599. SSL_CTX_set_verify(
  7600. &ssl_ctx,
  7601. SSL_VERIFY_PEER |
  7602. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  7603. nullptr);
  7604. return true;
  7605. };
  7606. SSLServer svr(setup_ssl_ctx_callback);
  7607. ASSERT_TRUE(svr.is_valid());
  7608. svr.Get("/test", [&](const Request &req, Response &res) {
  7609. res.set_content("test", "text/plain");
  7610. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7611. ASSERT_TRUE(peer_cert != nullptr);
  7612. auto subject_name = X509_get_subject_name(peer_cert);
  7613. ASSERT_TRUE(subject_name != nullptr);
  7614. std::string common_name;
  7615. {
  7616. char name[BUFSIZ];
  7617. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  7618. name, sizeof(name));
  7619. common_name.assign(name, static_cast<size_t>(name_len));
  7620. }
  7621. EXPECT_EQ("Common Name", common_name);
  7622. X509_free(peer_cert);
  7623. });
  7624. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7625. auto se = detail::scope_exit([&] {
  7626. svr.stop();
  7627. t.join();
  7628. ASSERT_FALSE(svr.is_running());
  7629. });
  7630. svr.wait_until_ready();
  7631. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7632. cli.enable_server_certificate_verification(false);
  7633. cli.set_connection_timeout(30);
  7634. auto res = cli.Get("/test");
  7635. ASSERT_TRUE(res);
  7636. ASSERT_EQ(StatusCode::OK_200, res->status);
  7637. }
  7638. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  7639. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7640. ASSERT_TRUE(svr.is_valid());
  7641. // Set up a handler to verify client certificate is present
  7642. bool client_cert_verified = false;
  7643. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  7644. // Verify that client certificate was provided
  7645. client_cert_verified = true;
  7646. res.set_content("success", "text/plain");
  7647. });
  7648. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7649. auto se = detail::scope_exit([&] {
  7650. svr.stop();
  7651. t.join();
  7652. ASSERT_FALSE(svr.is_running());
  7653. });
  7654. svr.wait_until_ready();
  7655. // Client with certificate
  7656. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7657. cli.enable_server_certificate_verification(false);
  7658. cli.set_connection_timeout(30);
  7659. auto res = cli.Get("/test");
  7660. ASSERT_TRUE(res);
  7661. ASSERT_EQ(StatusCode::OK_200, res->status);
  7662. ASSERT_TRUE(client_cert_verified);
  7663. EXPECT_EQ("success", res->body);
  7664. }
  7665. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  7666. // Test that when client CA cert file is provided,
  7667. // SSL_CTX_set_client_CA_list is called and the CA list is properly set
  7668. // Create a server with client authentication
  7669. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  7670. ASSERT_TRUE(svr.is_valid());
  7671. // We can't directly access the SSL_CTX from SSLServer to verify,
  7672. // but we can test that the server properly requests client certificates
  7673. // and accepts valid ones from the specified CA
  7674. bool handler_called = false;
  7675. svr.Get("/test", [&](const Request &req, Response &res) {
  7676. handler_called = true;
  7677. // Verify that a client certificate was provided
  7678. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  7679. ASSERT_TRUE(peer_cert != nullptr);
  7680. // Get the issuer name
  7681. auto issuer_name = X509_get_issuer_name(peer_cert);
  7682. ASSERT_TRUE(issuer_name != nullptr);
  7683. char issuer_buf[256];
  7684. X509_NAME_oneline(issuer_name, issuer_buf, sizeof(issuer_buf));
  7685. // The client certificate should be issued by our test CA
  7686. std::string issuer_str(issuer_buf);
  7687. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  7688. X509_free(peer_cert);
  7689. res.set_content("authenticated", "text/plain");
  7690. });
  7691. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  7692. auto se = detail::scope_exit([&] {
  7693. svr.stop();
  7694. t.join();
  7695. ASSERT_FALSE(svr.is_running());
  7696. });
  7697. svr.wait_until_ready();
  7698. // Connect with a client certificate issued by the CA
  7699. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7700. cli.enable_server_certificate_verification(false);
  7701. cli.set_connection_timeout(30);
  7702. auto res = cli.Get("/test");
  7703. ASSERT_TRUE(res);
  7704. ASSERT_EQ(StatusCode::OK_200, res->status);
  7705. ASSERT_TRUE(handler_called);
  7706. EXPECT_EQ("authenticated", res->body);
  7707. }
  7708. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  7709. // Test 1: Valid CA file - no error should be recorded
  7710. {
  7711. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  7712. CLIENT_CA_CERT_FILE);
  7713. ASSERT_TRUE(svr.is_valid());
  7714. // With valid setup, last_ssl_error should be 0
  7715. EXPECT_EQ(0, svr.ssl_last_error());
  7716. }
  7717. // Test 2: Invalid CA file content
  7718. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  7719. {
  7720. // Create a temporary file with completely invalid content
  7721. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  7722. {
  7723. std::ofstream ofs(temp_invalid_ca);
  7724. ofs << "This is not a certificate file at all\n";
  7725. ofs << "Just plain text content\n";
  7726. }
  7727. // Create server with invalid CA file
  7728. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  7729. // Clean up temporary file
  7730. std::remove(temp_invalid_ca);
  7731. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  7732. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  7733. // Note: SSL_CTX_load_verify_locations typically fails first,
  7734. // but our error handling code path is still exercised
  7735. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  7736. }
  7737. }
  7738. TEST(SSLClientServerTest, ClientCAListFromX509Store) {
  7739. // Test SSL server using X509_STORE constructor with client CA certificates
  7740. // This test verifies that Phase 2 implementation correctly extracts CA names
  7741. // from an X509_STORE and sets them in the SSL context
  7742. // Load the CA certificate into memory
  7743. auto bio = BIO_new_file(CLIENT_CA_CERT_FILE, "r");
  7744. ASSERT_NE(nullptr, bio);
  7745. auto ca_cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr);
  7746. BIO_free(bio);
  7747. ASSERT_NE(nullptr, ca_cert);
  7748. // Create an X509_STORE and add the CA certificate
  7749. auto store = X509_STORE_new();
  7750. ASSERT_NE(nullptr, store);
  7751. ASSERT_EQ(1, X509_STORE_add_cert(store, ca_cert));
  7752. // Load server certificate and private key
  7753. auto cert_bio = BIO_new_file(SERVER_CERT_FILE, "r");
  7754. ASSERT_NE(nullptr, cert_bio);
  7755. auto server_cert = PEM_read_bio_X509(cert_bio, nullptr, nullptr, nullptr);
  7756. BIO_free(cert_bio);
  7757. ASSERT_NE(nullptr, server_cert);
  7758. auto key_bio = BIO_new_file(SERVER_PRIVATE_KEY_FILE, "r");
  7759. ASSERT_NE(nullptr, key_bio);
  7760. auto server_key = PEM_read_bio_PrivateKey(key_bio, nullptr, nullptr, nullptr);
  7761. BIO_free(key_bio);
  7762. ASSERT_NE(nullptr, server_key);
  7763. // Create SSLServer with X509_STORE constructor
  7764. // Note: X509_STORE ownership is transferred to SSL_CTX
  7765. SSLServer svr(server_cert, server_key, store);
  7766. ASSERT_TRUE(svr.is_valid());
  7767. // No SSL error should be recorded for valid setup
  7768. EXPECT_EQ(0, svr.ssl_last_error());
  7769. // Set up server endpoints
  7770. svr.Get("/test-x509store", [&](const Request & /*req*/, Response &res) {
  7771. res.set_content("ok", "text/plain");
  7772. });
  7773. // Start server in a thread
  7774. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  7775. svr.wait_until_ready();
  7776. // Connect with client certificate (using constructor with paths)
  7777. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  7778. cli.enable_server_certificate_verification(false);
  7779. auto res = cli.Get("/test-x509store");
  7780. ASSERT_TRUE(res);
  7781. EXPECT_EQ(200, res->status);
  7782. EXPECT_EQ("ok", res->body);
  7783. // Clean up
  7784. X509_free(server_cert);
  7785. EVP_PKEY_free(server_key);
  7786. X509_free(ca_cert);
  7787. svr.stop();
  7788. server_thread.join();
  7789. }
  7790. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  7791. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  7792. // prepare large data
  7793. std::random_device seed_gen;
  7794. std::mt19937 random(seed_gen());
  7795. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  7796. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  7797. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  7798. // server
  7799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  7800. ASSERT_TRUE(svr.is_valid());
  7801. svr.Post("/binary", [&](const Request &req, Response &res) {
  7802. EXPECT_EQ(large_size_byte, req.body.size());
  7803. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  7804. res.set_content(req.body, "application/octet-stream");
  7805. });
  7806. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  7807. auto se = detail::scope_exit([&] {
  7808. svr.stop();
  7809. listen_thread.join();
  7810. ASSERT_FALSE(svr.is_running());
  7811. });
  7812. svr.wait_until_ready();
  7813. // client POST
  7814. SSLClient cli("localhost", PORT);
  7815. cli.enable_server_certificate_verification(false);
  7816. cli.set_read_timeout(std::chrono::seconds(100));
  7817. cli.set_write_timeout(std::chrono::seconds(100));
  7818. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  7819. large_size_byte, "application/octet-stream");
  7820. // compare
  7821. EXPECT_EQ(StatusCode::OK_200, res->status);
  7822. EXPECT_EQ(large_size_byte, res->body.size());
  7823. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  7824. }
  7825. #endif
  7826. #ifdef _WIN32
  7827. TEST(CleanupTest, WSACleanup) {
  7828. int ret = WSACleanup();
  7829. ASSERT_EQ(0, ret);
  7830. }
  7831. #endif
  7832. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  7833. TEST(NoSSLSupport, SimpleInterface) {
  7834. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  7835. }
  7836. #endif
  7837. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  7838. TEST(InvalidScheme, SimpleInterface) {
  7839. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  7840. }
  7841. #endif
  7842. TEST(NoScheme, SimpleInterface) {
  7843. Client cli("yahoo.com:80");
  7844. ASSERT_TRUE(cli.is_valid());
  7845. }
  7846. TEST(SendAPI, SimpleInterface_Online) {
  7847. Client cli("http://yahoo.com");
  7848. Request req;
  7849. req.method = "GET";
  7850. req.path = "/";
  7851. auto res = cli.send(req);
  7852. ASSERT_TRUE(res);
  7853. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7854. }
  7855. TEST(SendAPI, WithParamsInRequest) {
  7856. Server svr;
  7857. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  7858. EXPECT_TRUE(req.has_param("test"));
  7859. EXPECT_EQ("test_value", req.get_param_value("test"));
  7860. });
  7861. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  7862. auto se = detail::scope_exit([&] {
  7863. svr.stop();
  7864. t.join();
  7865. ASSERT_FALSE(svr.is_running());
  7866. });
  7867. svr.wait_until_ready();
  7868. Client cli(HOST, PORT);
  7869. {
  7870. Request req;
  7871. req.method = "GET";
  7872. req.path = "/";
  7873. req.params.emplace("test", "test_value");
  7874. auto res = cli.send(req);
  7875. ASSERT_TRUE(res);
  7876. }
  7877. {
  7878. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  7879. ASSERT_TRUE(res);
  7880. }
  7881. }
  7882. TEST(ClientImplMethods, GetSocketTest) {
  7883. httplib::Server svr;
  7884. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  7885. res.status = StatusCode::OK_200;
  7886. });
  7887. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  7888. auto se = detail::scope_exit([&] {
  7889. svr.stop();
  7890. thread.join();
  7891. ASSERT_FALSE(svr.is_running());
  7892. });
  7893. svr.wait_until_ready();
  7894. {
  7895. httplib::Client cli("http://127.0.0.1:3333");
  7896. cli.set_keep_alive(true);
  7897. // Use the behavior of cpp-httplib of opening the connection
  7898. // only when the first request happens. If that changes,
  7899. // this test would be obsolete.
  7900. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  7901. // This also implicitly tests the server. But other tests would fail much
  7902. // earlier than this one to be considered.
  7903. auto res = cli.Get("/");
  7904. ASSERT_TRUE(res);
  7905. EXPECT_EQ(StatusCode::OK_200, res->status);
  7906. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  7907. }
  7908. }
  7909. // Disabled due to out-of-memory problem on GitHub Actions
  7910. #ifdef _WIN64
  7911. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  7912. // allocate content size larger than 2GB in memory
  7913. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  7914. char *content = (char *)malloc(content_size);
  7915. ASSERT_TRUE(content);
  7916. Server svr;
  7917. svr.Get("/foo",
  7918. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  7919. res.set_content(content, content_size, "application/octet-stream");
  7920. });
  7921. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  7922. auto se = detail::scope_exit([&] {
  7923. svr.stop();
  7924. listen_thread.join();
  7925. if (content) free(content);
  7926. ASSERT_FALSE(svr.is_running());
  7927. });
  7928. svr.wait_until_ready();
  7929. Client cli(HOST, PORT);
  7930. auto res = cli.Get("/foo");
  7931. ASSERT_TRUE(res);
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. EXPECT_EQ(content_size, res->body.length());
  7934. }
  7935. #endif
  7936. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  7937. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  7938. Client cli("http://yahoo.com");
  7939. auto res = cli.Get("/");
  7940. ASSERT_TRUE(res);
  7941. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7942. cli.set_follow_location(true);
  7943. res = cli.Get("/");
  7944. ASSERT_TRUE(res);
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7947. }
  7948. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  7949. Client cli("https://yahoo.com");
  7950. auto res = cli.Get("/");
  7951. ASSERT_TRUE(res);
  7952. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7953. cli.set_follow_location(true);
  7954. res = cli.Get("/");
  7955. ASSERT_TRUE(res);
  7956. EXPECT_EQ(StatusCode::OK_200, res->status);
  7957. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7958. }
  7959. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  7960. Client cli("https://yahoo.com");
  7961. auto res = cli.Get("/");
  7962. ASSERT_TRUE(res);
  7963. ASSERT_FALSE(!res);
  7964. ASSERT_TRUE(res);
  7965. ASSERT_FALSE(res == nullptr);
  7966. ASSERT_TRUE(res != nullptr);
  7967. EXPECT_EQ(Error::Success, res.error());
  7968. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  7969. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  7970. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7971. cli.set_follow_location(true);
  7972. res = cli.Get("/");
  7973. ASSERT_TRUE(res);
  7974. EXPECT_EQ(Error::Success, res.error());
  7975. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  7976. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. EXPECT_EQ("https://www.yahoo.com/", res->location);
  7979. }
  7980. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7981. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  7982. Client cli("https://cdnjs.cloudflare.com");
  7983. auto res =
  7984. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  7985. ASSERT_TRUE(res);
  7986. EXPECT_EQ(StatusCode::OK_200, res->status);
  7987. EXPECT_EQ(287630U, res->body.size());
  7988. EXPECT_EQ("application/javascript; charset=utf-8",
  7989. res->get_header_value("Content-Type"));
  7990. }
  7991. #endif
  7992. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  7993. #undef REDIR_HOST // Silence compiler warning
  7994. #define REDIR_HOST "https://httpbingo.org"
  7995. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  7996. Client cli(REDIR_HOST);
  7997. cli.set_follow_location(true);
  7998. auto res =
  7999. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  8000. ASSERT_TRUE(res);
  8001. EXPECT_EQ(StatusCode::OK_200, res->status);
  8002. }
  8003. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  8004. Client cli(REDIR_HOST);
  8005. cli.set_follow_location(true);
  8006. Params params;
  8007. params.emplace("url", "http://example.com");
  8008. params.emplace("status_code", "302");
  8009. auto res = cli.Get(REDIR_PATH, params, Headers{});
  8010. ASSERT_TRUE(res);
  8011. EXPECT_EQ(StatusCode::OK_200, res->status);
  8012. }
  8013. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  8014. Client cli(REDIR_HOST);
  8015. cli.set_follow_location(true);
  8016. Params params;
  8017. params.emplace("url", "http://example.com");
  8018. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  8019. ASSERT_TRUE(res);
  8020. EXPECT_EQ(StatusCode::OK_200, res->status);
  8021. }
  8022. TEST(HttpToHttpsRedirectTest, CertFile) {
  8023. Server svr;
  8024. ASSERT_TRUE(svr.is_valid());
  8025. svr.Get("/index", [&](const Request &, Response &res) {
  8026. res.set_redirect("https://127.0.0.1:1235/index");
  8027. svr.stop();
  8028. });
  8029. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8030. ASSERT_TRUE(ssl_svr.is_valid());
  8031. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  8032. res.set_content("test", "text/plain");
  8033. ssl_svr.stop();
  8034. });
  8035. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  8036. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  8037. auto se = detail::scope_exit([&] {
  8038. t2.join();
  8039. t.join();
  8040. ASSERT_FALSE(svr.is_running());
  8041. });
  8042. svr.wait_until_ready();
  8043. ssl_svr.wait_until_ready();
  8044. Client cli("127.0.0.1", PORT);
  8045. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  8046. cli.enable_server_certificate_verification(true);
  8047. cli.set_follow_location(true);
  8048. cli.set_connection_timeout(30);
  8049. auto res = cli.Get("/index");
  8050. ASSERT_TRUE(res);
  8051. ASSERT_EQ(StatusCode::OK_200, res->status);
  8052. }
  8053. TEST(SSLClientRedirectTest, CertFile) {
  8054. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8055. ASSERT_TRUE(ssl_svr1.is_valid());
  8056. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  8057. res.set_redirect("https://127.0.0.1:1235/index");
  8058. ssl_svr1.stop();
  8059. });
  8060. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  8061. ASSERT_TRUE(ssl_svr2.is_valid());
  8062. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  8063. res.set_content("test", "text/plain");
  8064. ssl_svr2.stop();
  8065. });
  8066. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  8067. thread t2 =
  8068. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", 1235)); });
  8069. auto se = detail::scope_exit([&] {
  8070. t2.join();
  8071. t.join();
  8072. ASSERT_FALSE(ssl_svr1.is_running());
  8073. });
  8074. ssl_svr1.wait_until_ready();
  8075. ssl_svr2.wait_until_ready();
  8076. SSLClient cli("127.0.0.1", PORT);
  8077. std::string cert;
  8078. read_file(SERVER_CERT2_FILE, cert);
  8079. cli.load_ca_cert_store(cert.c_str(), cert.size());
  8080. cli.enable_server_certificate_verification(true);
  8081. cli.set_follow_location(true);
  8082. cli.set_connection_timeout(30);
  8083. auto res = cli.Get("/index");
  8084. ASSERT_TRUE(res);
  8085. ASSERT_EQ(StatusCode::OK_200, res->status);
  8086. }
  8087. TEST(MultipartFormDataTest, LargeData) {
  8088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8089. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8090. const ContentReader &content_reader) {
  8091. if (req.is_multipart_form_data()) {
  8092. std::vector<FormData> items;
  8093. content_reader(
  8094. [&](const FormData &file) {
  8095. items.push_back(file);
  8096. return true;
  8097. },
  8098. [&](const char *data, size_t data_length) {
  8099. items.back().content.append(data, data_length);
  8100. return true;
  8101. });
  8102. EXPECT_TRUE(std::string(items[0].name) == "document");
  8103. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8104. EXPECT_TRUE(items[0].filename == "2MB_data");
  8105. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8106. EXPECT_TRUE(items[1].name == "hello");
  8107. EXPECT_TRUE(items[1].content == "world");
  8108. EXPECT_TRUE(items[1].filename == "");
  8109. EXPECT_TRUE(items[1].content_type == "");
  8110. } else {
  8111. std::string body;
  8112. content_reader([&](const char *data, size_t data_length) {
  8113. body.append(data, data_length);
  8114. return true;
  8115. });
  8116. }
  8117. });
  8118. auto t = std::thread([&]() { svr.listen(HOST, 8080); });
  8119. auto se = detail::scope_exit([&] {
  8120. svr.stop();
  8121. t.join();
  8122. ASSERT_FALSE(svr.is_running());
  8123. });
  8124. svr.wait_until_ready();
  8125. {
  8126. std::string data(1024 * 1024 * 2, '.');
  8127. std::stringstream buffer;
  8128. buffer << data;
  8129. Client cli("https://localhost:8080");
  8130. cli.enable_server_certificate_verification(false);
  8131. UploadFormDataItems items{
  8132. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8133. {"hello", "world", "", ""},
  8134. };
  8135. auto res = cli.Post("/post", items);
  8136. ASSERT_TRUE(res);
  8137. ASSERT_EQ(StatusCode::OK_200, res->status);
  8138. }
  8139. }
  8140. TEST(MultipartFormDataTest, DataProviderItems) {
  8141. std::random_device seed_gen;
  8142. std::mt19937 random(seed_gen());
  8143. std::string rand1;
  8144. rand1.resize(1000);
  8145. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  8146. std::string rand2;
  8147. rand2.resize(3000);
  8148. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  8149. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8150. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  8151. const ContentReader &content_reader) {
  8152. ASSERT_FALSE(req.is_multipart_form_data());
  8153. std::string body;
  8154. content_reader([&](const char *data, size_t data_length) {
  8155. body.append(data, data_length);
  8156. return true;
  8157. });
  8158. EXPECT_EQ(body, "");
  8159. });
  8160. svr.Post("/post-items", [&](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() == 2);
  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. });
  8183. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  8184. const ContentReader &content_reader) {
  8185. ASSERT_TRUE(req.is_multipart_form_data());
  8186. std::vector<FormData> items;
  8187. content_reader(
  8188. [&](const FormData &file) {
  8189. items.push_back(file);
  8190. return true;
  8191. },
  8192. [&](const char *data, size_t data_length) {
  8193. items.back().content.append(data, data_length);
  8194. return true;
  8195. });
  8196. ASSERT_TRUE(items.size() == 2);
  8197. EXPECT_EQ(items[0].name, "name3");
  8198. EXPECT_EQ(items[0].content, rand1);
  8199. EXPECT_EQ(items[0].filename, "filename3");
  8200. EXPECT_EQ(items[0].content_type, "");
  8201. EXPECT_EQ(items[1].name, "name4");
  8202. EXPECT_EQ(items[1].content, rand2);
  8203. EXPECT_EQ(items[1].filename, "filename4");
  8204. EXPECT_EQ(items[1].content_type, "");
  8205. });
  8206. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  8207. const ContentReader &content_reader) {
  8208. ASSERT_TRUE(req.is_multipart_form_data());
  8209. std::vector<FormData> items;
  8210. content_reader(
  8211. [&](const FormData &file) {
  8212. items.push_back(file);
  8213. return true;
  8214. },
  8215. [&](const char *data, size_t data_length) {
  8216. items.back().content.append(data, data_length);
  8217. return true;
  8218. });
  8219. ASSERT_TRUE(items.size() == 4);
  8220. EXPECT_EQ(std::string(items[0].name), "name1");
  8221. EXPECT_EQ(items[0].content, "Testing123");
  8222. EXPECT_EQ(items[0].filename, "filename1");
  8223. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  8224. EXPECT_EQ(items[1].name, "name2");
  8225. EXPECT_EQ(items[1].content, "Testing456");
  8226. EXPECT_EQ(items[1].filename, "");
  8227. EXPECT_EQ(items[1].content_type, "");
  8228. EXPECT_EQ(items[2].name, "name3");
  8229. EXPECT_EQ(items[2].content, rand1);
  8230. EXPECT_EQ(items[2].filename, "filename3");
  8231. EXPECT_EQ(items[2].content_type, "");
  8232. EXPECT_EQ(items[3].name, "name4");
  8233. EXPECT_EQ(items[3].content, rand2);
  8234. EXPECT_EQ(items[3].filename, "filename4");
  8235. EXPECT_EQ(items[3].content_type, "");
  8236. });
  8237. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8238. auto se = detail::scope_exit([&] {
  8239. svr.stop();
  8240. t.join();
  8241. ASSERT_FALSE(svr.is_running());
  8242. });
  8243. svr.wait_until_ready();
  8244. {
  8245. Client cli("https://localhost:8080");
  8246. cli.enable_server_certificate_verification(false);
  8247. UploadFormDataItems items{
  8248. {"name1", "Testing123", "filename1", "application/octet-stream"},
  8249. {"name2", "Testing456", "", ""}, // not a file
  8250. };
  8251. {
  8252. auto res = cli.Post("/post-none", {}, {}, {});
  8253. ASSERT_TRUE(res);
  8254. ASSERT_EQ(StatusCode::OK_200, res->status);
  8255. }
  8256. FormDataProviderItems providers;
  8257. {
  8258. auto res =
  8259. cli.Post("/post-items", {}, items, providers); // empty providers
  8260. ASSERT_TRUE(res);
  8261. ASSERT_EQ(StatusCode::OK_200, res->status);
  8262. }
  8263. providers.push_back({"name3",
  8264. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8265. // test the offset is given correctly at each step
  8266. if (!offset)
  8267. sink.os.write(rand1.data(), 30);
  8268. else if (offset == 30)
  8269. sink.os.write(rand1.data() + 30, 300);
  8270. else if (offset == 330)
  8271. sink.os.write(rand1.data() + 330, 670);
  8272. else if (offset == rand1.size())
  8273. sink.done();
  8274. return true;
  8275. },
  8276. "filename3",
  8277. {}});
  8278. providers.push_back({"name4",
  8279. [&](size_t offset, httplib::DataSink &sink) -> bool {
  8280. // test the offset is given correctly at each step
  8281. if (!offset)
  8282. sink.os.write(rand2.data(), 2000);
  8283. else if (offset == 2000)
  8284. sink.os.write(rand2.data() + 2000, 1);
  8285. else if (offset == 2001)
  8286. sink.os.write(rand2.data() + 2001, 999);
  8287. else if (offset == rand2.size())
  8288. sink.done();
  8289. return true;
  8290. },
  8291. "filename4",
  8292. {}});
  8293. {
  8294. auto res = cli.Post("/post-providers", {}, {}, providers);
  8295. ASSERT_TRUE(res);
  8296. ASSERT_EQ(StatusCode::OK_200, res->status);
  8297. }
  8298. {
  8299. auto res = cli.Post("/post-both", {}, items, providers);
  8300. ASSERT_TRUE(res);
  8301. ASSERT_EQ(StatusCode::OK_200, res->status);
  8302. }
  8303. }
  8304. }
  8305. TEST(MultipartFormDataTest, BadHeader) {
  8306. Server svr;
  8307. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8308. res.set_content("ok", "text/plain");
  8309. });
  8310. thread t = thread([&] { svr.listen(HOST, PORT); });
  8311. auto se = detail::scope_exit([&] {
  8312. svr.stop();
  8313. t.join();
  8314. ASSERT_FALSE(svr.is_running());
  8315. });
  8316. svr.wait_until_ready();
  8317. const std::string body =
  8318. "This is the preamble. It is to be ignored, though it\r\n"
  8319. "is a handy place for composition agents to include an\r\n"
  8320. "explanatory note to non-MIME conformant readers.\r\n"
  8321. "\r\n"
  8322. "\r\n"
  8323. "--simple boundary\r\n"
  8324. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8325. ": BAD...\r\n"
  8326. "\r\n"
  8327. "value1\r\n"
  8328. "--simple boundary\r\n"
  8329. "Content-Disposition: form-data; name=\"field2\"; "
  8330. "filename=\"example.txt\"\r\n"
  8331. "\r\n"
  8332. "value2\r\n"
  8333. "--simple boundary--\r\n"
  8334. "This is the epilogue. It is also to be ignored.\r\n";
  8335. std::string content_type =
  8336. R"(multipart/form-data; boundary="simple boundary")";
  8337. Client cli(HOST, PORT);
  8338. auto res = cli.Post("/post", body, content_type.c_str());
  8339. ASSERT_TRUE(res);
  8340. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8341. }
  8342. TEST(MultipartFormDataTest, WithPreamble) {
  8343. Server svr;
  8344. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  8345. res.set_content("ok", "text/plain");
  8346. });
  8347. thread t = thread([&] { svr.listen(HOST, PORT); });
  8348. auto se = detail::scope_exit([&] {
  8349. svr.stop();
  8350. t.join();
  8351. ASSERT_FALSE(svr.is_running());
  8352. });
  8353. svr.wait_until_ready();
  8354. const std::string body =
  8355. "This is the preamble. It is to be ignored, though it\r\n"
  8356. "is a handy place for composition agents to include an\r\n"
  8357. "explanatory note to non-MIME conformant readers.\r\n"
  8358. "\r\n"
  8359. "\r\n"
  8360. "--simple boundary\r\n"
  8361. "Content-Disposition: form-data; name=\"field1\"\r\n"
  8362. "\r\n"
  8363. "value1\r\n"
  8364. "--simple boundary\r\n"
  8365. "Content-Disposition: form-data; name=\"field2\"; "
  8366. "filename=\"example.txt\"\r\n"
  8367. "\r\n"
  8368. "value2\r\n"
  8369. "--simple boundary--\r\n"
  8370. "This is the epilogue. It is also to be ignored.\r\n";
  8371. std::string content_type =
  8372. R"(multipart/form-data; boundary="simple boundary")";
  8373. Client cli(HOST, PORT);
  8374. auto res = cli.Post("/post", body, content_type.c_str());
  8375. ASSERT_TRUE(res);
  8376. EXPECT_EQ(StatusCode::OK_200, res->status);
  8377. }
  8378. TEST(MultipartFormDataTest, PostCustomBoundary) {
  8379. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8380. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  8381. const ContentReader &content_reader) {
  8382. if (req.is_multipart_form_data()) {
  8383. std::vector<FormData> items;
  8384. content_reader(
  8385. [&](const FormData &file) {
  8386. items.push_back(file);
  8387. return true;
  8388. },
  8389. [&](const char *data, size_t data_length) {
  8390. items.back().content.append(data, data_length);
  8391. return true;
  8392. });
  8393. EXPECT_TRUE(std::string(items[0].name) == "document");
  8394. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8395. EXPECT_TRUE(items[0].filename == "2MB_data");
  8396. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8397. EXPECT_TRUE(items[1].name == "hello");
  8398. EXPECT_TRUE(items[1].content == "world");
  8399. EXPECT_TRUE(items[1].filename == "");
  8400. EXPECT_TRUE(items[1].content_type == "");
  8401. } else {
  8402. std::string body;
  8403. content_reader([&](const char *data, size_t data_length) {
  8404. body.append(data, data_length);
  8405. return true;
  8406. });
  8407. }
  8408. });
  8409. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8410. auto se = detail::scope_exit([&] {
  8411. svr.stop();
  8412. t.join();
  8413. ASSERT_FALSE(svr.is_running());
  8414. });
  8415. svr.wait_until_ready();
  8416. {
  8417. std::string data(1024 * 1024 * 2, '.');
  8418. std::stringstream buffer;
  8419. buffer << data;
  8420. Client cli("https://localhost:8080");
  8421. cli.enable_server_certificate_verification(false);
  8422. UploadFormDataItems items{
  8423. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8424. {"hello", "world", "", ""},
  8425. };
  8426. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  8427. ASSERT_TRUE(res);
  8428. ASSERT_EQ(StatusCode::OK_200, res->status);
  8429. }
  8430. }
  8431. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  8432. std::string data(1024 * 1024 * 2, '&');
  8433. std::stringstream buffer;
  8434. buffer << data;
  8435. Client cli("https://localhost:8080");
  8436. UploadFormDataItems items{
  8437. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8438. {"hello", "world", "", ""},
  8439. };
  8440. for (const char &c : " \t\r\n") {
  8441. auto res =
  8442. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  8443. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8444. ASSERT_FALSE(res);
  8445. }
  8446. }
  8447. TEST(MultipartFormDataTest, PutFormData) {
  8448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8449. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  8450. const ContentReader &content_reader) {
  8451. if (req.is_multipart_form_data()) {
  8452. std::vector<FormData> items;
  8453. content_reader(
  8454. [&](const FormData &file) {
  8455. items.push_back(file);
  8456. return true;
  8457. },
  8458. [&](const char *data, size_t data_length) {
  8459. items.back().content.append(data, data_length);
  8460. return true;
  8461. });
  8462. EXPECT_TRUE(std::string(items[0].name) == "document");
  8463. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8464. EXPECT_TRUE(items[0].filename == "2MB_data");
  8465. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8466. EXPECT_TRUE(items[1].name == "hello");
  8467. EXPECT_TRUE(items[1].content == "world");
  8468. EXPECT_TRUE(items[1].filename == "");
  8469. EXPECT_TRUE(items[1].content_type == "");
  8470. } else {
  8471. std::string body;
  8472. content_reader([&](const char *data, size_t data_length) {
  8473. body.append(data, data_length);
  8474. return true;
  8475. });
  8476. }
  8477. });
  8478. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8479. auto se = detail::scope_exit([&] {
  8480. svr.stop();
  8481. t.join();
  8482. ASSERT_FALSE(svr.is_running());
  8483. });
  8484. svr.wait_until_ready();
  8485. {
  8486. std::string data(1024 * 1024 * 2, '&');
  8487. std::stringstream buffer;
  8488. buffer << data;
  8489. Client cli("https://localhost:8080");
  8490. cli.enable_server_certificate_verification(false);
  8491. UploadFormDataItems items{
  8492. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8493. {"hello", "world", "", ""},
  8494. };
  8495. auto res = cli.Put("/put", items);
  8496. ASSERT_TRUE(res);
  8497. ASSERT_EQ(StatusCode::OK_200, res->status);
  8498. }
  8499. }
  8500. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  8501. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8502. svr.Put("/put_customboundary",
  8503. [&](const Request &req, const Response & /*res*/,
  8504. const ContentReader &content_reader) {
  8505. if (req.is_multipart_form_data()) {
  8506. std::vector<FormData> items;
  8507. content_reader(
  8508. [&](const FormData &file) {
  8509. items.push_back(file);
  8510. return true;
  8511. },
  8512. [&](const char *data, size_t data_length) {
  8513. items.back().content.append(data, data_length);
  8514. return true;
  8515. });
  8516. EXPECT_TRUE(std::string(items[0].name) == "document");
  8517. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  8518. EXPECT_TRUE(items[0].filename == "2MB_data");
  8519. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  8520. EXPECT_TRUE(items[1].name == "hello");
  8521. EXPECT_TRUE(items[1].content == "world");
  8522. EXPECT_TRUE(items[1].filename == "");
  8523. EXPECT_TRUE(items[1].content_type == "");
  8524. } else {
  8525. std::string body;
  8526. content_reader([&](const char *data, size_t data_length) {
  8527. body.append(data, data_length);
  8528. return true;
  8529. });
  8530. }
  8531. });
  8532. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  8533. auto se = detail::scope_exit([&] {
  8534. svr.stop();
  8535. t.join();
  8536. ASSERT_FALSE(svr.is_running());
  8537. });
  8538. svr.wait_until_ready();
  8539. {
  8540. std::string data(1024 * 1024 * 2, '&');
  8541. std::stringstream buffer;
  8542. buffer << data;
  8543. Client cli("https://localhost:8080");
  8544. cli.enable_server_certificate_verification(false);
  8545. UploadFormDataItems items{
  8546. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8547. {"hello", "world", "", ""},
  8548. };
  8549. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  8550. ASSERT_TRUE(res);
  8551. ASSERT_EQ(StatusCode::OK_200, res->status);
  8552. }
  8553. }
  8554. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  8555. std::string data(1024 * 1024 * 2, '&');
  8556. std::stringstream buffer;
  8557. buffer << data;
  8558. Client cli("https://localhost:8080");
  8559. cli.enable_server_certificate_verification(false);
  8560. UploadFormDataItems items{
  8561. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  8562. {"hello", "world", "", ""},
  8563. };
  8564. for (const char &c : " \t\r\n") {
  8565. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  8566. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  8567. ASSERT_FALSE(res);
  8568. }
  8569. }
  8570. TEST(MultipartFormDataTest, AlternateFilename) {
  8571. auto handled = false;
  8572. Server svr;
  8573. svr.Post("/test", [&](const Request &req, Response &res) {
  8574. ASSERT_EQ(2u, req.form.files.size());
  8575. ASSERT_EQ(1u, req.form.fields.size());
  8576. // Test files
  8577. const auto &file1 = req.form.get_file("file1");
  8578. ASSERT_EQ("file1", file1.name);
  8579. ASSERT_EQ("A.txt", file1.filename);
  8580. ASSERT_EQ("text/plain", file1.content_type);
  8581. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  8582. const auto &file2 = req.form.get_file("file2");
  8583. ASSERT_EQ("file2", file2.name);
  8584. ASSERT_EQ("a.html", file2.filename);
  8585. ASSERT_EQ("text/html", file2.content_type);
  8586. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  8587. file2.content);
  8588. // Test text field
  8589. const auto &text = req.form.get_field("text");
  8590. ASSERT_EQ("text default", text);
  8591. res.set_content("ok", "text/plain");
  8592. handled = true;
  8593. });
  8594. thread t = thread([&] { svr.listen(HOST, PORT); });
  8595. auto se = detail::scope_exit([&] {
  8596. svr.stop();
  8597. t.join();
  8598. ASSERT_FALSE(svr.is_running());
  8599. ASSERT_TRUE(handled);
  8600. });
  8601. svr.wait_until_ready();
  8602. auto req = "POST /test HTTP/1.1\r\n"
  8603. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8604. "Content-Length: 399\r\n"
  8605. "\r\n"
  8606. "----------\r\n"
  8607. "Content-Disposition: form-data; name=\"text\"\r\n"
  8608. "\r\n"
  8609. "text default\r\n"
  8610. "----------\r\n"
  8611. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  8612. "filename=\"a.txt\"; name=\"file1\"\r\n"
  8613. "Content-Type: text/plain\r\n"
  8614. "\r\n"
  8615. "Content of a.txt.\r\n"
  8616. "\r\n"
  8617. "----------\r\n"
  8618. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  8619. "\"a.html\"\r\n"
  8620. "Content-Type: text/html\r\n"
  8621. "\r\n"
  8622. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  8623. "\r\n"
  8624. "------------\r\n";
  8625. ASSERT_TRUE(send_request(1, req));
  8626. }
  8627. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  8628. auto handled = false;
  8629. Server svr;
  8630. svr.Post("/test", [&](const Request &req, Response &) {
  8631. ASSERT_EQ(2u, req.form.fields.size());
  8632. const auto &text1 = req.form.get_field("text1");
  8633. ASSERT_EQ("text1", text1);
  8634. const auto &text2 = req.form.get_field("text2");
  8635. ASSERT_EQ("text2", text2);
  8636. handled = true;
  8637. });
  8638. thread t = thread([&] { svr.listen(HOST, PORT); });
  8639. auto se = detail::scope_exit([&] {
  8640. svr.stop();
  8641. t.join();
  8642. ASSERT_FALSE(svr.is_running());
  8643. ASSERT_TRUE(handled);
  8644. });
  8645. svr.wait_until_ready();
  8646. auto req = "POST /test HTTP/1.1\r\n"
  8647. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8648. "Content-Length: 146\r\n"
  8649. "\r\n----------\r\n"
  8650. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8651. "\r\n"
  8652. "text1"
  8653. "\r\n----------\r\n"
  8654. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8655. "\r\n"
  8656. "text2"
  8657. "\r\n------------";
  8658. std::string response;
  8659. ASSERT_TRUE(send_request(1, req, &response));
  8660. ASSERT_EQ("200", response.substr(9, 3));
  8661. }
  8662. TEST(MultipartFormDataTest, ContentLength) {
  8663. auto handled = false;
  8664. Server svr;
  8665. svr.Post("/test", [&](const Request &req, Response &) {
  8666. ASSERT_EQ(2u, req.form.fields.size());
  8667. const auto &text1 = req.form.get_field("text1");
  8668. ASSERT_EQ("text1", text1);
  8669. const auto &text2 = req.form.get_field("text2");
  8670. ASSERT_EQ("text2", text2);
  8671. handled = true;
  8672. });
  8673. thread t = thread([&] { svr.listen(HOST, PORT); });
  8674. auto se = detail::scope_exit([&] {
  8675. svr.stop();
  8676. t.join();
  8677. ASSERT_FALSE(svr.is_running());
  8678. ASSERT_TRUE(handled);
  8679. });
  8680. svr.wait_until_ready();
  8681. auto req = "POST /test HTTP/1.1\r\n"
  8682. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8683. "Content-Length: 167\r\n"
  8684. "\r\n----------\r\n"
  8685. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8686. "Content-Length: 5\r\n"
  8687. "\r\n"
  8688. "text1"
  8689. "\r\n----------\r\n"
  8690. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8691. "\r\n"
  8692. "text2"
  8693. "\r\n------------\r\n";
  8694. std::string response;
  8695. ASSERT_TRUE(send_request(1, req, &response));
  8696. ASSERT_EQ("200", response.substr(9, 3));
  8697. }
  8698. TEST(MultipartFormDataTest, AccessPartHeaders) {
  8699. auto handled = false;
  8700. Server svr;
  8701. svr.Post("/test", [&](const Request &req, Response &) {
  8702. ASSERT_EQ(2u, req.form.fields.size());
  8703. const auto &text1 = req.form.get_field("text1");
  8704. ASSERT_EQ("text1", text1);
  8705. // TODO: Add header access for text fields if needed
  8706. const auto &text2 = req.form.get_field("text2");
  8707. ASSERT_EQ("text2", text2);
  8708. // TODO: Header access for text fields needs to be implemented
  8709. // auto &headers = it->second.headers;
  8710. // ASSERT_EQ(3U, headers.size());
  8711. // auto custom_header = headers.find("x-whatever");
  8712. // ASSERT_TRUE(custom_header != headers.end());
  8713. // ASSERT_NE("customvalue", custom_header->second);
  8714. // ASSERT_EQ("CustomValue", custom_header->second);
  8715. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  8716. handled = true;
  8717. });
  8718. thread t = thread([&] { svr.listen(HOST, PORT); });
  8719. auto se = detail::scope_exit([&] {
  8720. svr.stop();
  8721. t.join();
  8722. ASSERT_FALSE(svr.is_running());
  8723. ASSERT_TRUE(handled);
  8724. });
  8725. svr.wait_until_ready();
  8726. auto req = "POST /test HTTP/1.1\r\n"
  8727. "Content-Type: multipart/form-data;boundary=--------\r\n"
  8728. "Content-Length: 232\r\n"
  8729. "\r\n----------\r\n"
  8730. "Content-Disposition: form-data; name=\"text1\"\r\n"
  8731. "Content-Length: 5\r\n"
  8732. "X-Test: 1\r\n"
  8733. "\r\n"
  8734. "text1"
  8735. "\r\n----------\r\n"
  8736. "Content-Disposition: form-data; name=\"text2\"\r\n"
  8737. "Content-Type: text/plain\r\n"
  8738. "X-Whatever: CustomValue\r\n"
  8739. "\r\n"
  8740. "text2"
  8741. "\r\n------------\r\n"
  8742. "That should be disregarded. Not even read";
  8743. std::string response;
  8744. ASSERT_TRUE(send_request(1, req, &response));
  8745. ASSERT_EQ("200", response.substr(9, 3));
  8746. }
  8747. #endif
  8748. TEST(MultipartFormDataTest, LargeHeader) {
  8749. auto handled = false;
  8750. Server svr;
  8751. svr.Post("/test", [&](const Request &req, Response &) {
  8752. ASSERT_EQ(1u, req.form.fields.size());
  8753. const auto &text = req.form.get_field("name1");
  8754. ASSERT_EQ("text1", text);
  8755. handled = true;
  8756. });
  8757. thread t = thread([&] { svr.listen(HOST, PORT); });
  8758. auto se = detail::scope_exit([&] {
  8759. svr.stop();
  8760. t.join();
  8761. ASSERT_FALSE(svr.is_running());
  8762. ASSERT_TRUE(handled);
  8763. });
  8764. svr.wait_until_ready();
  8765. auto boundary = std::string("cpp-httplib-multipart-data");
  8766. std::string content = "--" + boundary +
  8767. "\r\n"
  8768. "Content-Disposition: form-data; name=\"name1\"\r\n"
  8769. "\r\n"
  8770. "text1\r\n"
  8771. "--" +
  8772. boundary + "--\r\n";
  8773. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  8774. "Content-Type: multipart/form-data;boundary=" +
  8775. boundary +
  8776. "\r\n"
  8777. "Content-Length: " +
  8778. std::to_string(content.size()) +
  8779. "\r\n"
  8780. "Dummy-Header: ";
  8781. std::string header_suffix = "\r\n"
  8782. "\r\n";
  8783. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  8784. size_t header_dummy_size =
  8785. read_buff_size -
  8786. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  8787. auto header_dummy = std::string(header_dummy_size, '@');
  8788. auto req = header_prefix + header_dummy + header_suffix + content;
  8789. std::string response;
  8790. ASSERT_TRUE(send_request(1, req, &response));
  8791. ASSERT_EQ("200", response.substr(9, 3));
  8792. }
  8793. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  8794. static constexpr unsigned int number_of_tasks{1000000};
  8795. std::atomic_uint count{0};
  8796. std::unique_ptr<TaskQueue> task_queue{
  8797. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  8798. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8799. auto queued = task_queue->enqueue(
  8800. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  8801. EXPECT_TRUE(queued);
  8802. }
  8803. EXPECT_NO_THROW(task_queue->shutdown());
  8804. EXPECT_EQ(number_of_tasks, count.load());
  8805. }
  8806. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  8807. static constexpr unsigned int number_of_tasks{1000000};
  8808. static constexpr unsigned int qlimit{2};
  8809. unsigned int queued_count{0};
  8810. std::atomic_uint count{0};
  8811. std::unique_ptr<TaskQueue> task_queue{
  8812. new ThreadPool{/*num_threads=*/1, qlimit}};
  8813. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  8814. if (task_queue->enqueue(
  8815. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  8816. queued_count++;
  8817. }
  8818. }
  8819. EXPECT_NO_THROW(task_queue->shutdown());
  8820. EXPECT_EQ(queued_count, count.load());
  8821. EXPECT_TRUE(queued_count <= number_of_tasks);
  8822. EXPECT_TRUE(queued_count >= qlimit);
  8823. }
  8824. TEST(TaskQueueTest, MaxQueuedRequests) {
  8825. static constexpr unsigned int qlimit{3};
  8826. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  8827. std::condition_variable sem_cv;
  8828. std::mutex sem_mtx;
  8829. int credits = 0;
  8830. bool queued;
  8831. /* Fill up the queue with tasks that will block until we give them credits to
  8832. * complete. */
  8833. for (unsigned int n = 0; n <= qlimit;) {
  8834. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  8835. std::unique_lock<std::mutex> lock(sem_mtx);
  8836. while (credits <= 0) {
  8837. sem_cv.wait(lock);
  8838. }
  8839. /* Consume the credit and signal the test code if they are all gone. */
  8840. if (--credits == 0) { sem_cv.notify_one(); }
  8841. });
  8842. if (n < qlimit) {
  8843. /* The first qlimit enqueues must succeed. */
  8844. EXPECT_TRUE(queued);
  8845. } else {
  8846. /* The last one will succeed only when the worker thread
  8847. * starts and dequeues the first blocking task. Although
  8848. * not necessary for the correctness of this test, we sleep for
  8849. * a short while to avoid busy waiting. */
  8850. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  8851. }
  8852. if (queued) { n++; }
  8853. }
  8854. /* Further enqueues must fail since the queue is full. */
  8855. for (auto i = 0; i < 4; i++) {
  8856. queued = task_queue->enqueue([] {});
  8857. EXPECT_FALSE(queued);
  8858. }
  8859. /* Give the credits to allow the previous tasks to complete. */
  8860. {
  8861. std::unique_lock<std::mutex> lock(sem_mtx);
  8862. credits += qlimit + 1;
  8863. }
  8864. sem_cv.notify_all();
  8865. /* Wait for all the credits to be consumed. */
  8866. {
  8867. std::unique_lock<std::mutex> lock(sem_mtx);
  8868. while (credits > 0) {
  8869. sem_cv.wait(lock);
  8870. }
  8871. }
  8872. /* Check that we are able again to enqueue at least qlimit tasks. */
  8873. for (unsigned int i = 0; i < qlimit; i++) {
  8874. queued = task_queue->enqueue([] {});
  8875. EXPECT_TRUE(queued);
  8876. }
  8877. EXPECT_NO_THROW(task_queue->shutdown());
  8878. }
  8879. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  8880. Server svr;
  8881. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8882. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  8883. });
  8884. svr.Get("/hello", [](const Request &req, Response &res) {
  8885. res.set_content(req.get_param_value("key"), "text/plain");
  8886. });
  8887. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8888. auto se = detail::scope_exit([&] {
  8889. svr.stop();
  8890. thread.join();
  8891. ASSERT_FALSE(svr.is_running());
  8892. });
  8893. svr.wait_until_ready();
  8894. {
  8895. Client cli(HOST, PORT);
  8896. cli.set_follow_location(true);
  8897. auto res = cli.Get("/");
  8898. ASSERT_TRUE(res);
  8899. EXPECT_EQ(StatusCode::OK_200, res->status);
  8900. EXPECT_EQ("val&key2=val2", res->body);
  8901. }
  8902. }
  8903. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  8904. Server svr;
  8905. svr.Get("/", [](const Request & /*req*/, Response &res) {
  8906. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  8907. });
  8908. svr.Get("/hello", [](const Request &req, Response &res) {
  8909. res.set_content(req.get_param_value("key"), "text/plain");
  8910. });
  8911. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8912. auto se = detail::scope_exit([&] {
  8913. svr.stop();
  8914. thread.join();
  8915. ASSERT_FALSE(svr.is_running());
  8916. });
  8917. svr.wait_until_ready();
  8918. {
  8919. Client cli(HOST, PORT);
  8920. cli.set_follow_location(true);
  8921. auto res = cli.Get("/");
  8922. ASSERT_TRUE(res);
  8923. EXPECT_EQ(StatusCode::OK_200, res->status);
  8924. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  8925. }
  8926. }
  8927. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  8928. TEST(RedirectTest, Issue2185_Online) {
  8929. SSLClient client("github.com");
  8930. client.set_follow_location(true);
  8931. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  8932. "Coollab-Windows.zip");
  8933. ASSERT_TRUE(res);
  8934. EXPECT_EQ(StatusCode::OK_200, res->status);
  8935. EXPECT_EQ(9920427U, res->body.size());
  8936. }
  8937. #endif
  8938. TEST(VulnerabilityTest, CRLFInjection) {
  8939. Server svr;
  8940. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  8941. res.set_content("Hello 1", "text/plain");
  8942. });
  8943. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  8944. res.set_content("Hello 2", "text/plain");
  8945. });
  8946. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  8947. res.set_content("Hello 3", "text/plain");
  8948. });
  8949. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  8950. res.set_content("Hello 4", "text/plain");
  8951. });
  8952. svr.set_logger([](const Request &req, const Response & /*res*/) {
  8953. for (const auto &x : req.headers) {
  8954. auto key = x.first;
  8955. EXPECT_STRNE("evil", key.c_str());
  8956. }
  8957. });
  8958. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8959. auto se = detail::scope_exit([&] {
  8960. svr.stop();
  8961. thread.join();
  8962. ASSERT_FALSE(svr.is_running());
  8963. });
  8964. svr.wait_until_ready();
  8965. {
  8966. Client cli(HOST, PORT);
  8967. cli.Post("/test1", "A=B",
  8968. "application/x-www-form-urlencoded\r\nevil: hello1");
  8969. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  8970. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  8971. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  8972. }
  8973. }
  8974. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  8975. auto server_thread = std::thread([] {
  8976. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  8977. default_socket_options(srv);
  8978. sockaddr_in addr{};
  8979. addr.sin_family = AF_INET;
  8980. addr.sin_port = htons(PORT + 1);
  8981. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  8982. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  8983. ::listen(srv, 1);
  8984. sockaddr_in cli_addr{};
  8985. socklen_t cli_len = sizeof(cli_addr);
  8986. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  8987. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  8988. std::string buf_all;
  8989. char buf[2048];
  8990. ssize_t n;
  8991. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  8992. buf_all.append(buf, static_cast<size_t>(n));
  8993. size_t pos;
  8994. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  8995. auto request_block = buf_all.substr(0, pos + 4); // include separator
  8996. auto e = request_block.find("\r\n");
  8997. if (e != std::string::npos) {
  8998. auto request_line = request_block.substr(0, e);
  8999. std::string msg =
  9000. "CRLF injection detected in request line: '" + request_line + "'";
  9001. EXPECT_FALSE(true) << msg;
  9002. }
  9003. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  9004. ::send(cli,
  9005. #ifdef _WIN32
  9006. static_cast<const char *>(resp.c_str()),
  9007. static_cast<int>(resp.size()),
  9008. #else
  9009. resp.c_str(), resp.size(),
  9010. #endif
  9011. 0);
  9012. buf_all.erase(0, pos + 4);
  9013. }
  9014. }
  9015. detail::close_socket(cli);
  9016. detail::close_socket(srv);
  9017. });
  9018. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  9019. auto cli = Client("127.0.0.1", PORT + 1);
  9020. auto headers = Headers{
  9021. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  9022. {"Connection", "keep-alive"}};
  9023. auto res = cli.Get("/hi", headers);
  9024. EXPECT_FALSE(res);
  9025. EXPECT_EQ(Error::InvalidHeaders, res.error());
  9026. server_thread.join();
  9027. }
  9028. TEST(PathParamsTest, StaticMatch) {
  9029. const auto pattern = "/users/all";
  9030. detail::PathParamsMatcher matcher(pattern);
  9031. Request request;
  9032. request.path = "/users/all";
  9033. ASSERT_TRUE(matcher.match(request));
  9034. std::unordered_map<std::string, std::string> expected_params = {};
  9035. EXPECT_EQ(request.path_params, expected_params);
  9036. }
  9037. TEST(PathParamsTest, StaticMismatch) {
  9038. const auto pattern = "/users/all";
  9039. detail::PathParamsMatcher matcher(pattern);
  9040. Request request;
  9041. request.path = "/users/1";
  9042. ASSERT_FALSE(matcher.match(request));
  9043. }
  9044. TEST(PathParamsTest, SingleParamInTheMiddle) {
  9045. const auto pattern = "/users/:id/subscriptions";
  9046. detail::PathParamsMatcher matcher(pattern);
  9047. Request request;
  9048. request.path = "/users/42/subscriptions";
  9049. ASSERT_TRUE(matcher.match(request));
  9050. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9051. EXPECT_EQ(request.path_params, expected_params);
  9052. }
  9053. TEST(PathParamsTest, SingleParamInTheEnd) {
  9054. const auto pattern = "/users/:id";
  9055. detail::PathParamsMatcher matcher(pattern);
  9056. Request request;
  9057. request.path = "/users/24";
  9058. ASSERT_TRUE(matcher.match(request));
  9059. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  9060. EXPECT_EQ(request.path_params, expected_params);
  9061. }
  9062. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  9063. const auto pattern = "/users/:id/";
  9064. detail::PathParamsMatcher matcher(pattern);
  9065. Request request;
  9066. request.path = "/users/42/";
  9067. ASSERT_TRUE(matcher.match(request));
  9068. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  9069. EXPECT_EQ(request.path_params, expected_params);
  9070. }
  9071. TEST(PathParamsTest, EmptyParam) {
  9072. const auto pattern = "/users/:id/";
  9073. detail::PathParamsMatcher matcher(pattern);
  9074. Request request;
  9075. request.path = "/users//";
  9076. ASSERT_TRUE(matcher.match(request));
  9077. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  9078. EXPECT_EQ(request.path_params, expected_params);
  9079. }
  9080. TEST(PathParamsTest, FragmentMismatch) {
  9081. const auto pattern = "/users/:id/";
  9082. detail::PathParamsMatcher matcher(pattern);
  9083. Request request;
  9084. request.path = "/admins/24/";
  9085. ASSERT_FALSE(matcher.match(request));
  9086. }
  9087. TEST(PathParamsTest, ExtraFragments) {
  9088. const auto pattern = "/users/:id";
  9089. detail::PathParamsMatcher matcher(pattern);
  9090. Request request;
  9091. request.path = "/users/42/subscriptions";
  9092. ASSERT_FALSE(matcher.match(request));
  9093. }
  9094. TEST(PathParamsTest, MissingTrailingParam) {
  9095. const auto pattern = "/users/:id";
  9096. detail::PathParamsMatcher matcher(pattern);
  9097. Request request;
  9098. request.path = "/users";
  9099. ASSERT_FALSE(matcher.match(request));
  9100. }
  9101. TEST(PathParamsTest, MissingParamInTheMiddle) {
  9102. const auto pattern = "/users/:id/subscriptions";
  9103. detail::PathParamsMatcher matcher(pattern);
  9104. Request request;
  9105. request.path = "/users/subscriptions";
  9106. ASSERT_FALSE(matcher.match(request));
  9107. }
  9108. TEST(PathParamsTest, MultipleParams) {
  9109. const auto pattern = "/users/:userid/subscriptions/:subid";
  9110. detail::PathParamsMatcher matcher(pattern);
  9111. Request request;
  9112. request.path = "/users/42/subscriptions/2";
  9113. ASSERT_TRUE(matcher.match(request));
  9114. std::unordered_map<std::string, std::string> expected_params = {
  9115. {"userid", "42"}, {"subid", "2"}};
  9116. EXPECT_EQ(request.path_params, expected_params);
  9117. }
  9118. TEST(PathParamsTest, SequenceOfParams) {
  9119. const auto pattern = "/values/:x/:y/:z";
  9120. detail::PathParamsMatcher matcher(pattern);
  9121. Request request;
  9122. request.path = "/values/1/2/3";
  9123. ASSERT_TRUE(matcher.match(request));
  9124. std::unordered_map<std::string, std::string> expected_params = {
  9125. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  9126. EXPECT_EQ(request.path_params, expected_params);
  9127. }
  9128. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  9129. const auto pattern = "/prefix:suffix";
  9130. detail::PathParamsMatcher matcher(pattern);
  9131. Request request;
  9132. request.path = "/prefix:suffix";
  9133. ASSERT_TRUE(matcher.match(request));
  9134. const std::unordered_map<std::string, std::string> expected_params = {};
  9135. EXPECT_EQ(request.path_params, expected_params);
  9136. }
  9137. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  9138. // If ipv6 regex working, regex match codepath is taken.
  9139. // else port will default to 80 in Client impl
  9140. int clientImplMagicPort = 80;
  9141. int port = 4321;
  9142. // above ports must be different to avoid false negative
  9143. EXPECT_NE(clientImplMagicPort, port);
  9144. std::string ipV6TestURL = "http://[ff06::c3]";
  9145. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  9146. CLIENT_PRIVATE_KEY_FILE);
  9147. EXPECT_EQ(cli.port(), port);
  9148. }
  9149. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  9150. auto file_path = "./www/dir/index.html";
  9151. auto dir_path = "./www/dir";
  9152. detail::FileStat stat_file(file_path);
  9153. EXPECT_TRUE(stat_file.is_file());
  9154. EXPECT_FALSE(stat_file.is_dir());
  9155. detail::FileStat stat_dir(dir_path);
  9156. EXPECT_FALSE(stat_dir.is_file());
  9157. EXPECT_TRUE(stat_dir.is_dir());
  9158. }
  9159. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  9160. // IPv4 with default HTTP port (80)
  9161. EXPECT_EQ("example.com",
  9162. detail::make_host_and_port_string("example.com", 80, false));
  9163. // IPv4 with default HTTPS port (443)
  9164. EXPECT_EQ("example.com",
  9165. detail::make_host_and_port_string("example.com", 443, true));
  9166. // IPv4 with non-default HTTP port
  9167. EXPECT_EQ("example.com:8080",
  9168. detail::make_host_and_port_string("example.com", 8080, false));
  9169. // IPv4 with non-default HTTPS port
  9170. EXPECT_EQ("example.com:8443",
  9171. detail::make_host_and_port_string("example.com", 8443, true));
  9172. // IPv6 with default HTTP port (80)
  9173. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  9174. // IPv6 with default HTTPS port (443)
  9175. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  9176. // IPv6 with non-default HTTP port
  9177. EXPECT_EQ("[::1]:8080",
  9178. detail::make_host_and_port_string("::1", 8080, false));
  9179. // IPv6 with non-default HTTPS port
  9180. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  9181. // IPv6 full address with default port
  9182. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  9183. detail::make_host_and_port_string(
  9184. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  9185. // IPv6 full address with non-default port
  9186. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  9187. detail::make_host_and_port_string(
  9188. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  9189. // IPv6 localhost with non-default port
  9190. EXPECT_EQ("[::1]:3000",
  9191. detail::make_host_and_port_string("::1", 3000, false));
  9192. // IPv6 with zone ID (link-local address) with default port
  9193. EXPECT_EQ("[fe80::1%eth0]",
  9194. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  9195. // IPv6 with zone ID (link-local address) with non-default port
  9196. EXPECT_EQ("[fe80::1%eth0]:8080",
  9197. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  9198. // Edge case: Port 443 with is_ssl=false (should add port)
  9199. EXPECT_EQ("example.com:443",
  9200. detail::make_host_and_port_string("example.com", 443, false));
  9201. // Edge case: Port 80 with is_ssl=true (should add port)
  9202. EXPECT_EQ("example.com:80",
  9203. detail::make_host_and_port_string("example.com", 80, true));
  9204. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  9205. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  9206. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  9207. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  9208. // Security fix: Already bracketed IPv6 should not get double brackets
  9209. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  9210. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  9211. EXPECT_EQ("[::1]:8080",
  9212. detail::make_host_and_port_string("[::1]", 8080, false));
  9213. EXPECT_EQ("[2001:db8::1]:8080",
  9214. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  9215. EXPECT_EQ("[fe80::1%eth0]",
  9216. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  9217. EXPECT_EQ("[fe80::1%eth0]:8080",
  9218. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  9219. // Edge case: Empty host (should return as-is)
  9220. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  9221. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  9222. // This is a known limitation but shouldn't crash
  9223. EXPECT_EQ("[host:name]",
  9224. detail::make_host_and_port_string("host:name", 80, false));
  9225. // Port number edge cases (no validation, but should not crash)
  9226. EXPECT_EQ("example.com:0",
  9227. detail::make_host_and_port_string("example.com", 0, false));
  9228. EXPECT_EQ("example.com:-1",
  9229. detail::make_host_and_port_string("example.com", -1, false));
  9230. EXPECT_EQ("example.com:65535",
  9231. detail::make_host_and_port_string("example.com", 65535, false));
  9232. EXPECT_EQ("example.com:65536",
  9233. detail::make_host_and_port_string("example.com", 65536, false));
  9234. }
  9235. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9236. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  9237. httplib::SSLClient cli("roblox.com", 443);
  9238. cli.set_follow_location(true);
  9239. auto res = cli.Get("/");
  9240. ASSERT_TRUE(res);
  9241. EXPECT_EQ(StatusCode::OK_200, res->status);
  9242. }
  9243. #endif
  9244. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  9245. Server svr;
  9246. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  9247. EXPECT_EQ(res.status, 400);
  9248. });
  9249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9250. auto se = detail::scope_exit([&] {
  9251. svr.stop();
  9252. thread.join();
  9253. ASSERT_FALSE(svr.is_running());
  9254. });
  9255. svr.wait_until_ready();
  9256. Client cli(HOST, PORT);
  9257. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  9258. }
  9259. TEST(InvalidHeaderCharsTest, is_field_name) {
  9260. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  9261. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  9262. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  9263. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  9264. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  9265. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  9266. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  9267. EXPECT_FALSE(detail::fields::is_field_name(""));
  9268. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  9269. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  9270. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  9271. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  9272. }
  9273. TEST(InvalidHeaderCharsTest, is_field_value) {
  9274. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  9275. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  9276. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  9277. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  9278. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  9279. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  9280. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  9281. EXPECT_TRUE(detail::fields::is_field_value(""));
  9282. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  9283. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  9284. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  9285. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  9286. EXPECT_TRUE(detail::fields::is_field_value("0"));
  9287. }
  9288. TEST(InvalidHeaderCharsTest, OnServer) {
  9289. Server svr;
  9290. svr.Get("/test_name", [&](const Request &req, Response &res) {
  9291. std::string header = "Not Set";
  9292. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9293. res.set_header(header, "value");
  9294. res.set_content("Page Content Page Content", "text/plain");
  9295. });
  9296. svr.Get("/test_value", [&](const Request &req, Response &res) {
  9297. std::string header = "Not Set";
  9298. if (req.has_param("header")) { header = req.get_param_value("header"); }
  9299. res.set_header("X-Test", header);
  9300. res.set_content("Page Content Page Content", "text/plain");
  9301. });
  9302. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9303. auto se = detail::scope_exit([&] {
  9304. svr.stop();
  9305. thread.join();
  9306. ASSERT_FALSE(svr.is_running());
  9307. });
  9308. svr.wait_until_ready();
  9309. Client cli(HOST, PORT);
  9310. {
  9311. auto res = cli.Get(
  9312. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9313. ASSERT_TRUE(res);
  9314. EXPECT_EQ("Page Content Page Content", res->body);
  9315. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9316. }
  9317. {
  9318. auto res = cli.Get(
  9319. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  9320. ASSERT_TRUE(res);
  9321. EXPECT_EQ("Page Content Page Content", res->body);
  9322. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  9323. }
  9324. }
  9325. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  9326. auto handled = false;
  9327. Server svr;
  9328. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  9329. thread t = thread([&] { svr.listen(HOST, PORT); });
  9330. auto se = detail::scope_exit([&] {
  9331. svr.stop();
  9332. t.join();
  9333. ASSERT_FALSE(svr.is_running());
  9334. ASSERT_FALSE(handled);
  9335. });
  9336. svr.wait_until_ready();
  9337. auto req = "POST /test HTTP/1.1\r\n"
  9338. "Content-Length: x\r\n"
  9339. "\r\n";
  9340. std::string response;
  9341. ASSERT_TRUE(send_request(1, req, &response));
  9342. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  9343. response.substr(0, response.find("\r\n")));
  9344. }
  9345. #ifndef _WIN32
  9346. TEST(Expect100ContinueTest, ServerClosesConnection) {
  9347. static constexpr char reject[] = "Unauthorized";
  9348. static constexpr char accept[] = "Upload accepted";
  9349. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  9350. Server svr;
  9351. svr.set_expect_100_continue_handler(
  9352. [](const Request & /*req*/, Response &res) {
  9353. res.status = StatusCode::Unauthorized_401;
  9354. res.set_content(reject, "text/plain");
  9355. return res.status;
  9356. });
  9357. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  9358. res.set_content(accept, "text/plain");
  9359. });
  9360. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9361. auto se = detail::scope_exit([&] {
  9362. svr.stop();
  9363. thread.join();
  9364. ASSERT_FALSE(svr.is_running());
  9365. });
  9366. svr.wait_until_ready();
  9367. {
  9368. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  9369. curl_easy_init(), &curl_easy_cleanup};
  9370. ASSERT_NE(curl, nullptr);
  9371. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  9372. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  9373. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  9374. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  9375. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  9376. &curl_slist_free_all};
  9377. ASSERT_NE(list, nullptr);
  9378. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  9379. struct read_data {
  9380. size_t read_size;
  9381. size_t total_size;
  9382. } data = {0, total_size};
  9383. using read_callback_t =
  9384. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9385. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  9386. void *userdata) -> size_t {
  9387. read_data *data = (read_data *)userdata;
  9388. if (!userdata || data->read_size >= data->total_size) { return 0; }
  9389. std::fill_n(ptr, size * nmemb, 'A');
  9390. data->read_size += size * nmemb;
  9391. return size * nmemb;
  9392. };
  9393. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  9394. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  9395. std::vector<char> buffer;
  9396. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  9397. using write_callback_t =
  9398. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  9399. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  9400. void *userdata) -> size_t {
  9401. std::vector<char> *buffer = (std::vector<char> *)userdata;
  9402. buffer->reserve(buffer->size() + size * nmemb + 1);
  9403. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  9404. return size * nmemb;
  9405. };
  9406. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  9407. {
  9408. const auto res = curl_easy_perform(curl.get());
  9409. ASSERT_EQ(res, CURLE_OK);
  9410. }
  9411. {
  9412. auto response_code = long{};
  9413. const auto res =
  9414. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  9415. ASSERT_EQ(res, CURLE_OK);
  9416. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  9417. }
  9418. {
  9419. auto dl = curl_off_t{};
  9420. const auto res =
  9421. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  9422. ASSERT_EQ(res, CURLE_OK);
  9423. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  9424. }
  9425. {
  9426. buffer.push_back('\0');
  9427. ASSERT_STRCASEEQ(buffer.data(), reject);
  9428. }
  9429. }
  9430. }
  9431. #endif
  9432. template <typename S, typename C>
  9433. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  9434. svr.Get("/stream", [&](const Request &, Response &res) {
  9435. auto data = new std::string("01234567890123456789");
  9436. res.set_content_provider(
  9437. data->size(), "text/plain",
  9438. [&, data](size_t offset, size_t length, DataSink &sink) {
  9439. const size_t DATA_CHUNK_SIZE = 4;
  9440. const auto &d = *data;
  9441. std::this_thread::sleep_for(std::chrono::seconds(1));
  9442. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  9443. return true;
  9444. },
  9445. [data](bool success) {
  9446. EXPECT_FALSE(success);
  9447. delete data;
  9448. });
  9449. });
  9450. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  9451. auto i = new size_t(0);
  9452. res.set_content_provider(
  9453. "text/plain",
  9454. [i](size_t, DataSink &sink) {
  9455. if (*i < 5) {
  9456. std::this_thread::sleep_for(std::chrono::seconds(1));
  9457. sink.write("abcd", 4);
  9458. (*i)++;
  9459. } else {
  9460. sink.done();
  9461. }
  9462. return true;
  9463. },
  9464. [i](bool success) {
  9465. EXPECT_FALSE(success);
  9466. delete i;
  9467. });
  9468. });
  9469. svr.Get("/chunked", [&](const Request &, Response &res) {
  9470. auto i = new size_t(0);
  9471. res.set_chunked_content_provider(
  9472. "text/plain",
  9473. [i](size_t, DataSink &sink) {
  9474. if (*i < 5) {
  9475. std::this_thread::sleep_for(std::chrono::seconds(1));
  9476. sink.os << "abcd";
  9477. (*i)++;
  9478. } else {
  9479. sink.done();
  9480. }
  9481. return true;
  9482. },
  9483. [i](bool success) {
  9484. EXPECT_FALSE(success);
  9485. delete i;
  9486. });
  9487. });
  9488. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9489. auto se = detail::scope_exit([&] {
  9490. svr.stop();
  9491. listen_thread.join();
  9492. ASSERT_FALSE(svr.is_running());
  9493. });
  9494. svr.wait_until_ready();
  9495. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  9496. {
  9497. auto start = std::chrono::steady_clock::now();
  9498. auto res = cli.Get("/stream");
  9499. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9500. std::chrono::steady_clock::now() - start)
  9501. .count();
  9502. ASSERT_FALSE(res);
  9503. EXPECT_EQ(Error::Read, res.error());
  9504. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9505. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9506. }
  9507. {
  9508. auto start = std::chrono::steady_clock::now();
  9509. auto res = cli.Get("/stream_without_length");
  9510. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9511. std::chrono::steady_clock::now() - start)
  9512. .count();
  9513. ASSERT_FALSE(res);
  9514. EXPECT_EQ(Error::Read, res.error());
  9515. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9516. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9517. }
  9518. {
  9519. auto start = std::chrono::steady_clock::now();
  9520. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  9521. EXPECT_EQ("abcd", string(data, data_length));
  9522. return true;
  9523. });
  9524. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  9525. std::chrono::steady_clock::now() - start)
  9526. .count();
  9527. ASSERT_FALSE(res);
  9528. EXPECT_EQ(Error::Read, res.error());
  9529. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  9530. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  9531. }
  9532. }
  9533. TEST(MaxTimeoutTest, ContentStream) {
  9534. time_t timeout = 2000;
  9535. time_t threshold = 200;
  9536. Server svr;
  9537. Client cli("localhost", PORT);
  9538. max_timeout_test(svr, cli, timeout, threshold);
  9539. }
  9540. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9541. TEST(MaxTimeoutTest, ContentStreamSSL) {
  9542. time_t timeout = 2000;
  9543. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  9544. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9545. SSLClient cli("localhost", PORT);
  9546. cli.enable_server_certificate_verification(false);
  9547. max_timeout_test(svr, cli, timeout, threshold);
  9548. }
  9549. #endif
  9550. class EventDispatcher {
  9551. public:
  9552. EventDispatcher() {}
  9553. bool wait_event(DataSink *sink) {
  9554. unique_lock<mutex> lk(m_);
  9555. int id = id_;
  9556. // Wait with timeout to prevent hanging if client disconnects
  9557. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  9558. [&] { return cid_ == id; })) {
  9559. return false; // Timeout occurred
  9560. }
  9561. sink->write(message_.data(), message_.size());
  9562. return true;
  9563. }
  9564. void send_event(const string &message) {
  9565. lock_guard<mutex> lk(m_);
  9566. cid_ = id_++;
  9567. message_ = message;
  9568. cv_.notify_all();
  9569. }
  9570. private:
  9571. mutex m_;
  9572. condition_variable cv_;
  9573. atomic_int id_{0};
  9574. atomic_int cid_{-1};
  9575. string message_;
  9576. };
  9577. TEST(ClientInThreadTest, Issue2068) {
  9578. EventDispatcher ed;
  9579. Server svr;
  9580. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  9581. res.set_chunked_content_provider("text/event-stream",
  9582. [&](size_t /*offset*/, DataSink &sink) {
  9583. return ed.wait_event(&sink);
  9584. });
  9585. });
  9586. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  9587. svr.wait_until_ready();
  9588. thread event_thread([&] {
  9589. int id = 0;
  9590. while (svr.is_running()) {
  9591. this_thread::sleep_for(chrono::milliseconds(500));
  9592. std::stringstream ss;
  9593. ss << "data: " << id << "\n\n";
  9594. ed.send_event(ss.str());
  9595. id++;
  9596. }
  9597. });
  9598. auto se = detail::scope_exit([&] {
  9599. svr.stop();
  9600. listen_thread.join();
  9601. event_thread.join();
  9602. ASSERT_FALSE(svr.is_running());
  9603. });
  9604. {
  9605. auto client = detail::make_unique<Client>(HOST, PORT);
  9606. client->set_read_timeout(std::chrono::minutes(10));
  9607. std::atomic<bool> stop{false};
  9608. std::thread t([&] {
  9609. client->Get("/event1",
  9610. [&](const char *, size_t) -> bool { return !stop; });
  9611. });
  9612. std::this_thread::sleep_for(std::chrono::seconds(2));
  9613. stop = true;
  9614. client->stop();
  9615. t.join();
  9616. // Reset client after thread has finished
  9617. client.reset();
  9618. }
  9619. }
  9620. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  9621. Server svr;
  9622. svr.Get("/", [](const Request &req, Response &res) {
  9623. EXPECT_EQ(2U, req.trailers.size());
  9624. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  9625. // Denied
  9626. EXPECT_FALSE(req.has_trailer("Content-Length"));
  9627. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  9628. // Accepted
  9629. EXPECT_TRUE(req.has_trailer("X-Hello"));
  9630. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  9631. EXPECT_TRUE(req.has_trailer("X-World"));
  9632. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  9633. res.set_content("ok", "text/plain");
  9634. });
  9635. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9636. auto se = detail::scope_exit([&] {
  9637. svr.stop();
  9638. t.join();
  9639. ASSERT_FALSE(svr.is_running());
  9640. });
  9641. svr.wait_until_ready();
  9642. const std::string req = "GET / HTTP/1.1\r\n"
  9643. "Transfer-Encoding: chunked\r\n"
  9644. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  9645. "\r\n"
  9646. "0\r\n"
  9647. "Content-Length: 10\r\n"
  9648. "Host: internal.local\r\n"
  9649. "Content-Type: malicious/content\r\n"
  9650. "Cookie: any\r\n"
  9651. "Set-Cookie: any\r\n"
  9652. "X-Forwarded-For: attacker.com\r\n"
  9653. "X-Real-Ip: 1.1.1.1\r\n"
  9654. "X-Hello: hello\r\n"
  9655. "X-World: world\r\n"
  9656. "\r\n";
  9657. std::string res;
  9658. ASSERT_TRUE(send_request(1, req, &res));
  9659. }
  9660. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  9661. Server svr;
  9662. std::string observed_remote_addr;
  9663. std::string observed_xff;
  9664. svr.Get("/ip", [&](const Request &req, Response &res) {
  9665. observed_remote_addr = req.remote_addr;
  9666. observed_xff = req.get_header_value("X-Forwarded-For");
  9667. res.set_content("ok", "text/plain");
  9668. });
  9669. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9670. auto se = detail::scope_exit([&] {
  9671. svr.stop();
  9672. t.join();
  9673. ASSERT_FALSE(svr.is_running());
  9674. });
  9675. svr.wait_until_ready();
  9676. Client cli(HOST, PORT);
  9677. auto res = cli.Get("/ip", {{"X-Forwarded-For", "203.0.113.66"}});
  9678. ASSERT_TRUE(res);
  9679. EXPECT_EQ(StatusCode::OK_200, res->status);
  9680. EXPECT_EQ(observed_xff, "203.0.113.66");
  9681. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9682. observed_remote_addr == "127.0.0.1");
  9683. }
  9684. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  9685. Server svr;
  9686. svr.set_trusted_proxies({"203.0.113.66"});
  9687. std::string observed_remote_addr;
  9688. std::string observed_xff;
  9689. svr.Get("/ip", [&](const Request &req, Response &res) {
  9690. observed_remote_addr = req.remote_addr;
  9691. observed_xff = req.get_header_value("X-Forwarded-For");
  9692. res.set_content("ok", "text/plain");
  9693. });
  9694. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9695. auto se = detail::scope_exit([&] {
  9696. svr.stop();
  9697. t.join();
  9698. ASSERT_FALSE(svr.is_running());
  9699. });
  9700. svr.wait_until_ready();
  9701. Client cli(HOST, PORT);
  9702. auto res = cli.Get("/ip");
  9703. ASSERT_TRUE(res);
  9704. EXPECT_EQ(StatusCode::OK_200, res->status);
  9705. EXPECT_EQ(observed_xff, "");
  9706. EXPECT_TRUE(observed_remote_addr == "::1" ||
  9707. observed_remote_addr == "127.0.0.1");
  9708. }
  9709. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  9710. Server svr;
  9711. svr.set_trusted_proxies({"203.0.113.66"});
  9712. std::string observed_remote_addr;
  9713. std::string observed_xff;
  9714. svr.Get("/ip", [&](const Request &req, Response &res) {
  9715. observed_remote_addr = req.remote_addr;
  9716. observed_xff = req.get_header_value("X-Forwarded-For");
  9717. res.set_content("ok", "text/plain");
  9718. });
  9719. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9720. auto se = detail::scope_exit([&] {
  9721. svr.stop();
  9722. t.join();
  9723. ASSERT_FALSE(svr.is_running());
  9724. });
  9725. svr.wait_until_ready();
  9726. Client cli(HOST, PORT);
  9727. auto res =
  9728. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  9729. ASSERT_TRUE(res);
  9730. EXPECT_EQ(StatusCode::OK_200, res->status);
  9731. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  9732. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9733. }
  9734. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  9735. Server svr;
  9736. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45"});
  9737. std::string observed_remote_addr;
  9738. std::string observed_xff;
  9739. svr.Get("/ip", [&](const Request &req, Response &res) {
  9740. observed_remote_addr = req.remote_addr;
  9741. observed_xff = req.get_header_value("X-Forwarded-For");
  9742. res.set_content("ok", "text/plain");
  9743. });
  9744. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. t.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. });
  9750. svr.wait_until_ready();
  9751. Client cli(HOST, PORT);
  9752. auto res = cli.Get(
  9753. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9754. ASSERT_TRUE(res);
  9755. EXPECT_EQ(StatusCode::OK_200, res->status);
  9756. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9757. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9758. }
  9759. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesFirstFromXFF) {
  9760. Server svr;
  9761. svr.set_trusted_proxies({"192.0.2.45"});
  9762. std::string observed_remote_addr;
  9763. std::string observed_xff;
  9764. svr.Get("/ip", [&](const Request &req, Response &res) {
  9765. observed_remote_addr = req.remote_addr;
  9766. observed_xff = req.get_header_value("X-Forwarded-For");
  9767. res.set_content("ok", "text/plain");
  9768. });
  9769. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9770. auto se = detail::scope_exit([&] {
  9771. svr.stop();
  9772. t.join();
  9773. ASSERT_FALSE(svr.is_running());
  9774. });
  9775. svr.wait_until_ready();
  9776. Client cli(HOST, PORT);
  9777. auto res =
  9778. cli.Get("/ip", {{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  9779. ASSERT_TRUE(res);
  9780. EXPECT_EQ(StatusCode::OK_200, res->status);
  9781. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  9782. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  9783. }
  9784. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  9785. Server svr;
  9786. svr.set_trusted_proxies({"192.0.2.45"});
  9787. std::string observed_remote_addr;
  9788. std::string observed_xff;
  9789. svr.Get("/ip", [&](const Request &req, Response &res) {
  9790. observed_remote_addr = req.remote_addr;
  9791. observed_xff = req.get_header_value("X-Forwarded-For");
  9792. res.set_content("ok", "text/plain");
  9793. });
  9794. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. t.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. Client cli(HOST, PORT);
  9802. auto res = cli.Get(
  9803. "/ip", {{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  9804. ASSERT_TRUE(res);
  9805. EXPECT_EQ(StatusCode::OK_200, res->status);
  9806. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  9807. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9808. }
  9809. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  9810. Server svr;
  9811. svr.set_trusted_proxies({"192.0.2.45"});
  9812. std::string observed_remote_addr;
  9813. std::string observed_xff;
  9814. svr.Get("/ip", [&](const Request &req, Response &res) {
  9815. observed_remote_addr = req.remote_addr;
  9816. observed_xff = req.get_header_value("X-Forwarded-For");
  9817. res.set_content("ok", "text/plain");
  9818. });
  9819. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9820. auto se = detail::scope_exit([&] {
  9821. svr.stop();
  9822. t.join();
  9823. ASSERT_FALSE(svr.is_running());
  9824. });
  9825. svr.wait_until_ready();
  9826. std::string raw_req =
  9827. "GET /ip HTTP/1.1\r\n"
  9828. "Host: localhost\r\n"
  9829. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  9830. "Connection: close\r\n"
  9831. "\r\n";
  9832. std::string out;
  9833. ASSERT_TRUE(send_request(5, raw_req, &out));
  9834. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9835. // Header parser trims surrounding whitespace of the header value
  9836. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  9837. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  9838. }
  9839. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  9840. Server svr;
  9841. svr.Post("/post", [&](const Request &req, Response &res) {
  9842. res.set_content(req.body, "text/plain");
  9843. });
  9844. svr.Put("/put", [&](const Request &req, Response &res) {
  9845. res.set_content(req.body, "text/plain");
  9846. });
  9847. svr.Patch("/patch", [&](const Request &req, Response &res) {
  9848. res.set_content(req.body, "text/plain");
  9849. });
  9850. svr.Delete("/delete", [&](const Request &req, Response &res) {
  9851. res.set_content(req.body, "text/plain");
  9852. });
  9853. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9854. auto se = detail::scope_exit([&] {
  9855. svr.stop();
  9856. t.join();
  9857. ASSERT_FALSE(svr.is_running());
  9858. });
  9859. svr.wait_until_ready();
  9860. std::string resp;
  9861. // POST without Content-Length
  9862. ASSERT_TRUE(send_request(5,
  9863. "POST /post HTTP/1.1\r\n"
  9864. "Host: localhost\r\n"
  9865. "Connection: close\r\n"
  9866. "\r\n",
  9867. &resp));
  9868. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9869. // PUT without Content-Length
  9870. resp.clear();
  9871. ASSERT_TRUE(send_request(5,
  9872. "PUT /put HTTP/1.1\r\n"
  9873. "Host: localhost\r\n"
  9874. "Connection: close\r\n"
  9875. "\r\n",
  9876. &resp));
  9877. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9878. // PATCH without Content-Length
  9879. resp.clear();
  9880. ASSERT_TRUE(send_request(5,
  9881. "PATCH /patch HTTP/1.1\r\n"
  9882. "Host: localhost\r\n"
  9883. "Connection: close\r\n"
  9884. "\r\n",
  9885. &resp));
  9886. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9887. // DELETE without Content-Length
  9888. resp.clear();
  9889. ASSERT_TRUE(send_request(5,
  9890. "DELETE /delete HTTP/1.1\r\n"
  9891. "Host: localhost\r\n"
  9892. "Connection: close\r\n"
  9893. "\r\n",
  9894. &resp));
  9895. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  9896. }
  9897. //==============================================================================
  9898. // open_stream() Tests
  9899. //==============================================================================
  9900. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  9901. std::string result;
  9902. char buf[8192];
  9903. ssize_t n;
  9904. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  9905. result.append(buf, static_cast<size_t>(n));
  9906. }
  9907. return result;
  9908. }
  9909. // Mock stream for unit tests
  9910. class MockStream : public Stream {
  9911. public:
  9912. std::string data;
  9913. size_t pos = 0;
  9914. ssize_t error_after = -1; // -1 = no error
  9915. explicit MockStream(const std::string &d, ssize_t err = -1)
  9916. : data(d), error_after(err) {}
  9917. bool is_readable() const override { return true; }
  9918. bool wait_readable() const override { return true; }
  9919. bool wait_writable() const override { return true; }
  9920. ssize_t read(char *ptr, size_t size) override {
  9921. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  9922. if (pos >= data.size()) return 0;
  9923. size_t limit =
  9924. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  9925. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  9926. std::memcpy(ptr, data.data() + pos, to_read);
  9927. pos += to_read;
  9928. return static_cast<ssize_t>(to_read);
  9929. }
  9930. ssize_t write(const char *, size_t) override { return -1; }
  9931. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  9932. ip = "127.0.0.1";
  9933. port = 0;
  9934. }
  9935. void get_local_ip_and_port(std::string &ip, int &port) const override {
  9936. ip = "127.0.0.1";
  9937. port = 0;
  9938. }
  9939. socket_t socket() const override { return INVALID_SOCKET; }
  9940. time_t duration() const override { return 0; }
  9941. };
  9942. TEST(StreamHandleTest, Basic) {
  9943. ClientImpl::StreamHandle handle;
  9944. EXPECT_FALSE(handle.is_valid());
  9945. handle.response = detail::make_unique<Response>();
  9946. handle.error = Error::Connection;
  9947. EXPECT_FALSE(handle.is_valid());
  9948. handle.error = Error::Success;
  9949. EXPECT_TRUE(handle.is_valid());
  9950. }
  9951. TEST(BodyReaderTest, Basic) {
  9952. MockStream stream("Hello, World!");
  9953. detail::BodyReader reader;
  9954. reader.stream = &stream;
  9955. reader.content_length = 13;
  9956. char buf[32];
  9957. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  9958. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  9959. EXPECT_TRUE(reader.eof);
  9960. }
  9961. TEST(BodyReaderTest, NoStream) {
  9962. detail::BodyReader reader;
  9963. char buf[32];
  9964. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9965. EXPECT_EQ(Error::Connection, reader.last_error);
  9966. }
  9967. TEST(BodyReaderTest, Error) {
  9968. MockStream stream("Hello, World!", 5);
  9969. detail::BodyReader reader;
  9970. reader.stream = &stream;
  9971. reader.content_length = 13;
  9972. char buf[32];
  9973. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  9974. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  9975. EXPECT_EQ(Error::Read, reader.last_error);
  9976. }
  9977. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  9978. // Mock-based StreamHandle tests relying on private internals are removed.
  9979. class OpenStreamTest : public ::testing::Test {
  9980. protected:
  9981. void SetUp() override {
  9982. svr_.Get("/hello", [](const Request &, Response &res) {
  9983. res.set_content("Hello World!", "text/plain");
  9984. });
  9985. svr_.Get("/large", [](const Request &, Response &res) {
  9986. res.set_content(std::string(10000, 'X'), "text/plain");
  9987. });
  9988. svr_.Get("/chunked", [](const Request &, Response &res) {
  9989. res.set_chunked_content_provider("text/plain",
  9990. [](size_t offset, DataSink &sink) {
  9991. if (offset < 15) {
  9992. sink.write("chunk", 5);
  9993. return true;
  9994. }
  9995. sink.done();
  9996. return true;
  9997. });
  9998. });
  9999. svr_.Get("/compressible", [](const Request &, Response &res) {
  10000. res.set_chunked_content_provider("text/plain", [](size_t offset,
  10001. DataSink &sink) {
  10002. if (offset < 100 * 1024) {
  10003. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  10004. sink.write(chunk.data(), chunk.size());
  10005. return true;
  10006. }
  10007. sink.done();
  10008. return true;
  10009. });
  10010. });
  10011. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  10012. [](const Request & /*req*/, Response &res) {
  10013. auto i = new int(0);
  10014. res.set_header("Trailer", "Content-Length, X-Allowed");
  10015. res.set_chunked_content_provider(
  10016. "text/plain",
  10017. [i](size_t /*offset*/, DataSink &sink) {
  10018. switch (*i) {
  10019. case 0: sink.os << "123"; break;
  10020. case 1: sink.os << "456"; break;
  10021. case 2: sink.os << "789"; break;
  10022. case 3: {
  10023. sink.done_with_trailer(
  10024. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  10025. } break;
  10026. }
  10027. (*i)++;
  10028. return true;
  10029. },
  10030. [i](bool success) {
  10031. EXPECT_TRUE(success);
  10032. delete i;
  10033. });
  10034. });
  10035. // Echo headers endpoint for header-related tests
  10036. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  10037. std::string body;
  10038. for (const auto &h : req.headers) {
  10039. body.append(h.first);
  10040. body.push_back(':');
  10041. body.append(h.second);
  10042. body.push_back('\n');
  10043. }
  10044. res.set_content(body, "text/plain");
  10045. });
  10046. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  10047. std::string body;
  10048. for (const auto &h : req.headers) {
  10049. body.append(h.first);
  10050. body.push_back(':');
  10051. body.append(h.second);
  10052. body.push_back('\n');
  10053. }
  10054. res.set_content(body, "text/plain");
  10055. });
  10056. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8787); });
  10057. svr_.wait_until_ready();
  10058. }
  10059. void TearDown() override {
  10060. svr_.stop();
  10061. if (thread_.joinable()) thread_.join();
  10062. }
  10063. Server svr_;
  10064. std::thread thread_;
  10065. };
  10066. TEST_F(OpenStreamTest, Basic) {
  10067. Client cli("127.0.0.1", 8787);
  10068. auto handle = cli.open_stream("GET", "/hello");
  10069. EXPECT_TRUE(handle.is_valid());
  10070. EXPECT_EQ("Hello World!", read_all(handle));
  10071. }
  10072. TEST_F(OpenStreamTest, SmallBuffer) {
  10073. Client cli("127.0.0.1", 8787);
  10074. auto handle = cli.open_stream("GET", "/hello");
  10075. std::string result;
  10076. char buf[4];
  10077. ssize_t n;
  10078. while ((n = handle.read(buf, sizeof(buf))) > 0)
  10079. result.append(buf, static_cast<size_t>(n));
  10080. EXPECT_EQ("Hello World!", result);
  10081. }
  10082. TEST_F(OpenStreamTest, DefaultHeaders) {
  10083. Client cli("127.0.0.1", 8787);
  10084. // open_stream GET should include Host, User-Agent and Accept-Encoding
  10085. {
  10086. auto handle = cli.open_stream("GET", "/echo-headers");
  10087. ASSERT_TRUE(handle.is_valid());
  10088. auto body = read_all(handle);
  10089. EXPECT_NE(body.find("Host:127.0.0.1:8787"), std::string::npos);
  10090. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  10091. std::string::npos);
  10092. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  10093. }
  10094. // open_stream POST with body and no explicit content_type should NOT add
  10095. // text/plain Content-Type (behavior differs from non-streaming path), but
  10096. // should include Content-Length
  10097. {
  10098. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  10099. ASSERT_TRUE(handle.is_valid());
  10100. auto body = read_all(handle);
  10101. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  10102. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  10103. }
  10104. // open_stream POST with explicit Content-Type should preserve it
  10105. {
  10106. auto handle = cli.open_stream("POST", "/echo-headers", {},
  10107. {{"Content-Type", "application/custom"}},
  10108. "{}", "application/custom");
  10109. ASSERT_TRUE(handle.is_valid());
  10110. auto body = read_all(handle);
  10111. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  10112. }
  10113. // User-specified User-Agent must not be overwritten for stream API
  10114. {
  10115. auto handle = cli.open_stream("GET", "/echo-headers", {},
  10116. {{"User-Agent", "MyAgent/1.2"}});
  10117. ASSERT_TRUE(handle.is_valid());
  10118. auto body = read_all(handle);
  10119. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  10120. }
  10121. }
  10122. TEST_F(OpenStreamTest, Large) {
  10123. Client cli("127.0.0.1", 8787);
  10124. auto handle = cli.open_stream("GET", "/large");
  10125. EXPECT_EQ(10000u, read_all(handle).size());
  10126. }
  10127. TEST_F(OpenStreamTest, ConnectionError) {
  10128. Client cli("127.0.0.1", 9999);
  10129. auto handle = cli.open_stream("GET", "/hello");
  10130. EXPECT_FALSE(handle.is_valid());
  10131. }
  10132. TEST_F(OpenStreamTest, Chunked) {
  10133. Client cli("127.0.0.1", 8787);
  10134. auto handle = cli.open_stream("GET", "/chunked");
  10135. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10136. "Transfer-Encoding") == "chunked");
  10137. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  10138. }
  10139. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  10140. Client cli("127.0.0.1", 8787);
  10141. auto handle =
  10142. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  10143. ASSERT_TRUE(handle.is_valid());
  10144. // Consume body to allow trailers to be received/parsed
  10145. auto body = read_all(handle);
  10146. // Explicitly parse trailers (ensure trailers are available for assertion)
  10147. handle.parse_trailers_if_needed();
  10148. EXPECT_EQ(std::string("123456789"), body);
  10149. // The response should include a Trailer header declaring both names
  10150. ASSERT_TRUE(handle.response);
  10151. EXPECT_TRUE(handle.response->has_header("Trailer"));
  10152. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  10153. handle.response->get_header_value("Trailer"));
  10154. // Prohibited trailer must not be present
  10155. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  10156. // Allowed trailer should be present
  10157. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  10158. EXPECT_EQ(std::string("yes"),
  10159. handle.response->get_trailer_value("X-Allowed"));
  10160. // Verify trailers are NOT present as regular headers
  10161. EXPECT_EQ(std::string(""),
  10162. handle.response->get_header_value("Content-Length"));
  10163. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  10164. }
  10165. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10166. TEST_F(OpenStreamTest, Gzip) {
  10167. Client cli("127.0.0.1", 8787);
  10168. auto handle = cli.open_stream("GET", "/compressible", {},
  10169. {{"Accept-Encoding", "gzip"}});
  10170. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  10171. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10172. }
  10173. #endif
  10174. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10175. TEST_F(OpenStreamTest, Brotli) {
  10176. Client cli("127.0.0.1", 8787);
  10177. auto handle =
  10178. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  10179. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  10180. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10181. }
  10182. #endif
  10183. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10184. TEST_F(OpenStreamTest, Zstd) {
  10185. Client cli("127.0.0.1", 8787);
  10186. auto handle = cli.open_stream("GET", "/compressible", {},
  10187. {{"Accept-Encoding", "zstd"}});
  10188. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  10189. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  10190. }
  10191. #endif
  10192. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10193. class SSLOpenStreamTest : public ::testing::Test {
  10194. protected:
  10195. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  10196. void SetUp() override {
  10197. svr_.Get("/hello", [](const Request &, Response &res) {
  10198. res.set_content("Hello SSL World!", "text/plain");
  10199. });
  10200. svr_.Get("/chunked", [](const Request &, Response &res) {
  10201. res.set_chunked_content_provider("text/plain",
  10202. [](size_t offset, DataSink &sink) {
  10203. if (offset < 15) {
  10204. sink.write("chunk", 5);
  10205. return true;
  10206. }
  10207. sink.done();
  10208. return true;
  10209. });
  10210. });
  10211. svr_.Post("/echo", [](const Request &req, Response &res) {
  10212. res.set_content(req.body, req.get_header_value("Content-Type"));
  10213. });
  10214. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  10215. std::string body = req.body;
  10216. res.set_chunked_content_provider(
  10217. "text/plain", [body](size_t offset, DataSink &sink) {
  10218. if (offset < body.size()) {
  10219. sink.write(body.data() + offset, body.size() - offset);
  10220. }
  10221. sink.done();
  10222. return true;
  10223. });
  10224. });
  10225. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8788); });
  10226. svr_.wait_until_ready();
  10227. }
  10228. void TearDown() override {
  10229. svr_.stop();
  10230. if (thread_.joinable()) thread_.join();
  10231. }
  10232. SSLServer svr_;
  10233. std::thread thread_;
  10234. };
  10235. TEST_F(SSLOpenStreamTest, Basic) {
  10236. SSLClient cli("127.0.0.1", 8788);
  10237. cli.enable_server_certificate_verification(false);
  10238. auto handle = cli.open_stream("GET", "/hello");
  10239. ASSERT_TRUE(handle.is_valid());
  10240. EXPECT_EQ("Hello SSL World!", read_all(handle));
  10241. }
  10242. TEST_F(SSLOpenStreamTest, Chunked) {
  10243. SSLClient cli("127.0.0.1", 8788);
  10244. cli.enable_server_certificate_verification(false);
  10245. auto handle = cli.open_stream("GET", "/chunked");
  10246. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10247. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  10248. "Transfer-Encoding") == "chunked");
  10249. auto body = read_all(handle);
  10250. EXPECT_EQ("chunkchunkchunk", body);
  10251. }
  10252. TEST_F(SSLOpenStreamTest, Post) {
  10253. SSLClient cli("127.0.0.1", 8788);
  10254. cli.enable_server_certificate_verification(false);
  10255. auto handle =
  10256. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  10257. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  10258. EXPECT_EQ(200, handle.response->status);
  10259. auto body = read_all(handle);
  10260. EXPECT_EQ("Hello SSL POST", body);
  10261. }
  10262. TEST_F(SSLOpenStreamTest, PostChunked) {
  10263. SSLClient cli("127.0.0.1", 8788);
  10264. cli.enable_server_certificate_verification(false);
  10265. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  10266. "Chunked SSL Data", "text/plain");
  10267. ASSERT_TRUE(handle.is_valid());
  10268. EXPECT_EQ(200, handle.response->status);
  10269. auto body = read_all(handle);
  10270. EXPECT_EQ("Chunked SSL Data", body);
  10271. }
  10272. #endif // CPPHTTPLIB_OPENSSL_SUPPORT
  10273. //==============================================================================
  10274. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  10275. // results for various scenarios.
  10276. //==============================================================================
  10277. TEST(ParityTest, GetVsOpenStream) {
  10278. Server svr;
  10279. const std::string path = "/parity";
  10280. const std::string content = "Parity test content: hello world";
  10281. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10282. res.set_content(content, "text/plain");
  10283. });
  10284. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10285. auto se = detail::scope_exit([&] {
  10286. svr.stop();
  10287. t.join();
  10288. ASSERT_FALSE(svr.is_running());
  10289. });
  10290. svr.wait_until_ready();
  10291. Client cli(HOST, PORT);
  10292. // Non-stream path
  10293. auto r1 = cli.Get(path);
  10294. ASSERT_TRUE(r1);
  10295. EXPECT_EQ(StatusCode::OK_200, r1->status);
  10296. // Stream path
  10297. auto h = cli.open_stream("GET", path);
  10298. ASSERT_TRUE(h.is_valid());
  10299. EXPECT_EQ(r1->body, read_all(h));
  10300. }
  10301. // Helper to compress data with provided compressor type T
  10302. template <typename Compressor>
  10303. static std::string compress_payload_for_parity(const std::string &in) {
  10304. std::string out;
  10305. Compressor compressor;
  10306. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  10307. [&](const char *data, size_t n) {
  10308. out.append(data, n);
  10309. return true;
  10310. });
  10311. EXPECT_TRUE(ok);
  10312. return out;
  10313. }
  10314. // Helper function for compression parity tests
  10315. template <typename Compressor>
  10316. static void test_compression_parity(const std::string &original,
  10317. const std::string &path,
  10318. const std::string &encoding) {
  10319. const std::string compressed =
  10320. compress_payload_for_parity<Compressor>(original);
  10321. Server svr;
  10322. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  10323. res.set_content(compressed, "application/octet-stream");
  10324. res.set_header("Content-Encoding", encoding);
  10325. });
  10326. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  10327. auto se = detail::scope_exit([&] {
  10328. svr.stop();
  10329. t.join();
  10330. ASSERT_FALSE(svr.is_running());
  10331. });
  10332. svr.wait_until_ready();
  10333. Client cli(HOST, PORT);
  10334. // Non-streaming
  10335. {
  10336. auto res = cli.Get(path);
  10337. ASSERT_TRUE(res);
  10338. EXPECT_EQ(StatusCode::OK_200, res->status);
  10339. EXPECT_EQ(original, res->body);
  10340. }
  10341. // Streaming
  10342. {
  10343. auto h = cli.open_stream("GET", path);
  10344. ASSERT_TRUE(h.is_valid());
  10345. EXPECT_EQ(original, read_all(h));
  10346. }
  10347. }
  10348. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10349. TEST(ParityTest, Gzip) {
  10350. test_compression_parity<detail::gzip_compressor>(
  10351. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  10352. }
  10353. #endif
  10354. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  10355. TEST(ParityTest, Brotli) {
  10356. test_compression_parity<detail::brotli_compressor>(
  10357. "Hello, brotli parity test payload", "/parity-br", "br");
  10358. }
  10359. #endif
  10360. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  10361. TEST(ParityTest, Zstd) {
  10362. test_compression_parity<detail::zstd_compressor>(
  10363. "Zstandard parity test payload", "/parity-zstd", "zstd");
  10364. }
  10365. #endif
  10366. //==============================================================================
  10367. // New Stream API Tests
  10368. //==============================================================================
  10369. inline std::string read_body(httplib::stream::Result &result) {
  10370. std::string body;
  10371. while (result.next()) {
  10372. body.append(result.data(), result.size());
  10373. }
  10374. return body;
  10375. }
  10376. TEST(ClientConnectionTest, Basic) {
  10377. httplib::ClientConnection conn;
  10378. EXPECT_FALSE(conn.is_open());
  10379. conn.sock = 1;
  10380. EXPECT_TRUE(conn.is_open());
  10381. httplib::ClientConnection conn2(std::move(conn));
  10382. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  10383. conn2.sock = INVALID_SOCKET;
  10384. }
  10385. // Unified test server for all stream::* tests
  10386. class StreamApiTest : public ::testing::Test {
  10387. protected:
  10388. void SetUp() override {
  10389. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10390. res.set_content("Hello World!", "text/plain");
  10391. });
  10392. svr_.Get("/echo-params",
  10393. [](const httplib::Request &req, httplib::Response &res) {
  10394. std::string r;
  10395. for (const auto &p : req.params) {
  10396. if (!r.empty()) r += "&";
  10397. r += p.first + "=" + p.second;
  10398. }
  10399. res.set_content(r, "text/plain");
  10400. });
  10401. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10402. res.set_content(req.body, req.get_header_value("Content-Type"));
  10403. });
  10404. svr_.Post("/echo-headers",
  10405. [](const httplib::Request &req, httplib::Response &res) {
  10406. std::string r;
  10407. for (const auto &h : req.headers)
  10408. r += h.first + ": " + h.second + "\n";
  10409. res.set_content(r, "text/plain");
  10410. });
  10411. svr_.Post("/echo-params",
  10412. [](const httplib::Request &req, httplib::Response &res) {
  10413. std::string r = "params:";
  10414. for (const auto &p : req.params)
  10415. r += p.first + "=" + p.second + ";";
  10416. res.set_content(r + " body:" + req.body, "text/plain");
  10417. });
  10418. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  10419. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  10420. });
  10421. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10422. res.set_content("PUT:" + req.body, "text/plain");
  10423. });
  10424. svr_.Patch("/echo",
  10425. [](const httplib::Request &req, httplib::Response &res) {
  10426. res.set_content("PATCH:" + req.body, "text/plain");
  10427. });
  10428. svr_.Delete(
  10429. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  10430. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  10431. "text/plain");
  10432. });
  10433. svr_.Get("/head-test",
  10434. [](const httplib::Request &, httplib::Response &res) {
  10435. res.set_content("body for HEAD", "text/plain");
  10436. });
  10437. svr_.Options("/options",
  10438. [](const httplib::Request &, httplib::Response &res) {
  10439. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  10440. });
  10441. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  10442. svr_.wait_until_ready();
  10443. }
  10444. void TearDown() override {
  10445. svr_.stop();
  10446. if (thread_.joinable()) thread_.join();
  10447. }
  10448. httplib::Server svr_;
  10449. std::thread thread_;
  10450. };
  10451. // stream::Get tests
  10452. TEST_F(StreamApiTest, GetBasic) {
  10453. httplib::Client cli(HOST, PORT);
  10454. auto result = httplib::stream::Get(cli, "/hello");
  10455. ASSERT_TRUE(result.is_valid());
  10456. EXPECT_EQ(200, result.status());
  10457. EXPECT_EQ("Hello World!", read_body(result));
  10458. }
  10459. TEST_F(StreamApiTest, GetWithParams) {
  10460. httplib::Client cli(HOST, PORT);
  10461. httplib::Params params{{"foo", "bar"}};
  10462. auto result = httplib::stream::Get(cli, "/echo-params", params);
  10463. ASSERT_TRUE(result.is_valid());
  10464. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  10465. }
  10466. TEST_F(StreamApiTest, GetConnectionError) {
  10467. httplib::Client cli(HOST, 9999);
  10468. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  10469. }
  10470. TEST_F(StreamApiTest, Get404) {
  10471. httplib::Client cli(HOST, PORT);
  10472. auto result = httplib::stream::Get(cli, "/nonexistent");
  10473. EXPECT_TRUE(result.is_valid());
  10474. EXPECT_EQ(404, result.status());
  10475. }
  10476. // stream::Post tests
  10477. TEST_F(StreamApiTest, PostBasic) {
  10478. httplib::Client cli(HOST, PORT);
  10479. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  10480. "application/json");
  10481. ASSERT_TRUE(result.is_valid());
  10482. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  10483. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  10484. }
  10485. TEST_F(StreamApiTest, PostWithHeaders) {
  10486. httplib::Client cli(HOST, PORT);
  10487. httplib::Headers headers{{"X-Custom", "value"}};
  10488. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  10489. "text/plain");
  10490. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  10491. }
  10492. TEST_F(StreamApiTest, PostWithParams) {
  10493. httplib::Client cli(HOST, PORT);
  10494. httplib::Params params{{"k", "v"}};
  10495. auto result =
  10496. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  10497. auto body = read_body(result);
  10498. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  10499. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  10500. }
  10501. TEST_F(StreamApiTest, PostLarge) {
  10502. httplib::Client cli(HOST, PORT);
  10503. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  10504. size_t total = 0;
  10505. while (result.next()) {
  10506. total += result.size();
  10507. }
  10508. EXPECT_EQ(100u * 1024u, total);
  10509. }
  10510. // stream::Put/Patch tests
  10511. TEST_F(StreamApiTest, PutAndPatch) {
  10512. httplib::Client cli(HOST, PORT);
  10513. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  10514. EXPECT_EQ("PUT:test", read_body(put));
  10515. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  10516. EXPECT_EQ("PATCH:test", read_body(patch));
  10517. }
  10518. // stream::Delete tests
  10519. TEST_F(StreamApiTest, Delete) {
  10520. httplib::Client cli(HOST, PORT);
  10521. auto del1 = httplib::stream::Delete(cli, "/resource");
  10522. EXPECT_EQ("Deleted", read_body(del1));
  10523. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  10524. EXPECT_EQ("Deleted:data", read_body(del2));
  10525. }
  10526. // stream::Head/Options tests
  10527. TEST_F(StreamApiTest, HeadAndOptions) {
  10528. httplib::Client cli(HOST, PORT);
  10529. auto head = httplib::stream::Head(cli, "/head-test");
  10530. EXPECT_TRUE(head.is_valid());
  10531. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  10532. auto opts = httplib::stream::Options(cli, "/options");
  10533. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  10534. }
  10535. // SSL stream::* tests
  10536. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10537. class SSLStreamApiTest : public ::testing::Test {
  10538. protected:
  10539. void SetUp() override {
  10540. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  10541. res.set_content("Hello SSL!", "text/plain");
  10542. });
  10543. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  10544. res.set_content(req.body, "text/plain");
  10545. });
  10546. thread_ = std::thread([this]() { svr_.listen("127.0.0.1", 8803); });
  10547. svr_.wait_until_ready();
  10548. }
  10549. void TearDown() override {
  10550. svr_.stop();
  10551. if (thread_.joinable()) thread_.join();
  10552. }
  10553. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  10554. std::thread thread_;
  10555. };
  10556. TEST_F(SSLStreamApiTest, GetAndPost) {
  10557. httplib::SSLClient cli("127.0.0.1", 8803);
  10558. cli.enable_server_certificate_verification(false);
  10559. auto get = httplib::stream::Get(cli, "/hello");
  10560. EXPECT_EQ("Hello SSL!", read_body(get));
  10561. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  10562. EXPECT_EQ("test", read_body(post));
  10563. }
  10564. #endif
  10565. // Tests for Error::Timeout and Error::ConnectionClosed error types
  10566. // These errors are set in SocketStream/SSLSocketStream and propagated through
  10567. // BodyReader
  10568. TEST(ErrorHandlingTest, StreamReadTimeout) {
  10569. // Test that read timeout during streaming is detected
  10570. // Use a large content-length response where server delays mid-stream
  10571. Server svr;
  10572. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10573. // Send a large response with delay in the middle
  10574. res.set_content_provider(
  10575. 1000, // content_length
  10576. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  10577. if (offset < 100) {
  10578. // Send first 100 bytes immediately
  10579. std::string data(100, 'A');
  10580. sink.write(data.c_str(), data.size());
  10581. return true;
  10582. }
  10583. // Then delay longer than client timeout
  10584. std::this_thread::sleep_for(std::chrono::seconds(3));
  10585. std::string data(900, 'B');
  10586. sink.write(data.c_str(), data.size());
  10587. return true;
  10588. });
  10589. });
  10590. auto port = 8091;
  10591. std::thread t([&]() { svr.listen("localhost", port); });
  10592. svr.wait_until_ready();
  10593. Client cli("localhost", port);
  10594. cli.set_read_timeout(1, 0); // 1 second timeout
  10595. auto handle = cli.open_stream("GET", "/slow-stream");
  10596. ASSERT_TRUE(handle.is_valid());
  10597. char buf[256];
  10598. ssize_t total = 0;
  10599. ssize_t n;
  10600. bool got_error = false;
  10601. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10602. total += n;
  10603. }
  10604. if (n < 0) {
  10605. got_error = true;
  10606. // Should be timeout or read error
  10607. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10608. handle.get_read_error() == Error::Read)
  10609. << "Actual error: " << to_string(handle.get_read_error());
  10610. }
  10611. // Either we got an error, or we got less data than expected
  10612. EXPECT_TRUE(got_error || total < 1000)
  10613. << "Expected timeout but got all " << total << " bytes";
  10614. svr.stop();
  10615. t.join();
  10616. }
  10617. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  10618. // Test connection closed detection via BodyReader
  10619. Server svr;
  10620. std::atomic<bool> close_now{false};
  10621. svr.Get("/will-close", [&](const Request &, Response &res) {
  10622. res.set_content_provider(
  10623. 10000, // Large content_length that we won't fully send
  10624. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10625. if (offset < 100) {
  10626. std::string data(100, 'X');
  10627. sink.write(data.c_str(), data.size());
  10628. return true;
  10629. }
  10630. // Wait for signal then abort
  10631. while (!close_now) {
  10632. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10633. }
  10634. return false; // Abort - server will close connection
  10635. });
  10636. });
  10637. auto port = 8092;
  10638. std::thread t([&]() { svr.listen("localhost", port); });
  10639. svr.wait_until_ready();
  10640. Client cli("localhost", port);
  10641. auto handle = cli.open_stream("GET", "/will-close");
  10642. ASSERT_TRUE(handle.is_valid());
  10643. char buf[256];
  10644. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10645. EXPECT_GT(n, 0) << "First read should succeed";
  10646. // Signal server to close
  10647. close_now = true;
  10648. // Keep reading until error or EOF
  10649. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10650. // Keep reading
  10651. }
  10652. // Should get an error since content_length wasn't satisfied
  10653. if (n < 0) {
  10654. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10655. handle.get_read_error() == Error::Read)
  10656. << "Actual error: " << to_string(handle.get_read_error());
  10657. }
  10658. svr.stop();
  10659. t.join();
  10660. }
  10661. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10662. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  10663. // Test that read timeout during SSL streaming is detected
  10664. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10665. svr.Get("/slow-stream", [](const Request &, Response &res) {
  10666. res.set_content_provider(
  10667. 1000, "text/plain",
  10668. [](size_t offset, size_t /*length*/, DataSink &sink) {
  10669. if (offset < 100) {
  10670. std::string data(100, 'A');
  10671. sink.write(data.c_str(), data.size());
  10672. return true;
  10673. }
  10674. std::this_thread::sleep_for(std::chrono::seconds(3));
  10675. std::string data(900, 'B');
  10676. sink.write(data.c_str(), data.size());
  10677. return true;
  10678. });
  10679. });
  10680. auto port = 8093;
  10681. std::thread t([&]() { svr.listen("localhost", port); });
  10682. svr.wait_until_ready();
  10683. SSLClient cli("localhost", port);
  10684. cli.enable_server_certificate_verification(false);
  10685. cli.set_read_timeout(1, 0); // 1 second timeout
  10686. auto handle = cli.open_stream("GET", "/slow-stream");
  10687. ASSERT_TRUE(handle.is_valid());
  10688. char buf[256];
  10689. ssize_t total = 0;
  10690. ssize_t n;
  10691. bool got_error = false;
  10692. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10693. total += n;
  10694. }
  10695. if (n < 0) {
  10696. got_error = true;
  10697. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  10698. handle.get_read_error() == Error::Read)
  10699. << "Actual error: " << to_string(handle.get_read_error());
  10700. }
  10701. EXPECT_TRUE(got_error || total < 1000)
  10702. << "Expected timeout but got all " << total << " bytes";
  10703. svr.stop();
  10704. t.join();
  10705. }
  10706. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  10707. // Test SSL connection closed detection
  10708. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10709. std::atomic<bool> close_now{false};
  10710. svr.Get("/will-close", [&](const Request &, Response &res) {
  10711. res.set_content_provider(
  10712. 10000, "text/plain",
  10713. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  10714. if (offset < 100) {
  10715. std::string data(100, 'X');
  10716. sink.write(data.c_str(), data.size());
  10717. return true;
  10718. }
  10719. while (!close_now) {
  10720. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  10721. }
  10722. return false;
  10723. });
  10724. });
  10725. auto port = 8094;
  10726. std::thread t([&]() { svr.listen("localhost", port); });
  10727. svr.wait_until_ready();
  10728. SSLClient cli("localhost", port);
  10729. cli.enable_server_certificate_verification(false);
  10730. auto handle = cli.open_stream("GET", "/will-close");
  10731. ASSERT_TRUE(handle.is_valid());
  10732. char buf[256];
  10733. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  10734. EXPECT_GT(n, 0);
  10735. // Signal server to close
  10736. close_now = true;
  10737. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10738. // Keep reading
  10739. }
  10740. if (n < 0) {
  10741. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  10742. handle.get_read_error() == Error::Read)
  10743. << "Actual error: " << to_string(handle.get_read_error());
  10744. }
  10745. svr.stop();
  10746. t.join();
  10747. }
  10748. #endif
  10749. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  10750. using namespace httplib;
  10751. // Create a test file
  10752. const char *fname = "etag_testfile.txt";
  10753. const char *content = "etag-content";
  10754. {
  10755. std::ofstream ofs(fname);
  10756. ofs << content;
  10757. ASSERT_TRUE(ofs.good());
  10758. }
  10759. Server svr;
  10760. svr.set_mount_point("/static", ".");
  10761. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  10762. svr.wait_until_ready();
  10763. Client cli(HOST, PORT);
  10764. // First request: should get 200 with ETag header
  10765. auto res1 = cli.Get("/static/etag_testfile.txt");
  10766. ASSERT_TRUE(res1);
  10767. ASSERT_EQ(200, res1->status);
  10768. ASSERT_TRUE(res1->has_header("ETag"));
  10769. std::string etag = res1->get_header_value("ETag");
  10770. EXPECT_FALSE(etag.empty());
  10771. // Verify ETag format: W/"hex-hex"
  10772. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  10773. EXPECT_EQ('W', etag[0]);
  10774. EXPECT_EQ('/', etag[1]);
  10775. EXPECT_EQ('"', etag[2]);
  10776. EXPECT_EQ('"', etag.back());
  10777. // Exact match: expect 304 Not Modified
  10778. Headers h2 = {{"If-None-Match", etag}};
  10779. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  10780. ASSERT_TRUE(res2);
  10781. EXPECT_EQ(304, res2->status);
  10782. // Wildcard match: expect 304 Not Modified
  10783. Headers h3 = {{"If-None-Match", "*"}};
  10784. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  10785. ASSERT_TRUE(res3);
  10786. EXPECT_EQ(304, res3->status);
  10787. // Non-matching ETag: expect 200
  10788. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  10789. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  10790. ASSERT_TRUE(res4);
  10791. EXPECT_EQ(200, res4->status);
  10792. // Multiple ETags with one matching: expect 304
  10793. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  10794. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  10795. ASSERT_TRUE(res5);
  10796. EXPECT_EQ(304, res5->status);
  10797. svr.stop();
  10798. t.join();
  10799. std::remove(fname);
  10800. }
  10801. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  10802. using namespace httplib;
  10803. Server svr;
  10804. svr.set_mount_point("/static", ".");
  10805. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10806. svr.wait_until_ready();
  10807. Client cli(HOST, PORT);
  10808. // Send If-None-Match: * to a non-existent file
  10809. Headers h = {{"If-None-Match", "*"}};
  10810. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  10811. ASSERT_TRUE(res);
  10812. EXPECT_EQ(404, res->status);
  10813. svr.stop();
  10814. t.join();
  10815. }
  10816. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  10817. using namespace httplib;
  10818. // Create a test file
  10819. const char *fname = "ims_testfile.txt";
  10820. const char *content = "if-modified-since-test";
  10821. {
  10822. std::ofstream ofs(fname);
  10823. ofs << content;
  10824. ASSERT_TRUE(ofs.good());
  10825. }
  10826. Server svr;
  10827. svr.set_mount_point("/static", ".");
  10828. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10829. svr.wait_until_ready();
  10830. Client cli(HOST, PORT);
  10831. // First request: should get 200 with Last-Modified header
  10832. auto res1 = cli.Get("/static/ims_testfile.txt");
  10833. ASSERT_TRUE(res1);
  10834. ASSERT_EQ(200, res1->status);
  10835. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10836. std::string last_modified = res1->get_header_value("Last-Modified");
  10837. EXPECT_FALSE(last_modified.empty());
  10838. // If-Modified-Since with same time: expect 304
  10839. Headers h2 = {{"If-Modified-Since", last_modified}};
  10840. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  10841. ASSERT_TRUE(res2);
  10842. EXPECT_EQ(304, res2->status);
  10843. // If-Modified-Since with future time: expect 304
  10844. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10845. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  10846. ASSERT_TRUE(res3);
  10847. EXPECT_EQ(304, res3->status);
  10848. // If-Modified-Since with past time: expect 200
  10849. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10850. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  10851. ASSERT_TRUE(res4);
  10852. EXPECT_EQ(200, res4->status);
  10853. // If-None-Match takes precedence over If-Modified-Since
  10854. // (send matching ETag with old If-Modified-Since -> should still be 304)
  10855. ASSERT_TRUE(res1->has_header("ETag"));
  10856. std::string etag = res1->get_header_value("ETag");
  10857. Headers h5 = {{"If-None-Match", etag},
  10858. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10859. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  10860. ASSERT_TRUE(res5);
  10861. EXPECT_EQ(304, res5->status);
  10862. svr.stop();
  10863. t.join();
  10864. std::remove(fname);
  10865. }
  10866. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  10867. using namespace httplib;
  10868. Server svr;
  10869. // Endpoint that returns compressible content
  10870. svr.Get("/compressible", [](const Request &, Response &res) {
  10871. // Return a large enough body to trigger compression
  10872. std::string body(1000, 'a');
  10873. res.set_content(body, "text/plain");
  10874. });
  10875. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10876. svr.wait_until_ready();
  10877. Client cli(HOST, PORT);
  10878. // Request with gzip support: should get Vary header when compressed
  10879. cli.set_compress(true);
  10880. auto res1 = cli.Get("/compressible");
  10881. ASSERT_TRUE(res1);
  10882. EXPECT_EQ(200, res1->status);
  10883. // If Content-Encoding is set, Vary should also be set
  10884. if (res1->has_header("Content-Encoding")) {
  10885. EXPECT_TRUE(res1->has_header("Vary"));
  10886. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  10887. }
  10888. // Request without Accept-Encoding header: should not have compression
  10889. Headers h_no_compress;
  10890. auto res2 = cli.Get("/compressible", h_no_compress);
  10891. ASSERT_TRUE(res2);
  10892. EXPECT_EQ(200, res2->status);
  10893. // Verify Vary header is present when compression is applied
  10894. // (the exact behavior depends on server configuration)
  10895. svr.stop();
  10896. t.join();
  10897. }
  10898. TEST(ETagTest, IfRangeWithETag) {
  10899. using namespace httplib;
  10900. // Create a test file with known content
  10901. const char *fname = "if_range_testfile.txt";
  10902. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  10903. {
  10904. std::ofstream ofs(fname);
  10905. ofs << content;
  10906. ASSERT_TRUE(ofs.good());
  10907. }
  10908. Server svr;
  10909. svr.set_mount_point("/static", ".");
  10910. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10911. svr.wait_until_ready();
  10912. Client cli(HOST, PORT);
  10913. // First request: get ETag
  10914. auto res1 = cli.Get("/static/if_range_testfile.txt");
  10915. ASSERT_TRUE(res1);
  10916. ASSERT_EQ(200, res1->status);
  10917. ASSERT_TRUE(res1->has_header("ETag"));
  10918. std::string etag = res1->get_header_value("ETag");
  10919. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  10920. // Since our server generates weak ETags (W/"..."), If-Range with our
  10921. // ETag should NOT result in partial content - it should return full content.
  10922. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  10923. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  10924. ASSERT_TRUE(res2);
  10925. // Weak ETag in If-Range -> full content (200), not partial (206)
  10926. EXPECT_EQ(200, res2->status);
  10927. EXPECT_EQ(content, res2->body);
  10928. EXPECT_FALSE(res2->has_header("Content-Range"));
  10929. // Range request with non-matching If-Range (ETag): should get 200 (full
  10930. // content)
  10931. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  10932. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  10933. ASSERT_TRUE(res3);
  10934. EXPECT_EQ(200, res3->status);
  10935. EXPECT_EQ(content, res3->body);
  10936. EXPECT_FALSE(res3->has_header("Content-Range"));
  10937. // Range request with strong ETag (hypothetical - our server doesn't generate
  10938. // strong ETags, but if client sends a strong ETag that doesn't match, it
  10939. // should return full content)
  10940. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  10941. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  10942. ASSERT_TRUE(res4);
  10943. EXPECT_EQ(200, res4->status);
  10944. EXPECT_EQ(content, res4->body);
  10945. EXPECT_FALSE(res4->has_header("Content-Range"));
  10946. svr.stop();
  10947. t.join();
  10948. std::remove(fname);
  10949. }
  10950. TEST(ETagTest, IfRangeWithDate) {
  10951. using namespace httplib;
  10952. // Create a test file
  10953. const char *fname = "if_range_date_testfile.txt";
  10954. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  10955. {
  10956. std::ofstream ofs(fname);
  10957. ofs << content;
  10958. ASSERT_TRUE(ofs.good());
  10959. }
  10960. Server svr;
  10961. svr.set_mount_point("/static", ".");
  10962. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  10963. svr.wait_until_ready();
  10964. Client cli(HOST, PORT);
  10965. // First request: get Last-Modified
  10966. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  10967. ASSERT_TRUE(res1);
  10968. ASSERT_EQ(200, res1->status);
  10969. ASSERT_TRUE(res1->has_header("Last-Modified"));
  10970. std::string last_modified = res1->get_header_value("Last-Modified");
  10971. // Range request with matching If-Range (date): should get 206
  10972. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  10973. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  10974. ASSERT_TRUE(res2);
  10975. EXPECT_EQ(206, res2->status);
  10976. EXPECT_EQ("FGHIJ", res2->body);
  10977. // Range request with old If-Range date: should get 200 (full content)
  10978. Headers h3 = {{"Range", "bytes=5-9"},
  10979. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  10980. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  10981. ASSERT_TRUE(res3);
  10982. EXPECT_EQ(200, res3->status);
  10983. EXPECT_EQ(content, res3->body);
  10984. // Range request with future If-Range date: should get 206
  10985. Headers h4 = {{"Range", "bytes=0-4"},
  10986. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  10987. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  10988. ASSERT_TRUE(res4);
  10989. EXPECT_EQ(206, res4->status);
  10990. EXPECT_EQ("ABCDE", res4->body);
  10991. svr.stop();
  10992. t.join();
  10993. std::remove(fname);
  10994. }
  10995. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  10996. using namespace httplib;
  10997. const char *fname = "etag_malformed.txt";
  10998. const char *content = "malformed-etag";
  10999. {
  11000. std::ofstream ofs(fname);
  11001. ofs << content;
  11002. ASSERT_TRUE(ofs.good());
  11003. }
  11004. Server svr;
  11005. svr.set_mount_point("/static", ".");
  11006. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11007. svr.wait_until_ready();
  11008. Client cli(HOST, PORT);
  11009. // baseline: should get 200 and an ETag
  11010. auto res1 = cli.Get("/static/etag_malformed.txt");
  11011. ASSERT_TRUE(res1);
  11012. ASSERT_EQ(200, res1->status);
  11013. ASSERT_TRUE(res1->has_header("ETag"));
  11014. // Malformed ETag value (missing quotes) should be treated as non-matching
  11015. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  11016. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  11017. ASSERT_TRUE(res_bad);
  11018. EXPECT_EQ(200, res_bad->status);
  11019. // Whitespace-only header value should be considered invalid / non-matching
  11020. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  11021. "Host: localhost\r\n"
  11022. "If-None-Match: \r\n"
  11023. "Connection: close\r\n"
  11024. "\r\n";
  11025. std::string out;
  11026. ASSERT_TRUE(send_request(5, raw_req, &out));
  11027. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  11028. svr.stop();
  11029. t.join();
  11030. std::remove(fname);
  11031. }
  11032. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  11033. using namespace httplib;
  11034. const char *fname = "ims_invalid_format.txt";
  11035. const char *content = "ims-bad-format";
  11036. {
  11037. std::ofstream ofs(fname);
  11038. ofs << content;
  11039. ASSERT_TRUE(ofs.good());
  11040. }
  11041. Server svr;
  11042. svr.set_mount_point("/static", ".");
  11043. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11044. svr.wait_until_ready();
  11045. Client cli(HOST, PORT);
  11046. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  11047. ASSERT_TRUE(res1);
  11048. ASSERT_EQ(200, res1->status);
  11049. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11050. // If-Modified-Since with invalid format should not result in 304
  11051. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  11052. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  11053. ASSERT_TRUE(res_bad);
  11054. EXPECT_EQ(200, res_bad->status);
  11055. // If-Range with invalid date format should be treated as mismatch -> full
  11056. // content (200)
  11057. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  11058. {"If-Range", "invalid-date"}};
  11059. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  11060. ASSERT_TRUE(res_ifrange);
  11061. EXPECT_EQ(200, res_ifrange->status);
  11062. svr.stop();
  11063. t.join();
  11064. std::remove(fname);
  11065. }
  11066. TEST(ETagTest, IfRangeWithMalformedETag) {
  11067. using namespace httplib;
  11068. const char *fname = "ifrange_malformed.txt";
  11069. const std::string content = "0123456789";
  11070. {
  11071. std::ofstream ofs(fname);
  11072. ofs << content;
  11073. ASSERT_TRUE(ofs.good());
  11074. }
  11075. Server svr;
  11076. svr.set_mount_point("/static", ".");
  11077. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11078. svr.wait_until_ready();
  11079. Client cli(HOST, PORT);
  11080. // First request: get ETag
  11081. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  11082. ASSERT_TRUE(res1);
  11083. ASSERT_EQ(200, res1->status);
  11084. ASSERT_TRUE(res1->has_header("ETag"));
  11085. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  11086. // full content (200)
  11087. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  11088. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  11089. ASSERT_TRUE(res2);
  11090. EXPECT_EQ(200, res2->status);
  11091. EXPECT_EQ(content, res2->body);
  11092. svr.stop();
  11093. t.join();
  11094. std::remove(fname);
  11095. }
  11096. TEST(ETagTest, ExtremeLargeDateValues) {
  11097. using namespace httplib;
  11098. const char *fname = "ims_extreme_date.txt";
  11099. const char *content = "ims-extreme-date";
  11100. {
  11101. std::ofstream ofs(fname);
  11102. ofs << content;
  11103. ASSERT_TRUE(ofs.good());
  11104. }
  11105. Server svr;
  11106. svr.set_mount_point("/static", ".");
  11107. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11108. svr.wait_until_ready();
  11109. Client cli(HOST, PORT);
  11110. auto res1 = cli.Get(std::string("/static/") + fname);
  11111. ASSERT_TRUE(res1);
  11112. ASSERT_EQ(200, res1->status);
  11113. ASSERT_TRUE(res1->has_header("Last-Modified"));
  11114. // Extremely large year that may overflow date parsing routines.
  11115. Headers h_large_date = {
  11116. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11117. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  11118. ASSERT_TRUE(res_bad);
  11119. // Expect server to treat this as invalid/mismatch and return full content
  11120. EXPECT_EQ(200, res_bad->status);
  11121. // If-Range with extremely large date should be treated as mismatch -> full
  11122. // content (200)
  11123. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  11124. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11125. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  11126. ASSERT_TRUE(res_ifrange);
  11127. EXPECT_EQ(200, res_ifrange->status);
  11128. svr.stop();
  11129. t.join();
  11130. std::remove(fname);
  11131. }
  11132. TEST(ETagTest, NegativeFileModificationTime) {
  11133. using namespace httplib;
  11134. const char *fname = "ims_negative_mtime.txt";
  11135. const std::string content = "negative-mtime";
  11136. {
  11137. std::ofstream ofs(fname);
  11138. ofs << content;
  11139. ASSERT_TRUE(ofs.good());
  11140. }
  11141. // Try to set file mtime to a negative value. This may fail on some
  11142. // platforms/filesystems; if it fails, the test will still verify server
  11143. // behaves safely by performing a regular conditional request.
  11144. #if defined(__APPLE__) || defined(__linux__)
  11145. bool set_negative = false;
  11146. do {
  11147. struct timeval times[2];
  11148. // access time: now
  11149. times[0].tv_sec = time(nullptr);
  11150. times[0].tv_usec = 0;
  11151. // modification time: negative (e.g., -1)
  11152. times[1].tv_sec = -1;
  11153. times[1].tv_usec = 0;
  11154. if (utimes(fname, times) == 0) { set_negative = true; }
  11155. } while (0);
  11156. #else
  11157. bool set_negative = false;
  11158. #endif
  11159. Server svr;
  11160. svr.set_mount_point("/static", ".");
  11161. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  11162. svr.wait_until_ready();
  11163. Client cli(HOST, PORT);
  11164. auto res1 = cli.Get(std::string("/static/") + fname);
  11165. ASSERT_TRUE(res1);
  11166. ASSERT_EQ(200, res1->status);
  11167. bool has_last_modified = res1->has_header("Last-Modified");
  11168. std::string last_modified;
  11169. if (has_last_modified) {
  11170. last_modified = res1->get_header_value("Last-Modified");
  11171. }
  11172. if (set_negative) {
  11173. // If we successfully set a negative mtime, ensure server returns a
  11174. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  11175. // with an old date and ensure server handles it without crash.
  11176. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  11177. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  11178. ASSERT_TRUE(res2);
  11179. // Behavior may vary; at minimum ensure server responds (200 or 304).
  11180. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  11181. } else {
  11182. // Could not set negative mtime on this platform; fall back to verifying
  11183. // that normal invalid/malformed dates are treated safely (non-304).
  11184. Headers h_bad_date = {
  11185. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  11186. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  11187. ASSERT_TRUE(res_bad);
  11188. EXPECT_EQ(200, res_bad->status);
  11189. }
  11190. svr.stop();
  11191. t.join();
  11192. std::remove(fname);
  11193. }
  11194. //==============================================================================
  11195. // SSE Parsing Tests
  11196. //==============================================================================
  11197. class SSEParsingTest : public ::testing::Test {
  11198. protected:
  11199. // Test helper that mimics SSE parsing behavior
  11200. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  11201. int &retry_ms) {
  11202. // Blank line signals end of event
  11203. if (line.empty() || line == "\r") { return true; }
  11204. // Lines starting with ':' are comments (ignored)
  11205. if (!line.empty() && line[0] == ':') { return false; }
  11206. // Find the colon separator
  11207. auto colon_pos = line.find(':');
  11208. if (colon_pos == std::string::npos) {
  11209. // Line with no colon is treated as field name with empty value
  11210. return false;
  11211. }
  11212. std::string field = line.substr(0, colon_pos);
  11213. std::string value;
  11214. // Value starts after colon, skip optional single space
  11215. if (colon_pos + 1 < line.size()) {
  11216. size_t value_start = colon_pos + 1;
  11217. if (line[value_start] == ' ') { value_start++; }
  11218. value = line.substr(value_start);
  11219. // Remove trailing \r if present
  11220. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  11221. }
  11222. // Handle known fields
  11223. if (field == "event") {
  11224. msg.event = value;
  11225. } else if (field == "data") {
  11226. // Multiple data lines are concatenated with newlines
  11227. if (!msg.data.empty()) { msg.data += "\n"; }
  11228. msg.data += value;
  11229. } else if (field == "id") {
  11230. // Empty id is valid (clears the last event ID)
  11231. msg.id = value;
  11232. } else if (field == "retry") {
  11233. // Parse retry interval in milliseconds
  11234. try {
  11235. retry_ms = std::stoi(value);
  11236. } catch (...) {
  11237. // Invalid retry value, ignore
  11238. }
  11239. }
  11240. // Unknown fields are ignored per SSE spec
  11241. return false;
  11242. }
  11243. };
  11244. // Test: Single-line data
  11245. TEST_F(SSEParsingTest, SingleLineData) {
  11246. sse::SSEMessage msg;
  11247. int retry_ms = 3000;
  11248. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  11249. EXPECT_EQ(msg.data, "hello");
  11250. EXPECT_EQ(msg.event, "message");
  11251. // Blank line ends event
  11252. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11253. }
  11254. // Test: Multi-line data
  11255. TEST_F(SSEParsingTest, MultiLineData) {
  11256. sse::SSEMessage msg;
  11257. int retry_ms = 3000;
  11258. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  11259. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  11260. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  11261. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  11262. }
  11263. // Test: Custom event types
  11264. TEST_F(SSEParsingTest, CustomEventType) {
  11265. sse::SSEMessage msg;
  11266. int retry_ms = 3000;
  11267. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  11268. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  11269. EXPECT_EQ(msg.event, "update");
  11270. EXPECT_EQ(msg.data, "payload");
  11271. }
  11272. // Test: Event ID handling
  11273. TEST_F(SSEParsingTest, EventIdHandling) {
  11274. sse::SSEMessage msg;
  11275. int retry_ms = 3000;
  11276. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  11277. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  11278. EXPECT_EQ(msg.id, "12345");
  11279. }
  11280. // Test: Empty event ID (clears last event ID)
  11281. TEST_F(SSEParsingTest, EmptyEventId) {
  11282. sse::SSEMessage msg;
  11283. msg.id = "previous";
  11284. int retry_ms = 3000;
  11285. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  11286. EXPECT_EQ(msg.id, "");
  11287. }
  11288. // Test: Retry field parsing
  11289. TEST_F(SSEParsingTest, RetryFieldParsing) {
  11290. sse::SSEMessage msg;
  11291. int retry_ms = 3000;
  11292. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  11293. EXPECT_EQ(retry_ms, 5000);
  11294. }
  11295. // Test: Invalid retry value
  11296. TEST_F(SSEParsingTest, InvalidRetryValue) {
  11297. sse::SSEMessage msg;
  11298. int retry_ms = 3000;
  11299. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  11300. EXPECT_EQ(retry_ms, 3000); // Unchanged
  11301. }
  11302. // Test: Comments (lines starting with :)
  11303. TEST_F(SSEParsingTest, CommentsIgnored) {
  11304. sse::SSEMessage msg;
  11305. int retry_ms = 3000;
  11306. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  11307. EXPECT_EQ(msg.data, "");
  11308. EXPECT_EQ(msg.event, "message");
  11309. }
  11310. // Test: Colon in value
  11311. TEST_F(SSEParsingTest, ColonInValue) {
  11312. sse::SSEMessage msg;
  11313. int retry_ms = 3000;
  11314. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  11315. EXPECT_EQ(msg.data, "hello:world:test");
  11316. }
  11317. // Test: Line with no colon (field name only)
  11318. TEST_F(SSEParsingTest, FieldNameOnly) {
  11319. sse::SSEMessage msg;
  11320. int retry_ms = 3000;
  11321. // According to SSE spec, this is treated as field name with empty value
  11322. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  11323. // Since we don't recognize "data" without colon, data should be empty
  11324. EXPECT_EQ(msg.data, "");
  11325. }
  11326. // Test: Trailing \r handling
  11327. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  11328. sse::SSEMessage msg;
  11329. int retry_ms = 3000;
  11330. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  11331. EXPECT_EQ(msg.data, "hello");
  11332. }
  11333. // Test: Unknown fields ignored
  11334. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  11335. sse::SSEMessage msg;
  11336. int retry_ms = 3000;
  11337. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  11338. EXPECT_EQ(msg.data, "");
  11339. EXPECT_EQ(msg.event, "message");
  11340. }
  11341. // Test: Space after colon is optional
  11342. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  11343. sse::SSEMessage msg1, msg2;
  11344. int retry_ms = 3000;
  11345. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  11346. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  11347. EXPECT_EQ(msg1.data, "hello");
  11348. EXPECT_EQ(msg2.data, "hello");
  11349. }
  11350. // Test: SSEMessage clear
  11351. TEST_F(SSEParsingTest, MessageClear) {
  11352. sse::SSEMessage msg;
  11353. msg.event = "custom";
  11354. msg.data = "some data";
  11355. msg.id = "123";
  11356. msg.clear();
  11357. EXPECT_EQ(msg.event, "message");
  11358. EXPECT_EQ(msg.data, "");
  11359. EXPECT_EQ(msg.id, "");
  11360. }
  11361. // Test: Complete event parsing
  11362. TEST_F(SSEParsingTest, CompleteEventParsing) {
  11363. sse::SSEMessage msg;
  11364. int retry_ms = 3000;
  11365. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  11366. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  11367. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  11368. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  11369. // Blank line ends event
  11370. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  11371. EXPECT_EQ(msg.event, "notification");
  11372. EXPECT_EQ(msg.id, "evt-42");
  11373. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  11374. EXPECT_EQ(retry_ms, 1000);
  11375. }
  11376. //==============================================================================
  11377. // Integration Tests with Server
  11378. //==============================================================================
  11379. class SSEIntegrationTest : public ::testing::Test {
  11380. protected:
  11381. void SetUp() override {
  11382. stop_server_.store(false);
  11383. events_.clear();
  11384. server_ = httplib::detail::make_unique<Server>();
  11385. setup_server();
  11386. start_server();
  11387. }
  11388. void TearDown() override {
  11389. stop_server_.store(true);
  11390. event_cv_.notify_all();
  11391. server_->stop();
  11392. if (server_thread_.joinable()) { server_thread_.join(); }
  11393. }
  11394. void setup_server() {
  11395. // Simple SSE endpoint
  11396. server_->Get("/events", [this](const Request &req, Response &res) {
  11397. auto last_id = req.get_header_value("Last-Event-ID");
  11398. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  11399. res.set_chunked_content_provider(
  11400. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  11401. std::unique_lock<std::mutex> lock(event_mutex_);
  11402. if (event_cv_.wait_for(
  11403. lock, std::chrono::milliseconds(200), [this] {
  11404. return !events_.empty() || stop_server_.load();
  11405. })) {
  11406. if (stop_server_.load()) { return false; }
  11407. if (!events_.empty()) {
  11408. std::string event = events_.front();
  11409. events_.erase(events_.begin());
  11410. sink.write(event.data(), event.size());
  11411. return true;
  11412. }
  11413. }
  11414. return !stop_server_.load();
  11415. });
  11416. });
  11417. // Endpoint that returns error
  11418. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  11419. res.status = 500;
  11420. res.set_content("Internal Server Error", "text/plain");
  11421. });
  11422. // Endpoint for custom event types
  11423. server_->Get("/custom-events", [](const Request &, Response &res) {
  11424. res.set_chunked_content_provider(
  11425. "text/event-stream", [](size_t offset, DataSink &sink) {
  11426. if (offset == 0) {
  11427. std::string event = "event: update\ndata: updated\n\n"
  11428. "event: delete\ndata: deleted\n\n";
  11429. sink.write(event.data(), event.size());
  11430. }
  11431. return false; // End stream after sending
  11432. });
  11433. });
  11434. }
  11435. void start_server() {
  11436. port_ = server_->bind_to_any_port(HOST);
  11437. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  11438. // Wait for server to start
  11439. while (!server_->is_running()) {
  11440. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  11441. }
  11442. }
  11443. int get_port() const { return port_; }
  11444. void send_event(const std::string &event) {
  11445. std::lock_guard<std::mutex> lock(event_mutex_);
  11446. events_.push_back(event);
  11447. event_cv_.notify_all();
  11448. }
  11449. std::unique_ptr<Server> server_;
  11450. std::thread server_thread_;
  11451. std::mutex event_mutex_;
  11452. std::condition_variable event_cv_;
  11453. std::vector<std::string> events_;
  11454. std::atomic<bool> stop_server_{false};
  11455. std::string last_received_event_id_;
  11456. int port_ = 0;
  11457. };
  11458. // Test: Successful connection and on_open callback
  11459. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  11460. // Add a simple endpoint that sends one event and closes
  11461. server_->Get("/simple-event", [](const Request &, Response &res) {
  11462. res.set_chunked_content_provider(
  11463. "text/event-stream", [](size_t offset, DataSink &sink) {
  11464. if (offset == 0) {
  11465. std::string event = "data: hello\n\n";
  11466. sink.write(event.data(), event.size());
  11467. }
  11468. return false; // Close stream after sending
  11469. });
  11470. });
  11471. Client client("localhost", get_port());
  11472. sse::SSEClient sse(client, "/simple-event");
  11473. std::atomic<bool> open_called{false};
  11474. std::atomic<bool> message_received{false};
  11475. sse.on_open([&open_called]() { open_called.store(true); });
  11476. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  11477. if (msg.data == "hello") { message_received.store(true); }
  11478. });
  11479. sse.set_reconnect_interval(100);
  11480. sse.set_max_reconnect_attempts(1);
  11481. // Start async
  11482. sse.start_async();
  11483. // Wait for message to be processed
  11484. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11485. sse.stop();
  11486. EXPECT_TRUE(open_called.load());
  11487. EXPECT_TRUE(message_received.load());
  11488. }
  11489. // Test: on_message callback
  11490. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  11491. // Endpoint that sends multiple events then closes
  11492. server_->Get("/multi-event", [](const Request &, Response &res) {
  11493. res.set_chunked_content_provider(
  11494. "text/event-stream", [](size_t offset, DataSink &sink) {
  11495. if (offset == 0) {
  11496. std::string events = "data: message1\n\ndata: message2\n\n";
  11497. sink.write(events.data(), events.size());
  11498. }
  11499. return false;
  11500. });
  11501. });
  11502. Client client("localhost", get_port());
  11503. sse::SSEClient sse(client, "/multi-event");
  11504. std::vector<std::string> received_messages;
  11505. std::mutex messages_mutex;
  11506. sse.on_message([&](const sse::SSEMessage &msg) {
  11507. std::lock_guard<std::mutex> lock(messages_mutex);
  11508. received_messages.push_back(msg.data);
  11509. });
  11510. sse.set_reconnect_interval(100);
  11511. sse.set_max_reconnect_attempts(1);
  11512. sse.start_async();
  11513. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11514. sse.stop();
  11515. std::lock_guard<std::mutex> lock(messages_mutex);
  11516. EXPECT_GE(received_messages.size(), 2u);
  11517. if (received_messages.size() >= 2) {
  11518. EXPECT_EQ(received_messages[0], "message1");
  11519. EXPECT_EQ(received_messages[1], "message2");
  11520. }
  11521. }
  11522. // Test: on_event for specific types
  11523. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  11524. Client client("localhost", get_port());
  11525. sse::SSEClient sse(client, "/custom-events");
  11526. std::atomic<bool> update_received{false};
  11527. std::atomic<bool> delete_received{false};
  11528. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  11529. if (msg.data == "updated") { update_received.store(true); }
  11530. });
  11531. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  11532. if (msg.data == "deleted") { delete_received.store(true); }
  11533. });
  11534. sse.set_max_reconnect_attempts(1);
  11535. sse.start_async();
  11536. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  11537. sse.stop();
  11538. EXPECT_TRUE(update_received.load());
  11539. EXPECT_TRUE(delete_received.load());
  11540. }
  11541. // Test: on_error callback on connection failure
  11542. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  11543. // Connect to a non-existent port
  11544. Client client("localhost", 59999);
  11545. sse::SSEClient sse(client, "/events");
  11546. std::atomic<bool> error_called{false};
  11547. Error received_error = Error::Success;
  11548. sse.on_error([&](Error err) {
  11549. error_called.store(true);
  11550. received_error = err;
  11551. });
  11552. sse.set_reconnect_interval(50);
  11553. sse.set_max_reconnect_attempts(1);
  11554. sse.start_async();
  11555. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11556. sse.stop();
  11557. EXPECT_TRUE(error_called.load());
  11558. EXPECT_NE(received_error, Error::Success);
  11559. }
  11560. // Test: Last-Event-ID header sent on reconnect
  11561. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  11562. // Endpoint that sends event with ID
  11563. server_->Get("/event-with-id", [](const Request &, Response &res) {
  11564. res.set_chunked_content_provider(
  11565. "text/event-stream", [](size_t offset, DataSink &sink) {
  11566. if (offset == 0) {
  11567. std::string event = "id: evt-123\ndata: test\n\n";
  11568. sink.write(event.data(), event.size());
  11569. }
  11570. return false;
  11571. });
  11572. });
  11573. Client client("localhost", get_port());
  11574. sse::SSEClient sse(client, "/event-with-id");
  11575. std::atomic<bool> id_received{false};
  11576. sse.on_message([&](const sse::SSEMessage &msg) {
  11577. if (!msg.id.empty()) { id_received.store(true); }
  11578. });
  11579. sse.set_reconnect_interval(100);
  11580. sse.set_max_reconnect_attempts(1);
  11581. sse.start_async();
  11582. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11583. sse.stop();
  11584. EXPECT_TRUE(id_received.load());
  11585. EXPECT_EQ(sse.last_event_id(), "evt-123");
  11586. }
  11587. // Test: Manual stop
  11588. TEST_F(SSEIntegrationTest, ManualStop) {
  11589. // Endpoint that sends one event and stays open briefly
  11590. std::atomic<bool> handler_running{true};
  11591. server_->Get("/stay-open", [&handler_running](const Request &,
  11592. Response &res) {
  11593. res.set_chunked_content_provider(
  11594. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  11595. if (offset == 0) {
  11596. std::string event = "data: connected\n\n";
  11597. sink.write(event.data(), event.size());
  11598. }
  11599. // Keep connection open while handler_running is true
  11600. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  11601. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11602. }
  11603. return false;
  11604. });
  11605. });
  11606. Client client("localhost", get_port());
  11607. sse::SSEClient sse(client, "/stay-open");
  11608. std::atomic<bool> connected{false};
  11609. sse.on_open([&connected]() { connected.store(true); });
  11610. sse.set_reconnect_interval(100);
  11611. sse.set_max_reconnect_attempts(1);
  11612. sse.start_async();
  11613. // Wait for connection to establish
  11614. for (int i = 0; i < 20 && !connected.load(); ++i) {
  11615. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  11616. }
  11617. EXPECT_TRUE(connected.load());
  11618. EXPECT_TRUE(sse.is_connected());
  11619. // Signal handler to stop
  11620. handler_running.store(false);
  11621. // Stop SSE client
  11622. sse.stop();
  11623. EXPECT_FALSE(sse.is_connected());
  11624. }
  11625. // Test: SSEClient with custom headers
  11626. TEST_F(SSEIntegrationTest, CustomHeaders) {
  11627. // Setup a server endpoint that checks for custom header
  11628. std::atomic<bool> header_received{false};
  11629. server_->Get("/header-check", [&](const Request &req, Response &res) {
  11630. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  11631. header_received.store(true);
  11632. }
  11633. res.set_chunked_content_provider("text/event-stream",
  11634. [](size_t, DataSink &) { return false; });
  11635. });
  11636. Client client("localhost", get_port());
  11637. Headers headers = {{"X-Custom-Header", "custom-value"}};
  11638. sse::SSEClient sse(client, "/header-check", headers);
  11639. sse.set_max_reconnect_attempts(1);
  11640. sse.start_async();
  11641. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11642. sse.stop();
  11643. EXPECT_TRUE(header_received.load());
  11644. }
  11645. // Test: Reconnect interval configuration
  11646. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  11647. Client client("localhost", get_port());
  11648. sse::SSEClient sse(client, "/events");
  11649. auto &result = sse.set_reconnect_interval(500);
  11650. // Builder pattern should return reference to self
  11651. EXPECT_EQ(&result, &sse);
  11652. }
  11653. // Test: Max reconnect attempts
  11654. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  11655. // Connect to non-existent port to force reconnects
  11656. Client client("localhost", 59998);
  11657. sse::SSEClient sse(client, "/events");
  11658. std::atomic<int> error_count{0};
  11659. sse.on_error([&](Error) { error_count.fetch_add(1); });
  11660. sse.set_reconnect_interval(50);
  11661. sse.set_max_reconnect_attempts(2);
  11662. auto start = std::chrono::steady_clock::now();
  11663. sse.start(); // Blocking call
  11664. auto end = std::chrono::steady_clock::now();
  11665. // Should have stopped after 2 failed attempts
  11666. EXPECT_GE(error_count.load(), 2);
  11667. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  11668. auto duration =
  11669. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  11670. #ifdef _WIN32
  11671. // Windows is much slower for socket connection failures
  11672. EXPECT_LT(duration.count(), 7000);
  11673. #else
  11674. EXPECT_LT(duration.count(), 1000);
  11675. #endif
  11676. }
  11677. // Test: Multi-line data in integration
  11678. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  11679. // Endpoint with multi-line data
  11680. server_->Get("/multiline-data", [](const Request &, Response &res) {
  11681. res.set_chunked_content_provider(
  11682. "text/event-stream", [](size_t offset, DataSink &sink) {
  11683. if (offset == 0) {
  11684. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  11685. sink.write(event.data(), event.size());
  11686. }
  11687. return false;
  11688. });
  11689. });
  11690. Client client("localhost", get_port());
  11691. sse::SSEClient sse(client, "/multiline-data");
  11692. std::string received_data;
  11693. std::mutex data_mutex;
  11694. sse.on_message([&](const sse::SSEMessage &msg) {
  11695. std::lock_guard<std::mutex> lock(data_mutex);
  11696. received_data = msg.data;
  11697. });
  11698. sse.set_reconnect_interval(100);
  11699. sse.set_max_reconnect_attempts(1);
  11700. sse.start_async();
  11701. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11702. sse.stop();
  11703. std::lock_guard<std::mutex> lock(data_mutex);
  11704. EXPECT_EQ(received_data, "line1\nline2\nline3");
  11705. }
  11706. // Test: Auto-reconnect after server disconnection
  11707. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  11708. std::atomic<int> connection_count{0};
  11709. std::atomic<int> message_count{0};
  11710. // Endpoint that sends one event and closes, forcing reconnect
  11711. server_->Get("/reconnect-test",
  11712. [&connection_count](const Request &, Response &res) {
  11713. connection_count.fetch_add(1);
  11714. res.set_chunked_content_provider(
  11715. "text/event-stream", [](size_t offset, DataSink &sink) {
  11716. if (offset == 0) {
  11717. std::string event = "data: hello\n\n";
  11718. sink.write(event.data(), event.size());
  11719. }
  11720. return false; // Close connection after sending
  11721. });
  11722. });
  11723. Client client("localhost", get_port());
  11724. sse::SSEClient sse(client, "/reconnect-test");
  11725. sse.on_message([&message_count](const sse::SSEMessage &) {
  11726. message_count.fetch_add(1);
  11727. });
  11728. sse.set_reconnect_interval(100);
  11729. sse.set_max_reconnect_attempts(3);
  11730. sse.start_async();
  11731. // Wait long enough for multiple reconnects
  11732. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  11733. sse.stop();
  11734. // Should have connected multiple times (initial + reconnects)
  11735. EXPECT_GE(connection_count.load(), 2);
  11736. // Should have received messages from multiple connections
  11737. EXPECT_GE(message_count.load(), 2);
  11738. }
  11739. // Test: Last-Event-ID sent on reconnect
  11740. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  11741. std::atomic<int> connection_count{0};
  11742. std::vector<std::string> received_last_event_ids;
  11743. std::mutex id_mutex;
  11744. // Endpoint that checks Last-Event-ID header and sends event with ID
  11745. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  11746. int conn = connection_count.fetch_add(1);
  11747. // Capture the Last-Event-ID header from each connection
  11748. {
  11749. std::lock_guard<std::mutex> lock(id_mutex);
  11750. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  11751. }
  11752. res.set_chunked_content_provider(
  11753. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  11754. if (offset == 0) {
  11755. std::string event =
  11756. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  11757. sink.write(event.data(), event.size());
  11758. }
  11759. return false;
  11760. });
  11761. });
  11762. Client client("localhost", get_port());
  11763. sse::SSEClient sse(client, "/reconnect-with-id");
  11764. sse.set_reconnect_interval(100);
  11765. sse.set_max_reconnect_attempts(3);
  11766. sse.start_async();
  11767. // Wait for at least 2 connections
  11768. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11769. sse.stop();
  11770. // Verify behavior
  11771. std::lock_guard<std::mutex> lock(id_mutex);
  11772. EXPECT_GE(received_last_event_ids.size(), 2u);
  11773. // First connection should have no Last-Event-ID
  11774. if (!received_last_event_ids.empty()) {
  11775. EXPECT_EQ(received_last_event_ids[0], "");
  11776. }
  11777. // Second connection should have Last-Event-ID from first connection
  11778. if (received_last_event_ids.size() >= 2) {
  11779. EXPECT_EQ(received_last_event_ids[1], "event-0");
  11780. }
  11781. }
  11782. TEST(Issue2318Test, EmptyHostString) {
  11783. {
  11784. httplib::Client cli_empty("", PORT);
  11785. auto res = cli_empty.Get("/");
  11786. ASSERT_FALSE(res);
  11787. EXPECT_EQ(httplib::Error::Connection, res.error());
  11788. }
  11789. {
  11790. httplib::Client cli(" ", PORT);
  11791. auto res = cli.Get("/");
  11792. ASSERT_FALSE(res);
  11793. EXPECT_EQ(httplib::Error::Connection, res.error());
  11794. }
  11795. }
  11796. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11797. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  11798. Server svr;
  11799. // Set a small payload limit (1KB)
  11800. svr.set_payload_max_length(1024);
  11801. svr.Post("/test", [&](const Request &req, Response &res) {
  11802. res.set_content("Body size: " + std::to_string(req.body.size()),
  11803. "text/plain");
  11804. });
  11805. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11806. auto se = detail::scope_exit([&] {
  11807. svr.stop();
  11808. listen_thread.join();
  11809. });
  11810. svr.wait_until_ready();
  11811. // Create data that compresses well but exceeds limit when decompressed
  11812. // 8KB of repeated null bytes compresses to a very small size
  11813. std::string original_data(8 * 1024, '\0');
  11814. // Compress the data using gzip
  11815. std::string compressed_data;
  11816. detail::gzip_compressor compressor;
  11817. compressor.compress(original_data.data(), original_data.size(), true,
  11818. [&](const char *data, size_t size) {
  11819. compressed_data.append(data, size);
  11820. return true;
  11821. });
  11822. // Verify compression worked (compressed should be much smaller)
  11823. ASSERT_LT(compressed_data.size(), original_data.size());
  11824. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  11825. // Send compressed data with Content-Encoding: gzip
  11826. Client cli(HOST, PORT);
  11827. Headers headers = {{"Content-Encoding", "gzip"}};
  11828. auto res =
  11829. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  11830. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  11831. ASSERT_TRUE(res);
  11832. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  11833. }
  11834. #endif