test.cc 231 KB

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