test.cc 232 KB

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