test.cc 234 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798
  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("/file_content",
  1882. [&](const Request & /*req*/, Response &res) {
  1883. res.set_file_content("./www/dir/test.html");
  1884. })
  1885. .Get("/file_content_with_content_type",
  1886. [&](const Request & /*req*/, Response &res) {
  1887. res.set_file_content("./www/file", "text/plain");
  1888. })
  1889. .Get("/invalid_file_content",
  1890. [&](const Request & /*req*/, Response &res) {
  1891. res.set_file_content("./www/dir/invalid_file_path");
  1892. })
  1893. .Get("/http_response_splitting",
  1894. [&](const Request & /*req*/, Response &res) {
  1895. res.set_header("a", "1\r\nSet-Cookie: a=1");
  1896. EXPECT_EQ(0U, res.headers.size());
  1897. EXPECT_FALSE(res.has_header("a"));
  1898. res.set_header("a", "1\nSet-Cookie: a=1");
  1899. EXPECT_EQ(0U, res.headers.size());
  1900. EXPECT_FALSE(res.has_header("a"));
  1901. res.set_header("a", "1\rSet-Cookie: a=1");
  1902. EXPECT_EQ(0U, res.headers.size());
  1903. EXPECT_FALSE(res.has_header("a"));
  1904. res.set_header("a\r\nb", "0");
  1905. EXPECT_EQ(0U, res.headers.size());
  1906. EXPECT_FALSE(res.has_header("a"));
  1907. res.set_header("a\rb", "0");
  1908. EXPECT_EQ(0U, res.headers.size());
  1909. EXPECT_FALSE(res.has_header("a"));
  1910. res.set_header("a\nb", "0");
  1911. EXPECT_EQ(0U, res.headers.size());
  1912. EXPECT_FALSE(res.has_header("a"));
  1913. res.set_redirect("1\r\nSet-Cookie: a=1");
  1914. EXPECT_EQ(0U, res.headers.size());
  1915. EXPECT_FALSE(res.has_header("Location"));
  1916. })
  1917. .Get("/slow",
  1918. [&](const Request & /*req*/, Response &res) {
  1919. std::this_thread::sleep_for(std::chrono::seconds(2));
  1920. res.set_content("slow", "text/plain");
  1921. })
  1922. #if 0
  1923. .Post("/slowpost",
  1924. [&](const Request & /*req*/, Response &res) {
  1925. std::this_thread::sleep_for(std::chrono::seconds(2));
  1926. res.set_content("slow", "text/plain");
  1927. })
  1928. #endif
  1929. .Get("/remote_addr",
  1930. [&](const Request &req, Response &res) {
  1931. auto remote_addr = req.headers.find("REMOTE_ADDR")->second;
  1932. EXPECT_TRUE(req.has_header("REMOTE_PORT"));
  1933. EXPECT_EQ(req.remote_addr, req.get_header_value("REMOTE_ADDR"));
  1934. EXPECT_EQ(req.remote_port,
  1935. std::stoi(req.get_header_value("REMOTE_PORT")));
  1936. res.set_content(remote_addr.c_str(), "text/plain");
  1937. })
  1938. .Get("/local_addr",
  1939. [&](const Request &req, Response &res) {
  1940. EXPECT_TRUE(req.has_header("LOCAL_PORT"));
  1941. EXPECT_TRUE(req.has_header("LOCAL_ADDR"));
  1942. auto local_addr = req.get_header_value("LOCAL_ADDR");
  1943. auto local_port = req.get_header_value("LOCAL_PORT");
  1944. EXPECT_EQ(req.local_addr, local_addr);
  1945. EXPECT_EQ(req.local_port, std::stoi(local_port));
  1946. res.set_content(local_addr.append(":").append(local_port),
  1947. "text/plain");
  1948. })
  1949. .Get("/endwith%",
  1950. [&](const Request & /*req*/, Response &res) {
  1951. res.set_content("Hello World!", "text/plain");
  1952. })
  1953. .Get("/a\\+\\+b",
  1954. [&](const Request &req, Response &res) {
  1955. ASSERT_TRUE(req.has_param("a +b"));
  1956. auto val = req.get_param_value("a +b");
  1957. res.set_content(val, "text/plain");
  1958. })
  1959. .Get("/", [&](const Request & /*req*/,
  1960. Response &res) { res.set_redirect("/hi"); })
  1961. .Post("/1",
  1962. [](const Request & /*req*/, Response &res) {
  1963. res.set_redirect("/2", StatusCode::SeeOther_303);
  1964. })
  1965. .Get("/2",
  1966. [](const Request & /*req*/, Response &res) {
  1967. res.set_content("redirected.", "text/plain");
  1968. res.status = StatusCode::OK_200;
  1969. })
  1970. .Post("/person",
  1971. [&](const Request &req, Response &res) {
  1972. if (req.has_param("name") && req.has_param("note")) {
  1973. persons_[req.get_param_value("name")] =
  1974. req.get_param_value("note");
  1975. } else {
  1976. res.status = StatusCode::BadRequest_400;
  1977. }
  1978. })
  1979. .Put("/person",
  1980. [&](const Request &req, Response &res) {
  1981. if (req.has_param("name") && req.has_param("note")) {
  1982. persons_[req.get_param_value("name")] =
  1983. req.get_param_value("note");
  1984. } else {
  1985. res.status = StatusCode::BadRequest_400;
  1986. }
  1987. })
  1988. .Get("/person/(.*)",
  1989. [&](const Request &req, Response &res) {
  1990. string name = req.matches[1];
  1991. if (persons_.find(name) != persons_.end()) {
  1992. auto note = persons_[name];
  1993. res.set_content(note, "text/plain");
  1994. } else {
  1995. res.status = StatusCode::NotFound_404;
  1996. }
  1997. })
  1998. .Post("/x-www-form-urlencoded-json",
  1999. [&](const Request &req, Response &res) {
  2000. auto json = req.get_param_value("json");
  2001. ASSERT_EQ(JSON_DATA, json);
  2002. res.set_content(json, "appliation/json");
  2003. res.status = StatusCode::OK_200;
  2004. })
  2005. .Get("/streamed-chunked",
  2006. [&](const Request & /*req*/, Response &res) {
  2007. res.set_chunked_content_provider(
  2008. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  2009. sink.os << "123";
  2010. sink.os << "456";
  2011. sink.os << "789";
  2012. sink.done();
  2013. return true;
  2014. });
  2015. })
  2016. .Get("/streamed-chunked2",
  2017. [&](const Request & /*req*/, Response &res) {
  2018. auto i = new int(0);
  2019. res.set_chunked_content_provider(
  2020. "text/plain",
  2021. [i](size_t /*offset*/, DataSink &sink) {
  2022. switch (*i) {
  2023. case 0: sink.os << "123"; break;
  2024. case 1: sink.os << "456"; break;
  2025. case 2: sink.os << "789"; break;
  2026. case 3: sink.done(); break;
  2027. }
  2028. (*i)++;
  2029. return true;
  2030. },
  2031. [i](bool success) {
  2032. EXPECT_TRUE(success);
  2033. delete i;
  2034. });
  2035. })
  2036. .Get("/streamed-chunked-with-trailer",
  2037. [&](const Request & /*req*/, Response &res) {
  2038. auto i = new int(0);
  2039. res.set_header("Trailer", "Dummy1, Dummy2");
  2040. res.set_chunked_content_provider(
  2041. "text/plain",
  2042. [i](size_t /*offset*/, DataSink &sink) {
  2043. switch (*i) {
  2044. case 0: sink.os << "123"; break;
  2045. case 1: sink.os << "456"; break;
  2046. case 2: sink.os << "789"; break;
  2047. case 3: {
  2048. sink.done_with_trailer(
  2049. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  2050. } break;
  2051. }
  2052. (*i)++;
  2053. return true;
  2054. },
  2055. [i](bool success) {
  2056. EXPECT_TRUE(success);
  2057. delete i;
  2058. });
  2059. })
  2060. .Get("/streamed",
  2061. [&](const Request & /*req*/, Response &res) {
  2062. res.set_content_provider(
  2063. 6, "text/plain",
  2064. [](size_t offset, size_t /*length*/, DataSink &sink) {
  2065. sink.os << (offset < 3 ? "a" : "b");
  2066. return true;
  2067. });
  2068. })
  2069. .Get("/streamed-with-range",
  2070. [&](const Request &req, Response &res) {
  2071. auto data = new std::string("abcdefg");
  2072. res.set_content_provider(
  2073. data->size(), "text/plain",
  2074. [data](size_t offset, size_t length, DataSink &sink) {
  2075. size_t DATA_CHUNK_SIZE = 4;
  2076. const auto &d = *data;
  2077. auto out_len =
  2078. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  2079. auto ret =
  2080. sink.write(&d[static_cast<size_t>(offset)], out_len);
  2081. EXPECT_TRUE(ret);
  2082. return true;
  2083. },
  2084. [data, &req](bool success) {
  2085. EXPECT_EQ(success, !req.has_param("error"));
  2086. delete data;
  2087. });
  2088. })
  2089. .Get("/streamed-cancel",
  2090. [&](const Request & /*req*/, Response &res) {
  2091. res.set_content_provider(
  2092. size_t(-1), "text/plain",
  2093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2094. sink.os << "data_chunk";
  2095. return true;
  2096. });
  2097. })
  2098. .Get("/regex-with-delimiter",
  2099. [&](const Request &req, Response & /*res*/) {
  2100. ASSERT_TRUE(req.has_param("key"));
  2101. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  2102. })
  2103. .Get("/with-range",
  2104. [&](const Request & /*req*/, Response &res) {
  2105. res.set_content("abcdefg", "text/plain");
  2106. })
  2107. .Get("/with-range-customized-response",
  2108. [&](const Request & /*req*/, Response &res) {
  2109. res.status = StatusCode::BadRequest_400;
  2110. res.set_content(JSON_DATA, "application/json");
  2111. })
  2112. .Post("/chunked",
  2113. [&](const Request &req, Response & /*res*/) {
  2114. EXPECT_EQ(req.body, "dechunked post body");
  2115. })
  2116. .Post("/large-chunked",
  2117. [&](const Request &req, Response & /*res*/) {
  2118. std::string expected(6 * 30 * 1024u, 'a');
  2119. EXPECT_EQ(req.body, expected);
  2120. })
  2121. .Post("/multipart",
  2122. [&](const Request &req, Response & /*res*/) {
  2123. EXPECT_EQ(6u, req.files.size());
  2124. ASSERT_TRUE(!req.has_file("???"));
  2125. ASSERT_TRUE(req.body.empty());
  2126. {
  2127. const auto &file = req.get_file_value("text1");
  2128. EXPECT_TRUE(file.filename.empty());
  2129. EXPECT_EQ("text default", file.content);
  2130. }
  2131. {
  2132. const auto &file = req.get_file_value("text2");
  2133. EXPECT_TRUE(file.filename.empty());
  2134. EXPECT_EQ("aωb", file.content);
  2135. }
  2136. {
  2137. const auto &file = req.get_file_value("file1");
  2138. EXPECT_EQ("hello.txt", file.filename);
  2139. EXPECT_EQ("text/plain", file.content_type);
  2140. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2141. }
  2142. {
  2143. const auto &file = req.get_file_value("file3");
  2144. EXPECT_TRUE(file.filename.empty());
  2145. EXPECT_EQ("application/octet-stream", file.content_type);
  2146. EXPECT_EQ(0u, file.content.size());
  2147. }
  2148. {
  2149. const auto &file = req.get_file_value("file4");
  2150. EXPECT_TRUE(file.filename.empty());
  2151. EXPECT_EQ(0u, file.content.size());
  2152. EXPECT_EQ("application/json tmp-string", file.content_type);
  2153. }
  2154. })
  2155. .Post("/multipart/multi_file_values",
  2156. [&](const Request &req, Response & /*res*/) {
  2157. EXPECT_EQ(5u, req.files.size());
  2158. ASSERT_TRUE(!req.has_file("???"));
  2159. ASSERT_TRUE(req.body.empty());
  2160. {
  2161. const auto &text_value = req.get_file_values("text");
  2162. EXPECT_EQ(1u, text_value.size());
  2163. auto &text = text_value[0];
  2164. EXPECT_TRUE(text.filename.empty());
  2165. EXPECT_EQ("default text", text.content);
  2166. }
  2167. {
  2168. const auto &text1_values = req.get_file_values("multi_text1");
  2169. EXPECT_EQ(2u, text1_values.size());
  2170. EXPECT_EQ("aaaaa", text1_values[0].content);
  2171. EXPECT_EQ("bbbbb", text1_values[1].content);
  2172. }
  2173. {
  2174. const auto &file1_values = req.get_file_values("multi_file1");
  2175. EXPECT_EQ(2u, file1_values.size());
  2176. auto file1 = file1_values[0];
  2177. EXPECT_EQ(file1.filename, "hello.txt");
  2178. EXPECT_EQ(file1.content_type, "text/plain");
  2179. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  2180. auto file2 = file1_values[1];
  2181. EXPECT_EQ(file2.filename, "world.json");
  2182. EXPECT_EQ(file2.content_type, "application/json");
  2183. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  2184. }
  2185. })
  2186. .Post("/empty",
  2187. [&](const Request &req, Response &res) {
  2188. EXPECT_EQ(req.body, "");
  2189. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  2190. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2191. res.set_content("empty", "text/plain");
  2192. })
  2193. .Post("/empty-no-content-type",
  2194. [&](const Request &req, Response &res) {
  2195. EXPECT_EQ(req.body, "");
  2196. EXPECT_FALSE(req.has_header("Content-Type"));
  2197. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2198. res.set_content("empty-no-content-type", "text/plain");
  2199. })
  2200. .Post("/path-only",
  2201. [&](const Request &req, Response &res) {
  2202. EXPECT_EQ(req.body, "");
  2203. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2204. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2205. res.set_content("path-only", "text/plain");
  2206. })
  2207. .Post("/path-headers-only",
  2208. [&](const Request &req, Response &res) {
  2209. EXPECT_EQ(req.body, "");
  2210. EXPECT_EQ("", req.get_header_value("Content-Type"));
  2211. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2212. EXPECT_EQ("world", req.get_header_value("hello"));
  2213. EXPECT_EQ("world2", req.get_header_value("hello2"));
  2214. res.set_content("path-headers-only", "text/plain");
  2215. })
  2216. .Post("/post-large",
  2217. [&](const Request &req, Response &res) {
  2218. EXPECT_EQ(req.body, LARGE_DATA);
  2219. res.set_content(req.body, "text/plain");
  2220. })
  2221. .Put("/empty-no-content-type",
  2222. [&](const Request &req, Response &res) {
  2223. EXPECT_EQ(req.body, "");
  2224. EXPECT_FALSE(req.has_header("Content-Type"));
  2225. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  2226. res.set_content("empty-no-content-type", "text/plain");
  2227. })
  2228. .Put("/put",
  2229. [&](const Request &req, Response &res) {
  2230. EXPECT_EQ(req.body, "PUT");
  2231. res.set_content(req.body, "text/plain");
  2232. })
  2233. .Put("/put-large",
  2234. [&](const Request &req, Response &res) {
  2235. EXPECT_EQ(req.body, LARGE_DATA);
  2236. res.set_content(req.body, "text/plain");
  2237. })
  2238. .Patch("/patch",
  2239. [&](const Request &req, Response &res) {
  2240. EXPECT_EQ(req.body, "PATCH");
  2241. res.set_content(req.body, "text/plain");
  2242. })
  2243. .Delete("/delete",
  2244. [&](const Request & /*req*/, Response &res) {
  2245. res.set_content("DELETE", "text/plain");
  2246. })
  2247. .Delete("/delete-body",
  2248. [&](const Request &req, Response &res) {
  2249. EXPECT_EQ(req.body, "content");
  2250. res.set_content(req.body, "text/plain");
  2251. })
  2252. .Options(R"(\*)",
  2253. [&](const Request & /*req*/, Response &res) {
  2254. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  2255. })
  2256. .Get("/request-target",
  2257. [&](const Request &req, Response & /*res*/) {
  2258. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  2259. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  2260. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  2261. })
  2262. .Get("/long-query-value",
  2263. [&](const Request &req, Response & /*res*/) {
  2264. EXPECT_EQ(LONG_QUERY_URL, req.target);
  2265. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  2266. })
  2267. .Get("/array-param",
  2268. [&](const Request &req, Response & /*res*/) {
  2269. EXPECT_EQ(3u, req.get_param_value_count("array"));
  2270. EXPECT_EQ("value1", req.get_param_value("array", 0));
  2271. EXPECT_EQ("value2", req.get_param_value("array", 1));
  2272. EXPECT_EQ("value3", req.get_param_value("array", 2));
  2273. })
  2274. .Post("/validate-no-multiple-headers",
  2275. [&](const Request &req, Response & /*res*/) {
  2276. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  2277. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  2278. })
  2279. .Post("/content_receiver",
  2280. [&](const Request &req, Response &res,
  2281. const ContentReader &content_reader) {
  2282. if (req.is_multipart_form_data()) {
  2283. MultipartFormDataItems files;
  2284. content_reader(
  2285. [&](const MultipartFormData &file) {
  2286. files.push_back(file);
  2287. return true;
  2288. },
  2289. [&](const char *data, size_t data_length) {
  2290. files.back().content.append(data, data_length);
  2291. return true;
  2292. });
  2293. EXPECT_EQ(5u, files.size());
  2294. {
  2295. const auto &file = get_file_value(files, "text1");
  2296. EXPECT_TRUE(file.filename.empty());
  2297. EXPECT_EQ("text default", file.content);
  2298. }
  2299. {
  2300. const auto &file = get_file_value(files, "text2");
  2301. EXPECT_TRUE(file.filename.empty());
  2302. EXPECT_EQ("aωb", file.content);
  2303. }
  2304. {
  2305. const auto &file = get_file_value(files, "file1");
  2306. EXPECT_EQ("hello.txt", file.filename);
  2307. EXPECT_EQ("text/plain", file.content_type);
  2308. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  2309. }
  2310. {
  2311. const auto &file = get_file_value(files, "file3");
  2312. EXPECT_TRUE(file.filename.empty());
  2313. EXPECT_EQ("application/octet-stream", file.content_type);
  2314. EXPECT_EQ(0u, file.content.size());
  2315. }
  2316. } else {
  2317. std::string body;
  2318. content_reader([&](const char *data, size_t data_length) {
  2319. EXPECT_EQ(7U, 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. })
  2327. .Put("/content_receiver",
  2328. [&](const Request & /*req*/, Response &res,
  2329. const ContentReader &content_reader) {
  2330. std::string body;
  2331. content_reader([&](const char *data, size_t data_length) {
  2332. body.append(data, data_length);
  2333. return true;
  2334. });
  2335. EXPECT_EQ(body, "content");
  2336. res.set_content(body, "text/plain");
  2337. })
  2338. .Patch("/content_receiver",
  2339. [&](const Request & /*req*/, Response &res,
  2340. const ContentReader &content_reader) {
  2341. std::string body;
  2342. content_reader([&](const char *data, size_t data_length) {
  2343. body.append(data, data_length);
  2344. return true;
  2345. });
  2346. EXPECT_EQ(body, "content");
  2347. res.set_content(body, "text/plain");
  2348. })
  2349. .Post("/query-string-and-body",
  2350. [&](const Request &req, Response & /*res*/) {
  2351. ASSERT_TRUE(req.has_param("key"));
  2352. EXPECT_EQ(req.get_param_value("key"), "value");
  2353. EXPECT_EQ(req.body, "content");
  2354. })
  2355. .Get("/last-request",
  2356. [&](const Request &req, Response & /*res*/) {
  2357. EXPECT_EQ("close", req.get_header_value("Connection"));
  2358. })
  2359. .Get(R"(/redirect/(\d+))",
  2360. [&](const Request &req, Response &res) {
  2361. auto num = std::stoi(req.matches[1]) + 1;
  2362. std::string url = "/redirect/" + std::to_string(num);
  2363. res.set_redirect(url);
  2364. })
  2365. .Post("/binary",
  2366. [&](const Request &req, Response &res) {
  2367. EXPECT_EQ(4U, req.body.size());
  2368. EXPECT_EQ("application/octet-stream",
  2369. req.get_header_value("Content-Type"));
  2370. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2371. res.set_content(req.body, "application/octet-stream");
  2372. })
  2373. .Put("/binary",
  2374. [&](const Request &req, Response &res) {
  2375. EXPECT_EQ(4U, req.body.size());
  2376. EXPECT_EQ("application/octet-stream",
  2377. req.get_header_value("Content-Type"));
  2378. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2379. res.set_content(req.body, "application/octet-stream");
  2380. })
  2381. .Patch("/binary",
  2382. [&](const Request &req, Response &res) {
  2383. EXPECT_EQ(4U, req.body.size());
  2384. EXPECT_EQ("application/octet-stream",
  2385. req.get_header_value("Content-Type"));
  2386. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2387. res.set_content(req.body, "application/octet-stream");
  2388. })
  2389. .Delete("/binary",
  2390. [&](const Request &req, Response &res) {
  2391. EXPECT_EQ(4U, req.body.size());
  2392. EXPECT_EQ("application/octet-stream",
  2393. req.get_header_value("Content-Type"));
  2394. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  2395. res.set_content(req.body, "application/octet-stream");
  2396. })
  2397. .Get("/issue1772",
  2398. [&](const Request & /*req*/, Response &res) {
  2399. res.status = 401;
  2400. res.set_header("WWW-Authenticate", "Basic realm=123456");
  2401. })
  2402. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT)
  2403. .Get("/compress",
  2404. [&](const Request & /*req*/, Response &res) {
  2405. res.set_content(
  2406. "12345678901234567890123456789012345678901234567890123456789"
  2407. "01234567890123456789012345678901234567890",
  2408. "text/plain");
  2409. })
  2410. .Get("/nocompress",
  2411. [&](const Request & /*req*/, Response &res) {
  2412. res.set_content(
  2413. "12345678901234567890123456789012345678901234567890123456789"
  2414. "01234567890123456789012345678901234567890",
  2415. "application/octet-stream");
  2416. })
  2417. .Post("/compress-multipart",
  2418. [&](const Request &req, Response & /*res*/) {
  2419. EXPECT_EQ(2u, req.files.size());
  2420. ASSERT_TRUE(!req.has_file("???"));
  2421. {
  2422. const auto &file = req.get_file_value("key1");
  2423. EXPECT_TRUE(file.filename.empty());
  2424. EXPECT_EQ("test", file.content);
  2425. }
  2426. {
  2427. const auto &file = req.get_file_value("key2");
  2428. EXPECT_TRUE(file.filename.empty());
  2429. EXPECT_EQ("--abcdefg123", file.content);
  2430. }
  2431. })
  2432. #endif
  2433. ;
  2434. persons_["john"] = "programmer";
  2435. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2436. svr_.wait_until_ready();
  2437. }
  2438. virtual void TearDown() {
  2439. svr_.stop();
  2440. if (!request_threads_.empty()) {
  2441. std::this_thread::sleep_for(std::chrono::seconds(1));
  2442. for (auto &t : request_threads_) {
  2443. t.join();
  2444. }
  2445. }
  2446. t_.join();
  2447. }
  2448. map<string, string> persons_;
  2449. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2450. SSLClient cli_;
  2451. SSLServer svr_;
  2452. #else
  2453. Client cli_;
  2454. Server svr_;
  2455. #endif
  2456. thread t_;
  2457. std::vector<thread> request_threads_;
  2458. };
  2459. TEST_F(ServerTest, GetMethod200) {
  2460. auto res = cli_.Get("/hi");
  2461. ASSERT_TRUE(res);
  2462. EXPECT_EQ("HTTP/1.1", res->version);
  2463. EXPECT_EQ(StatusCode::OK_200, res->status);
  2464. EXPECT_EQ("OK", res->reason);
  2465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2466. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2467. EXPECT_EQ("Hello World!", res->body);
  2468. }
  2469. TEST_F(ServerTest, GetFileContent) {
  2470. auto res = cli_.Get("/file_content");
  2471. ASSERT_TRUE(res);
  2472. EXPECT_EQ(StatusCode::OK_200, res->status);
  2473. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2474. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  2475. EXPECT_EQ("test.html", res->body);
  2476. }
  2477. TEST_F(ServerTest, GetFileContentWithContentType) {
  2478. auto res = cli_.Get("/file_content_with_content_type");
  2479. ASSERT_TRUE(res);
  2480. EXPECT_EQ(StatusCode::OK_200, res->status);
  2481. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2482. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  2483. EXPECT_EQ("file\n", res->body);
  2484. }
  2485. TEST_F(ServerTest, GetInvalidFileContent) {
  2486. auto res = cli_.Get("/invalid_file_content");
  2487. ASSERT_TRUE(res);
  2488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2489. }
  2490. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  2491. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  2492. ASSERT_TRUE(res);
  2493. EXPECT_EQ("HTTP/1.1", res->version);
  2494. EXPECT_EQ(StatusCode::OK_200, res->status);
  2495. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2496. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  2497. EXPECT_EQ("Hello World!", res->body);
  2498. }
  2499. TEST_F(ServerTest, GetMethod302) {
  2500. auto res = cli_.Get("/");
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(StatusCode::Found_302, res->status);
  2503. EXPECT_EQ("/hi", res->get_header_value("Location"));
  2504. }
  2505. TEST_F(ServerTest, GetMethod302Redirect) {
  2506. cli_.set_follow_location(true);
  2507. auto res = cli_.Get("/");
  2508. ASSERT_TRUE(res);
  2509. EXPECT_EQ(StatusCode::OK_200, res->status);
  2510. EXPECT_EQ("Hello World!", res->body);
  2511. EXPECT_EQ("/hi", res->location);
  2512. }
  2513. TEST_F(ServerTest, GetMethod404) {
  2514. auto res = cli_.Get("/invalid");
  2515. ASSERT_TRUE(res);
  2516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2517. }
  2518. TEST_F(ServerTest, HeadMethod200) {
  2519. auto res = cli_.Head("/hi");
  2520. ASSERT_TRUE(res);
  2521. EXPECT_EQ(StatusCode::OK_200, res->status);
  2522. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2523. EXPECT_TRUE(res->body.empty());
  2524. }
  2525. TEST_F(ServerTest, HeadMethod200Static) {
  2526. auto res = cli_.Head("/mount/dir/index.html");
  2527. ASSERT_TRUE(res);
  2528. EXPECT_EQ(StatusCode::OK_200, res->status);
  2529. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2530. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  2531. EXPECT_TRUE(res->body.empty());
  2532. }
  2533. TEST_F(ServerTest, HeadMethod404) {
  2534. auto res = cli_.Head("/invalid");
  2535. ASSERT_TRUE(res);
  2536. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2537. EXPECT_TRUE(res->body.empty());
  2538. }
  2539. TEST_F(ServerTest, GetMethodPersonJohn) {
  2540. auto res = cli_.Get("/person/john");
  2541. ASSERT_TRUE(res);
  2542. EXPECT_EQ(StatusCode::OK_200, res->status);
  2543. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2544. EXPECT_EQ("programmer", res->body);
  2545. }
  2546. TEST_F(ServerTest, PostMethod1) {
  2547. auto res = cli_.Get("/person/john1");
  2548. ASSERT_TRUE(res);
  2549. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2550. res = cli_.Post("/person", "name=john1&note=coder",
  2551. "application/x-www-form-urlencoded");
  2552. ASSERT_TRUE(res);
  2553. ASSERT_EQ(StatusCode::OK_200, res->status);
  2554. res = cli_.Get("/person/john1");
  2555. ASSERT_TRUE(res);
  2556. ASSERT_EQ(StatusCode::OK_200, res->status);
  2557. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2558. ASSERT_EQ("coder", res->body);
  2559. }
  2560. TEST_F(ServerTest, PostMethod2) {
  2561. auto res = cli_.Get("/person/john2");
  2562. ASSERT_TRUE(res);
  2563. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2564. Params params;
  2565. params.emplace("name", "john2");
  2566. params.emplace("note", "coder");
  2567. res = cli_.Post("/person", params);
  2568. ASSERT_TRUE(res);
  2569. ASSERT_EQ(StatusCode::OK_200, res->status);
  2570. res = cli_.Get("/person/john2");
  2571. ASSERT_TRUE(res);
  2572. ASSERT_EQ(StatusCode::OK_200, res->status);
  2573. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2574. ASSERT_EQ("coder", res->body);
  2575. }
  2576. TEST_F(ServerTest, PutMethod3) {
  2577. auto res = cli_.Get("/person/john3");
  2578. ASSERT_TRUE(res);
  2579. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  2580. Params params;
  2581. params.emplace("name", "john3");
  2582. params.emplace("note", "coder");
  2583. res = cli_.Put("/person", params);
  2584. ASSERT_TRUE(res);
  2585. ASSERT_EQ(StatusCode::OK_200, res->status);
  2586. res = cli_.Get("/person/john3");
  2587. ASSERT_TRUE(res);
  2588. ASSERT_EQ(StatusCode::OK_200, res->status);
  2589. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  2590. ASSERT_EQ("coder", res->body);
  2591. }
  2592. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  2593. Params params;
  2594. params.emplace("json", JSON_DATA);
  2595. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  2596. ASSERT_TRUE(res);
  2597. ASSERT_EQ(StatusCode::OK_200, res->status);
  2598. ASSERT_EQ(JSON_DATA, res->body);
  2599. }
  2600. TEST_F(ServerTest, PostEmptyContent) {
  2601. auto res = cli_.Post("/empty", "", "text/plain");
  2602. ASSERT_TRUE(res);
  2603. ASSERT_EQ(StatusCode::OK_200, res->status);
  2604. ASSERT_EQ("empty", res->body);
  2605. }
  2606. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  2607. auto res = cli_.Post("/empty-no-content-type");
  2608. ASSERT_TRUE(res);
  2609. ASSERT_EQ(StatusCode::OK_200, res->status);
  2610. ASSERT_EQ("empty-no-content-type", res->body);
  2611. }
  2612. TEST_F(ServerTest, PostPathOnly) {
  2613. auto res = cli_.Post("/path-only");
  2614. ASSERT_TRUE(res);
  2615. ASSERT_EQ(StatusCode::OK_200, res->status);
  2616. ASSERT_EQ("path-only", res->body);
  2617. }
  2618. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  2619. auto res = cli_.Post("/path-headers-only",
  2620. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  2621. ASSERT_TRUE(res);
  2622. ASSERT_EQ(StatusCode::OK_200, res->status);
  2623. ASSERT_EQ("path-headers-only", res->body);
  2624. }
  2625. TEST_F(ServerTest, PostLarge) {
  2626. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  2627. ASSERT_TRUE(res);
  2628. ASSERT_EQ(StatusCode::OK_200, res->status);
  2629. EXPECT_EQ(LARGE_DATA, res->body);
  2630. }
  2631. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  2632. auto res = cli_.Put("/empty-no-content-type");
  2633. ASSERT_TRUE(res);
  2634. ASSERT_EQ(StatusCode::OK_200, res->status);
  2635. ASSERT_EQ("empty-no-content-type", res->body);
  2636. }
  2637. TEST_F(ServerTest, GetMethodDir) {
  2638. auto res = cli_.Get("/dir/");
  2639. ASSERT_TRUE(res);
  2640. EXPECT_EQ(StatusCode::OK_200, res->status);
  2641. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2642. auto body = R"(<html>
  2643. <head>
  2644. </head>
  2645. <body>
  2646. <a href="/dir/test.html">Test</a>
  2647. <a href="/hi">hi</a>
  2648. </body>
  2649. </html>
  2650. )";
  2651. EXPECT_EQ(body, res->body);
  2652. }
  2653. TEST_F(ServerTest, GetMethodDirTest) {
  2654. auto res = cli_.Get("/dir/test.html");
  2655. ASSERT_TRUE(res);
  2656. EXPECT_EQ(StatusCode::OK_200, res->status);
  2657. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2658. EXPECT_EQ("test.html", res->body);
  2659. }
  2660. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  2661. auto res = cli_.Get("/dir/../dir/test.html");
  2662. ASSERT_TRUE(res);
  2663. EXPECT_EQ(StatusCode::OK_200, res->status);
  2664. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2665. EXPECT_EQ("test.html", res->body);
  2666. }
  2667. TEST_F(ServerTest, GetMethodInvalidPath) {
  2668. auto res = cli_.Get("/dir/../test.html");
  2669. ASSERT_TRUE(res);
  2670. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2671. }
  2672. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  2673. auto res = cli_.Get("/../www/dir/test.html");
  2674. ASSERT_TRUE(res);
  2675. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2676. }
  2677. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  2678. auto res = cli_.Get("/dir/../../www/dir/test.html");
  2679. ASSERT_TRUE(res);
  2680. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2681. }
  2682. TEST_F(ServerTest, GetMethodDirMountTest) {
  2683. auto res = cli_.Get("/mount/dir/test.html");
  2684. ASSERT_TRUE(res);
  2685. EXPECT_EQ(StatusCode::OK_200, res->status);
  2686. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2687. EXPECT_EQ("test.html", res->body);
  2688. }
  2689. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  2690. auto res = cli_.Get("/mount/dir/../dir/test.html");
  2691. ASSERT_TRUE(res);
  2692. EXPECT_EQ(StatusCode::OK_200, res->status);
  2693. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  2694. EXPECT_EQ("test.html", res->body);
  2695. }
  2696. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  2697. auto res = cli_.Get("/mount/dir/../test.html");
  2698. ASSERT_TRUE(res);
  2699. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2700. }
  2701. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  2702. auto res = cli_.Get("/mount/dir/test.html%00.js");
  2703. ASSERT_TRUE(res);
  2704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2705. }
  2706. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  2707. auto res = cli_.Get("/mount/../www2/dir/test.html");
  2708. ASSERT_TRUE(res);
  2709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2710. }
  2711. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  2712. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  2713. ASSERT_TRUE(res);
  2714. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2715. }
  2716. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  2717. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  2718. ASSERT_TRUE(res);
  2719. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2720. }
  2721. TEST_F(ServerTest, PostMethod303) {
  2722. auto res = cli_.Post("/1", "body", "text/plain");
  2723. ASSERT_TRUE(res);
  2724. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  2725. EXPECT_EQ("/2", res->get_header_value("Location"));
  2726. }
  2727. TEST_F(ServerTest, PostMethod303Redirect) {
  2728. cli_.set_follow_location(true);
  2729. auto res = cli_.Post("/1", "body", "text/plain");
  2730. ASSERT_TRUE(res);
  2731. EXPECT_EQ(StatusCode::OK_200, res->status);
  2732. EXPECT_EQ("redirected.", res->body);
  2733. EXPECT_EQ("/2", res->location);
  2734. }
  2735. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  2736. auto res = cli_.Get("/dir/test.abcde");
  2737. ASSERT_TRUE(res);
  2738. EXPECT_EQ(StatusCode::OK_200, res->status);
  2739. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2740. EXPECT_EQ("abcde", res->body);
  2741. }
  2742. TEST_F(ServerTest, StaticFileRange) {
  2743. auto res = cli_.Get("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2744. ASSERT_TRUE(res);
  2745. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2746. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2747. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2748. EXPECT_EQ(true, res->has_header("Content-Range"));
  2749. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2750. EXPECT_EQ(std::string("cd"), res->body);
  2751. }
  2752. TEST_F(ServerTest, StaticFileRanges) {
  2753. auto res =
  2754. cli_.Get("/dir/test.abcde", {{make_range_header({{1, 2}, {4, -1}})}});
  2755. ASSERT_TRUE(res);
  2756. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2757. EXPECT_TRUE(
  2758. res->get_header_value("Content-Type")
  2759. .find(
  2760. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  2761. 0);
  2762. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  2763. }
  2764. TEST_F(ServerTest, StaticFileRangeHead) {
  2765. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  2766. ASSERT_TRUE(res);
  2767. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2768. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  2769. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2770. EXPECT_EQ(true, res->has_header("Content-Range"));
  2771. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  2772. }
  2773. TEST_F(ServerTest, StaticFileRangeBigFile) {
  2774. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{-1, 5}})}});
  2775. ASSERT_TRUE(res);
  2776. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2777. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2778. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  2779. EXPECT_EQ(true, res->has_header("Content-Range"));
  2780. EXPECT_EQ("bytes 1048571-1048575/1048576",
  2781. res->get_header_value("Content-Range"));
  2782. EXPECT_EQ("LAST\n", res->body);
  2783. }
  2784. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  2785. auto res = cli_.Get("/dir/1MB.txt", {{make_range_header({{1, 4097}})}});
  2786. ASSERT_TRUE(res);
  2787. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2788. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2789. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  2790. EXPECT_EQ(true, res->has_header("Content-Range"));
  2791. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  2792. }
  2793. TEST_F(ServerTest, StaticFileBigFile) {
  2794. auto res = cli_.Get("/dir/1MB.txt");
  2795. ASSERT_TRUE(res);
  2796. EXPECT_EQ(StatusCode::OK_200, res->status);
  2797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2798. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  2799. }
  2800. TEST_F(ServerTest, InvalidBaseDirMount) {
  2801. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  2802. }
  2803. TEST_F(ServerTest, Binary) {
  2804. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  2805. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  2806. "application/octet-stream");
  2807. ASSERT_TRUE(res);
  2808. ASSERT_EQ(StatusCode::OK_200, res->status);
  2809. ASSERT_EQ(4U, res->body.size());
  2810. res = cli_.Put("/binary", binary.data(), binary.size(),
  2811. "application/octet-stream");
  2812. ASSERT_TRUE(res);
  2813. ASSERT_EQ(StatusCode::OK_200, res->status);
  2814. ASSERT_EQ(4U, res->body.size());
  2815. res = cli_.Patch("/binary", binary.data(), binary.size(),
  2816. "application/octet-stream");
  2817. ASSERT_TRUE(res);
  2818. ASSERT_EQ(StatusCode::OK_200, res->status);
  2819. ASSERT_EQ(4U, res->body.size());
  2820. res = cli_.Delete("/binary", binary.data(), binary.size(),
  2821. "application/octet-stream");
  2822. ASSERT_TRUE(res);
  2823. ASSERT_EQ(StatusCode::OK_200, res->status);
  2824. ASSERT_EQ(4U, res->body.size());
  2825. }
  2826. TEST_F(ServerTest, BinaryString) {
  2827. auto binary = std::string("\x00\x01\x02\x03", 4);
  2828. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  2829. ASSERT_TRUE(res);
  2830. ASSERT_EQ(StatusCode::OK_200, res->status);
  2831. ASSERT_EQ(4U, res->body.size());
  2832. res = cli_.Put("/binary", binary, "application/octet-stream");
  2833. ASSERT_TRUE(res);
  2834. ASSERT_EQ(StatusCode::OK_200, res->status);
  2835. ASSERT_EQ(4U, res->body.size());
  2836. res = cli_.Patch("/binary", binary, "application/octet-stream");
  2837. ASSERT_TRUE(res);
  2838. ASSERT_EQ(StatusCode::OK_200, res->status);
  2839. ASSERT_EQ(4U, res->body.size());
  2840. res = cli_.Delete("/binary", binary, "application/octet-stream");
  2841. ASSERT_TRUE(res);
  2842. ASSERT_EQ(StatusCode::OK_200, res->status);
  2843. ASSERT_EQ(4U, res->body.size());
  2844. }
  2845. TEST_F(ServerTest, EmptyRequest) {
  2846. auto res = cli_.Get("");
  2847. ASSERT_TRUE(!res);
  2848. EXPECT_EQ(Error::Connection, res.error());
  2849. }
  2850. TEST_F(ServerTest, LongRequest) {
  2851. std::string request;
  2852. for (size_t i = 0; i < 545; i++) {
  2853. request += "/TooLongRequest";
  2854. }
  2855. request += "OK";
  2856. auto res = cli_.Get(request.c_str());
  2857. ASSERT_TRUE(res);
  2858. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2859. }
  2860. TEST_F(ServerTest, TooLongRequest) {
  2861. std::string request;
  2862. for (size_t i = 0; i < 545; i++) {
  2863. request += "/TooLongRequest";
  2864. }
  2865. request += "_NG";
  2866. auto res = cli_.Get(request.c_str());
  2867. ASSERT_TRUE(res);
  2868. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2869. }
  2870. TEST_F(ServerTest, LongHeader) {
  2871. Request req;
  2872. req.method = "GET";
  2873. req.path = "/hi";
  2874. std::string host_and_port;
  2875. host_and_port += HOST;
  2876. host_and_port += ":";
  2877. host_and_port += std::to_string(PORT);
  2878. req.headers.emplace("Host", host_and_port.c_str());
  2879. req.headers.emplace("Accept", "*/*");
  2880. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2881. req.headers.emplace(
  2882. "Header-Name",
  2883. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2884. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2885. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2886. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2887. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2888. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2889. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2890. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2891. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2892. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2893. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2894. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2895. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2896. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2897. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2898. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2899. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2900. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2901. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2902. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2903. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2904. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2905. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2906. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2907. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2908. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2909. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2910. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2911. "@@@@@@@@@@@@@@@@");
  2912. auto res = std::make_shared<Response>();
  2913. auto error = Error::Success;
  2914. auto ret = cli_.send(req, *res, error);
  2915. ASSERT_TRUE(ret);
  2916. EXPECT_EQ(StatusCode::OK_200, res->status);
  2917. }
  2918. TEST_F(ServerTest, LongQueryValue) {
  2919. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  2920. ASSERT_TRUE(res);
  2921. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  2922. }
  2923. TEST_F(ServerTest, TooLongHeader) {
  2924. Request req;
  2925. req.method = "GET";
  2926. req.path = "/hi";
  2927. std::string host_and_port;
  2928. host_and_port += HOST;
  2929. host_and_port += ":";
  2930. host_and_port += std::to_string(PORT);
  2931. req.headers.emplace("Host", host_and_port.c_str());
  2932. req.headers.emplace("Accept", "*/*");
  2933. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2934. req.headers.emplace(
  2935. "Header-Name",
  2936. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2937. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2938. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2939. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2940. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2941. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2942. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2943. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2944. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2945. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2946. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2947. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2948. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2949. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2950. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2951. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2952. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2953. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2954. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2955. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2956. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2957. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2958. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2959. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2960. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2961. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2962. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2963. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  2964. "@@@@@@@@@@@@@@@@@");
  2965. auto res = std::make_shared<Response>();
  2966. auto error = Error::Success;
  2967. auto ret = cli_.send(req, *res, error);
  2968. ASSERT_TRUE(ret);
  2969. EXPECT_EQ(StatusCode::OK_200, res->status);
  2970. }
  2971. TEST_F(ServerTest, PercentEncoding) {
  2972. auto res = cli_.Get("/e%6edwith%");
  2973. ASSERT_TRUE(res);
  2974. EXPECT_EQ(StatusCode::OK_200, res->status);
  2975. }
  2976. TEST_F(ServerTest, PercentEncodingUnicode) {
  2977. auto res = cli_.Get("/e%u006edwith%");
  2978. ASSERT_TRUE(res);
  2979. EXPECT_EQ(StatusCode::OK_200, res->status);
  2980. }
  2981. TEST_F(ServerTest, InvalidPercentEncoding) {
  2982. auto res = cli_.Get("/%endwith%");
  2983. ASSERT_TRUE(res);
  2984. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2985. }
  2986. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  2987. auto res = cli_.Get("/%uendwith%");
  2988. ASSERT_TRUE(res);
  2989. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2990. }
  2991. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  2992. auto res = cli_.Get("/hello?aaa=bbb%");
  2993. ASSERT_TRUE(res);
  2994. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  2995. }
  2996. TEST_F(ServerTest, PlusSignEncoding) {
  2997. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  2998. ASSERT_TRUE(res);
  2999. EXPECT_EQ(StatusCode::OK_200, res->status);
  3000. EXPECT_EQ("a +b", res->body);
  3001. }
  3002. TEST_F(ServerTest, MultipartFormData) {
  3003. MultipartFormDataItems items = {
  3004. {"text1", "text default", "", ""},
  3005. {"text2", "aωb", "", ""},
  3006. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3007. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3008. {"file3", "", "", "application/octet-stream"},
  3009. {"file4", "", "", " application/json tmp-string "}};
  3010. auto res = cli_.Post("/multipart", items);
  3011. ASSERT_TRUE(res);
  3012. EXPECT_EQ(StatusCode::OK_200, res->status);
  3013. }
  3014. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  3015. MultipartFormDataItems items = {
  3016. {"text", "default text", "", ""},
  3017. {"multi_text1", "aaaaa", "", ""},
  3018. {"multi_text1", "bbbbb", "", ""},
  3019. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3020. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  3021. "application/json"},
  3022. };
  3023. auto res = cli_.Post("/multipart/multi_file_values", items);
  3024. ASSERT_TRUE(res);
  3025. EXPECT_EQ(StatusCode::OK_200, res->status);
  3026. }
  3027. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  3028. auto res = cli_.Get("/hi");
  3029. ASSERT_TRUE(res);
  3030. EXPECT_EQ(StatusCode::OK_200, res->status);
  3031. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  3032. EXPECT_EQ("Hello World!", res->body);
  3033. }
  3034. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  3035. Request req;
  3036. req.method = "POST";
  3037. req.path = "/chunked";
  3038. std::string host_and_port;
  3039. host_and_port += HOST;
  3040. host_and_port += ":";
  3041. host_and_port += std::to_string(PORT);
  3042. req.headers.emplace("Host", host_and_port.c_str());
  3043. req.headers.emplace("Accept", "*/*");
  3044. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3045. req.headers.emplace("Content-Type", "text/plain");
  3046. req.headers.emplace("Content-Length", "0");
  3047. req.headers.emplace(
  3048. "Transfer-Encoding",
  3049. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  3050. // Client does not chunk, so make a chunked body manually.
  3051. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  3052. auto res = std::make_shared<Response>();
  3053. auto error = Error::Success;
  3054. auto ret = cli_.send(req, *res, error);
  3055. ASSERT_TRUE(ret);
  3056. EXPECT_EQ(StatusCode::OK_200, res->status);
  3057. }
  3058. TEST_F(ServerTest, GetStreamed2) {
  3059. auto res = cli_.Get("/streamed", {{make_range_header({{2, 3}})}});
  3060. ASSERT_TRUE(res);
  3061. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3062. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3063. EXPECT_EQ(true, res->has_header("Content-Range"));
  3064. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  3065. EXPECT_EQ(std::string("ab"), res->body);
  3066. }
  3067. TEST_F(ServerTest, GetStreamed) {
  3068. auto res = cli_.Get("/streamed");
  3069. ASSERT_TRUE(res);
  3070. EXPECT_EQ(StatusCode::OK_200, res->status);
  3071. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3072. EXPECT_EQ(std::string("aaabbb"), res->body);
  3073. }
  3074. TEST_F(ServerTest, GetStreamedWithRange1) {
  3075. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{3, 5}})}});
  3076. ASSERT_TRUE(res);
  3077. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3078. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3079. EXPECT_EQ(true, res->has_header("Content-Range"));
  3080. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3081. EXPECT_EQ(std::string("def"), res->body);
  3082. }
  3083. TEST_F(ServerTest, GetStreamedWithRange2) {
  3084. auto res = cli_.Get("/streamed-with-range", {{make_range_header({{1, -1}})}});
  3085. ASSERT_TRUE(res);
  3086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3087. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3088. EXPECT_EQ(true, res->has_header("Content-Range"));
  3089. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3090. EXPECT_EQ(std::string("bcdefg"), res->body);
  3091. }
  3092. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  3093. auto res = cli_.Get("/streamed-with-range", {{"Range", "bytes=-3"}});
  3094. ASSERT_TRUE(res);
  3095. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3096. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3097. EXPECT_EQ(true, res->has_header("Content-Range"));
  3098. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  3099. EXPECT_EQ(std::string("efg"), res->body);
  3100. }
  3101. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  3102. auto res = cli_.Get("/streamed-with-range?error", {{"Range", "bytes=-9999"}});
  3103. ASSERT_TRUE(res);
  3104. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3105. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3106. EXPECT_EQ(false, res->has_header("Content-Range"));
  3107. EXPECT_EQ(0U, res->body.size());
  3108. }
  3109. TEST_F(ServerTest, GetStreamedWithRangeError) {
  3110. auto res = cli_.Get("/streamed-with-range",
  3111. {{"Range", "bytes=92233720368547758079223372036854775806-"
  3112. "92233720368547758079223372036854775807"}});
  3113. ASSERT_TRUE(res);
  3114. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3115. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3116. EXPECT_EQ(false, res->has_header("Content-Range"));
  3117. EXPECT_EQ(0U, res->body.size());
  3118. }
  3119. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  3120. auto res = cli_.Get(
  3121. "/with-range",
  3122. {{"Range",
  3123. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())}});
  3124. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3125. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3126. EXPECT_EQ(false, res->has_header("Content-Range"));
  3127. EXPECT_EQ(0U, res->body.size());
  3128. }
  3129. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  3130. auto res =
  3131. cli_.Get("/streamed-with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3132. ASSERT_TRUE(res);
  3133. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3134. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3135. EXPECT_EQ(false, res->has_header("Content-Range"));
  3136. EXPECT_EQ(267U, res->body.size());
  3137. }
  3138. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  3139. Ranges ranges;
  3140. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  3141. ranges.emplace_back(0, -1);
  3142. }
  3143. auto res =
  3144. cli_.Get("/streamed-with-range?error", {{make_range_header(ranges)}});
  3145. ASSERT_TRUE(res);
  3146. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3147. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3148. EXPECT_EQ(false, res->has_header("Content-Range"));
  3149. EXPECT_EQ(0U, res->body.size());
  3150. }
  3151. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  3152. auto res = cli_.Get("/streamed-with-range?error",
  3153. {{make_range_header({{0, -1}, {0, -1}})}});
  3154. ASSERT_TRUE(res);
  3155. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3156. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3157. EXPECT_EQ(false, res->has_header("Content-Range"));
  3158. EXPECT_EQ(0U, res->body.size());
  3159. }
  3160. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  3161. auto res = cli_.Get("/streamed-with-range?error",
  3162. {{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  3163. ASSERT_TRUE(res);
  3164. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3165. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  3166. EXPECT_EQ(false, res->has_header("Content-Range"));
  3167. EXPECT_EQ(0U, res->body.size());
  3168. }
  3169. TEST_F(ServerTest, GetStreamedEndless) {
  3170. uint64_t offset = 0;
  3171. auto res = cli_.Get("/streamed-cancel",
  3172. [&](const char * /*data*/, uint64_t data_length) {
  3173. if (offset < 100) {
  3174. offset += data_length;
  3175. return true;
  3176. }
  3177. return false;
  3178. });
  3179. ASSERT_TRUE(!res);
  3180. EXPECT_EQ(Error::Canceled, res.error());
  3181. }
  3182. TEST_F(ServerTest, ClientStop) {
  3183. std::atomic_size_t count{4};
  3184. std::vector<std::thread> threads;
  3185. for (auto i = count.load(); i != 0; --i) {
  3186. threads.emplace_back([&]() {
  3187. auto res = cli_.Get("/streamed-cancel",
  3188. [&](const char *, uint64_t) { return true; });
  3189. --count;
  3190. ASSERT_TRUE(!res);
  3191. EXPECT_TRUE(res.error() == Error::Canceled ||
  3192. res.error() == Error::Read || res.error() == Error::Write);
  3193. });
  3194. }
  3195. std::this_thread::sleep_for(std::chrono::seconds(2));
  3196. while (count != 0) {
  3197. cli_.stop();
  3198. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3199. }
  3200. for (auto &t : threads) {
  3201. t.join();
  3202. }
  3203. }
  3204. TEST_F(ServerTest, GetWithRange1) {
  3205. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  3206. ASSERT_TRUE(res);
  3207. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3208. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  3209. EXPECT_EQ(true, res->has_header("Content-Range"));
  3210. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  3211. EXPECT_EQ(std::string("def"), res->body);
  3212. }
  3213. TEST_F(ServerTest, GetWithRange2) {
  3214. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  3215. ASSERT_TRUE(res);
  3216. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3217. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  3218. EXPECT_EQ(true, res->has_header("Content-Range"));
  3219. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  3220. EXPECT_EQ(std::string("bcdefg"), res->body);
  3221. }
  3222. TEST_F(ServerTest, GetWithRange3) {
  3223. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  3224. ASSERT_TRUE(res);
  3225. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3226. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  3227. EXPECT_EQ(true, res->has_header("Content-Range"));
  3228. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  3229. EXPECT_EQ(std::string("a"), res->body);
  3230. }
  3231. TEST_F(ServerTest, GetWithRange4) {
  3232. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  3233. ASSERT_TRUE(res);
  3234. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3235. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  3236. EXPECT_EQ(true, res->has_header("Content-Range"));
  3237. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  3238. EXPECT_EQ(std::string("fg"), res->body);
  3239. }
  3240. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  3241. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  3242. ASSERT_TRUE(res);
  3243. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3244. }
  3245. TEST_F(ServerTest, GetWithRangeMultipart) {
  3246. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  3247. ASSERT_TRUE(res);
  3248. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  3249. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  3250. EXPECT_EQ(false, res->has_header("Content-Range"));
  3251. EXPECT_EQ(267U, res->body.size());
  3252. }
  3253. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  3254. auto res =
  3255. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  3256. ASSERT_TRUE(res);
  3257. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  3258. }
  3259. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  3260. auto res = cli_.Get("/with-range-customized-response",
  3261. {{make_range_header({{1, 2}})}});
  3262. ASSERT_TRUE(res);
  3263. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3264. EXPECT_EQ(true, res->has_header("Content-Length"));
  3265. EXPECT_EQ(false, res->has_header("Content-Range"));
  3266. EXPECT_EQ(JSON_DATA, res->body);
  3267. }
  3268. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  3269. auto res = cli_.Get("/with-range-customized-response",
  3270. {{make_range_header({{1, 2}, {4, 5}})}});
  3271. ASSERT_TRUE(res);
  3272. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3273. EXPECT_EQ(true, res->has_header("Content-Length"));
  3274. EXPECT_EQ(false, res->has_header("Content-Range"));
  3275. EXPECT_EQ(JSON_DATA, res->body);
  3276. }
  3277. TEST_F(ServerTest, Issue1772) {
  3278. auto res = cli_.Get("/issue1772", {{make_range_header({{1000, -1}})}});
  3279. ASSERT_TRUE(res);
  3280. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3281. }
  3282. TEST_F(ServerTest, GetStreamedChunked) {
  3283. auto res = cli_.Get("/streamed-chunked");
  3284. ASSERT_TRUE(res);
  3285. EXPECT_EQ(StatusCode::OK_200, res->status);
  3286. EXPECT_EQ(std::string("123456789"), res->body);
  3287. }
  3288. TEST_F(ServerTest, GetStreamedChunked2) {
  3289. auto res = cli_.Get("/streamed-chunked2");
  3290. ASSERT_TRUE(res);
  3291. EXPECT_EQ(StatusCode::OK_200, res->status);
  3292. EXPECT_EQ(std::string("123456789"), res->body);
  3293. }
  3294. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  3295. auto res = cli_.Get("/streamed-chunked-with-trailer");
  3296. ASSERT_TRUE(res);
  3297. EXPECT_EQ(StatusCode::OK_200, res->status);
  3298. EXPECT_EQ(std::string("123456789"), res->body);
  3299. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  3300. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  3301. }
  3302. TEST_F(ServerTest, LargeChunkedPost) {
  3303. Request req;
  3304. req.method = "POST";
  3305. req.path = "/large-chunked";
  3306. std::string host_and_port;
  3307. host_and_port += HOST;
  3308. host_and_port += ":";
  3309. host_and_port += std::to_string(PORT);
  3310. req.headers.emplace("Host", host_and_port.c_str());
  3311. req.headers.emplace("Accept", "*/*");
  3312. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  3313. req.headers.emplace("Content-Type", "text/plain");
  3314. req.headers.emplace("Content-Length", "0");
  3315. req.headers.emplace("Transfer-Encoding", "chunked");
  3316. std::string long_string(30 * 1024u, 'a');
  3317. std::string chunk = "7800\r\n" + long_string + "\r\n";
  3318. // Attempt to make a large enough post to exceed OS buffers, to test that
  3319. // the server handles short reads if the full chunk data isn't available.
  3320. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  3321. auto res = std::make_shared<Response>();
  3322. auto error = Error::Success;
  3323. auto ret = cli_.send(req, *res, error);
  3324. ASSERT_TRUE(ret);
  3325. EXPECT_EQ(StatusCode::OK_200, res->status);
  3326. }
  3327. TEST_F(ServerTest, GetMethodRemoteAddr) {
  3328. auto res = cli_.Get("/remote_addr");
  3329. ASSERT_TRUE(res);
  3330. EXPECT_EQ(StatusCode::OK_200, res->status);
  3331. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3332. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  3333. }
  3334. TEST_F(ServerTest, GetMethodLocalAddr) {
  3335. auto res = cli_.Get("/local_addr");
  3336. ASSERT_TRUE(res);
  3337. EXPECT_EQ(StatusCode::OK_200, res->status);
  3338. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3339. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  3340. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  3341. }
  3342. TEST_F(ServerTest, HTTPResponseSplitting) {
  3343. auto res = cli_.Get("/http_response_splitting");
  3344. ASSERT_TRUE(res);
  3345. EXPECT_EQ(StatusCode::OK_200, res->status);
  3346. }
  3347. TEST_F(ServerTest, SlowRequest) {
  3348. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3349. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3350. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  3351. }
  3352. #if 0
  3353. TEST_F(ServerTest, SlowPost) {
  3354. char buffer[64 * 1024];
  3355. memset(buffer, 0x42, sizeof(buffer));
  3356. auto res = cli_.Post(
  3357. "/slowpost", 64 * 1024 * 1024,
  3358. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3359. auto ret = sink.write(buffer, sizeof(buffer));
  3360. EXPECT_TRUE(ret);
  3361. return true;
  3362. },
  3363. "text/plain");
  3364. ASSERT_TRUE(res);
  3365. EXPECT_EQ(StatusCode::OK_200, res->status);
  3366. }
  3367. TEST_F(ServerTest, SlowPostFail) {
  3368. char buffer[64 * 1024];
  3369. memset(buffer, 0x42, sizeof(buffer));
  3370. cli_.set_write_timeout(std::chrono::seconds(0));
  3371. auto res = cli_.Post(
  3372. "/slowpost", 64 * 1024 * 1024,
  3373. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3374. sink.write(buffer, sizeof(buffer));
  3375. return true;
  3376. },
  3377. "text/plain");
  3378. ASSERT_TRUE(!res);
  3379. EXPECT_EQ(Error::Write, res.error());
  3380. }
  3381. #endif
  3382. TEST_F(ServerTest, Put) {
  3383. auto res = cli_.Put("/put", "PUT", "text/plain");
  3384. ASSERT_TRUE(res);
  3385. EXPECT_EQ(StatusCode::OK_200, res->status);
  3386. EXPECT_EQ("PUT", res->body);
  3387. }
  3388. TEST_F(ServerTest, PutWithContentProvider) {
  3389. auto res = cli_.Put(
  3390. "/put", 3,
  3391. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3392. sink.os << "PUT";
  3393. return true;
  3394. },
  3395. "text/plain");
  3396. ASSERT_TRUE(res);
  3397. EXPECT_EQ(StatusCode::OK_200, res->status);
  3398. EXPECT_EQ("PUT", res->body);
  3399. }
  3400. TEST_F(ServerTest, PostWithContentProviderAbort) {
  3401. auto res = cli_.Post(
  3402. "/post", 42,
  3403. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3404. return false;
  3405. },
  3406. "text/plain");
  3407. ASSERT_TRUE(!res);
  3408. EXPECT_EQ(Error::Canceled, res.error());
  3409. }
  3410. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  3411. auto res = cli_.Put(
  3412. "/put",
  3413. [](size_t /*offset*/, DataSink &sink) {
  3414. sink.os << "PUT";
  3415. sink.done();
  3416. return true;
  3417. },
  3418. "text/plain");
  3419. ASSERT_TRUE(res);
  3420. EXPECT_EQ(StatusCode::OK_200, res->status);
  3421. EXPECT_EQ("PUT", res->body);
  3422. }
  3423. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  3424. auto res = cli_.Post(
  3425. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3426. "text/plain");
  3427. ASSERT_TRUE(!res);
  3428. EXPECT_EQ(Error::Canceled, res.error());
  3429. }
  3430. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3431. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  3432. cli_.set_compress(true);
  3433. auto res = cli_.Put(
  3434. "/put", 3,
  3435. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  3436. sink.os << "PUT";
  3437. return true;
  3438. },
  3439. "text/plain");
  3440. ASSERT_TRUE(res);
  3441. EXPECT_EQ(StatusCode::OK_200, res->status);
  3442. EXPECT_EQ("PUT", res->body);
  3443. }
  3444. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  3445. cli_.set_compress(true);
  3446. auto res = cli_.Post(
  3447. "/post", 42,
  3448. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  3449. return false;
  3450. },
  3451. "text/plain");
  3452. ASSERT_TRUE(!res);
  3453. EXPECT_EQ(Error::Canceled, res.error());
  3454. }
  3455. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  3456. cli_.set_compress(true);
  3457. auto res = cli_.Put(
  3458. "/put",
  3459. [](size_t /*offset*/, DataSink &sink) {
  3460. sink.os << "PUT";
  3461. sink.done();
  3462. return true;
  3463. },
  3464. "text/plain");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(StatusCode::OK_200, res->status);
  3467. EXPECT_EQ("PUT", res->body);
  3468. }
  3469. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  3470. cli_.set_compress(true);
  3471. auto res = cli_.Post(
  3472. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  3473. "text/plain");
  3474. ASSERT_TRUE(!res);
  3475. EXPECT_EQ(Error::Canceled, res.error());
  3476. }
  3477. TEST_F(ServerTest, PutLargeFileWithGzip) {
  3478. cli_.set_compress(true);
  3479. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  3480. ASSERT_TRUE(res);
  3481. EXPECT_EQ(StatusCode::OK_200, res->status);
  3482. EXPECT_EQ(LARGE_DATA, res->body);
  3483. }
  3484. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  3485. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3486. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  3487. Client cli(s.c_str());
  3488. cli.enable_server_certificate_verification(false);
  3489. #else
  3490. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  3491. Client cli(s.c_str());
  3492. #endif
  3493. cli.set_compress(true);
  3494. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  3495. ASSERT_TRUE(res);
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ(LARGE_DATA, res->body);
  3498. EXPECT_EQ(101942u, res.get_request_header_value_u64("Content-Length"));
  3499. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  3500. }
  3501. TEST_F(ServerTest, PutContentWithDeflate) {
  3502. cli_.set_compress(false);
  3503. Headers headers;
  3504. headers.emplace("Content-Encoding", "deflate");
  3505. // PUT in deflate format:
  3506. auto res = cli_.Put("/put", headers,
  3507. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  3508. ASSERT_TRUE(res);
  3509. EXPECT_EQ(StatusCode::OK_200, res->status);
  3510. EXPECT_EQ("PUT", res->body);
  3511. }
  3512. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  3513. Headers headers;
  3514. headers.emplace("Accept-Encoding", "gzip, deflate");
  3515. auto res = cli_.Get("/streamed-chunked", headers);
  3516. ASSERT_TRUE(res);
  3517. EXPECT_EQ(StatusCode::OK_200, res->status);
  3518. EXPECT_EQ(std::string("123456789"), res->body);
  3519. }
  3520. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  3521. Headers headers;
  3522. headers.emplace("Accept-Encoding", "gzip, deflate");
  3523. auto res = cli_.Get("/streamed-chunked2", headers);
  3524. ASSERT_TRUE(res);
  3525. EXPECT_EQ(StatusCode::OK_200, res->status);
  3526. EXPECT_EQ(std::string("123456789"), res->body);
  3527. }
  3528. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  3529. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  3530. ASSERT_TRUE(res);
  3531. EXPECT_EQ(StatusCode::OK_200, res->status);
  3532. }
  3533. TEST(GzipDecompressor, ChunkedDecompression) {
  3534. std::string data;
  3535. for (size_t i = 0; i < 32 * 1024; ++i) {
  3536. data.push_back(static_cast<char>('a' + i % 26));
  3537. }
  3538. std::string compressed_data;
  3539. {
  3540. httplib::detail::gzip_compressor compressor;
  3541. bool result = compressor.compress(
  3542. data.data(), data.size(),
  3543. /*last=*/true,
  3544. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  3545. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  3546. compressed_data_size);
  3547. return true;
  3548. });
  3549. ASSERT_TRUE(result);
  3550. }
  3551. std::string decompressed_data;
  3552. {
  3553. httplib::detail::gzip_decompressor decompressor;
  3554. // Chunk size is chosen specifically to have a decompressed chunk size equal
  3555. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  3556. size_t chunk_size = 130;
  3557. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  3558. chunk_begin += chunk_size) {
  3559. size_t current_chunk_size =
  3560. std::min(compressed_data.size() - chunk_begin, chunk_size);
  3561. bool result = decompressor.decompress(
  3562. compressed_data.data() + chunk_begin, current_chunk_size,
  3563. [&](const char *decompressed_data_chunk,
  3564. size_t decompressed_data_chunk_size) {
  3565. decompressed_data.insert(decompressed_data.size(),
  3566. decompressed_data_chunk,
  3567. decompressed_data_chunk_size);
  3568. return true;
  3569. });
  3570. ASSERT_TRUE(result);
  3571. }
  3572. }
  3573. ASSERT_EQ(data, decompressed_data);
  3574. }
  3575. TEST(GzipDecompressor, DeflateDecompression) {
  3576. std::string original_text = "Raw deflate without gzip";
  3577. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3578. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3579. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3580. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  3581. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3582. std::string decompressed_data;
  3583. {
  3584. httplib::detail::gzip_decompressor decompressor;
  3585. bool result = decompressor.decompress(
  3586. compressed_data.data(), compressed_data.size(),
  3587. [&](const char *decompressed_data_chunk,
  3588. size_t decompressed_data_chunk_size) {
  3589. decompressed_data.insert(decompressed_data.size(),
  3590. decompressed_data_chunk,
  3591. decompressed_data_chunk_size);
  3592. return true;
  3593. });
  3594. ASSERT_TRUE(result);
  3595. }
  3596. ASSERT_EQ(original_text, decompressed_data);
  3597. }
  3598. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  3599. std::string original_text = "Raw deflate without gzip";
  3600. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  3601. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  3602. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  3603. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  3604. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  3605. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  3606. std::string decompressed_data;
  3607. {
  3608. httplib::detail::gzip_decompressor decompressor;
  3609. bool result = decompressor.decompress(
  3610. compressed_data.data(), compressed_data.size(),
  3611. [&](const char *decompressed_data_chunk,
  3612. size_t decompressed_data_chunk_size) {
  3613. decompressed_data.insert(decompressed_data.size(),
  3614. decompressed_data_chunk,
  3615. decompressed_data_chunk_size);
  3616. return true;
  3617. });
  3618. ASSERT_TRUE(result);
  3619. }
  3620. ASSERT_EQ(original_text, decompressed_data);
  3621. }
  3622. #ifdef _WIN32
  3623. TEST(GzipDecompressor, LargeRandomData) {
  3624. // prepare large random data that is difficult to be compressed and is
  3625. // expected to have large size even when compressed
  3626. std::random_device seed_gen;
  3627. std::mt19937 random(seed_gen());
  3628. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  3629. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  3630. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  3631. std::generate(data.begin(), data.end(), [&]() { return random(); });
  3632. // compress data over 4GiB
  3633. std::string compressed_data;
  3634. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  3635. httplib::detail::gzip_compressor compressor;
  3636. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  3637. data.size() * sizeof(std::uint32_t), true,
  3638. [&](const char *data, size_t size) {
  3639. compressed_data.insert(
  3640. compressed_data.size(), data, size);
  3641. return true;
  3642. });
  3643. ASSERT_TRUE(result);
  3644. // FIXME: compressed data size is expected to be greater than 4GiB,
  3645. // but there is no guarantee
  3646. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  3647. // decompress data over 4GiB
  3648. std::string decompressed_data;
  3649. decompressed_data.reserve(data_size);
  3650. httplib::detail::gzip_decompressor decompressor;
  3651. result = decompressor.decompress(
  3652. compressed_data.data(), compressed_data.size(),
  3653. [&](const char *data, size_t size) {
  3654. decompressed_data.insert(decompressed_data.size(), data, size);
  3655. return true;
  3656. });
  3657. ASSERT_TRUE(result);
  3658. // compare
  3659. ASSERT_EQ(data_size, decompressed_data.size());
  3660. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  3661. 0);
  3662. }
  3663. #endif
  3664. #endif
  3665. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3666. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  3667. Headers headers;
  3668. headers.emplace("Accept-Encoding", "br");
  3669. auto res = cli_.Get("/streamed-chunked", headers);
  3670. ASSERT_TRUE(res);
  3671. EXPECT_EQ(StatusCode::OK_200, res->status);
  3672. EXPECT_EQ(std::string("123456789"), res->body);
  3673. }
  3674. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  3675. Headers headers;
  3676. headers.emplace("Accept-Encoding", "br");
  3677. auto res = cli_.Get("/streamed-chunked2", headers);
  3678. ASSERT_TRUE(res);
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. EXPECT_EQ(std::string("123456789"), res->body);
  3681. }
  3682. #endif
  3683. TEST_F(ServerTest, Patch) {
  3684. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  3685. ASSERT_TRUE(res);
  3686. EXPECT_EQ(StatusCode::OK_200, res->status);
  3687. EXPECT_EQ("PATCH", res->body);
  3688. }
  3689. TEST_F(ServerTest, Delete) {
  3690. auto res = cli_.Delete("/delete");
  3691. ASSERT_TRUE(res);
  3692. EXPECT_EQ(StatusCode::OK_200, res->status);
  3693. EXPECT_EQ("DELETE", res->body);
  3694. }
  3695. TEST_F(ServerTest, DeleteContentReceiver) {
  3696. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  3697. ASSERT_TRUE(res);
  3698. EXPECT_EQ(StatusCode::OK_200, res->status);
  3699. EXPECT_EQ("content", res->body);
  3700. }
  3701. TEST_F(ServerTest, Options) {
  3702. auto res = cli_.Options("*");
  3703. ASSERT_TRUE(res);
  3704. EXPECT_EQ(StatusCode::OK_200, res->status);
  3705. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  3706. EXPECT_TRUE(res->body.empty());
  3707. }
  3708. TEST_F(ServerTest, URL) {
  3709. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  3710. ASSERT_TRUE(res);
  3711. EXPECT_EQ(StatusCode::OK_200, res->status);
  3712. }
  3713. TEST_F(ServerTest, ArrayParam) {
  3714. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  3715. ASSERT_TRUE(res);
  3716. EXPECT_EQ(StatusCode::OK_200, res->status);
  3717. }
  3718. TEST_F(ServerTest, NoMultipleHeaders) {
  3719. Headers headers = {{"Content-Length", "5"}};
  3720. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  3721. "text/plain");
  3722. ASSERT_TRUE(res);
  3723. EXPECT_EQ(StatusCode::OK_200, res->status);
  3724. }
  3725. TEST_F(ServerTest, PostContentReceiver) {
  3726. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3727. ASSERT_TRUE(res);
  3728. ASSERT_EQ(StatusCode::OK_200, res->status);
  3729. ASSERT_EQ("content", res->body);
  3730. }
  3731. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  3732. MultipartFormDataItems items = {
  3733. {"text1", "text default", "", ""},
  3734. {"text2", "aωb", "", ""},
  3735. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3736. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3737. {"file3", "", "", "application/octet-stream"},
  3738. };
  3739. auto res = cli_.Post("/content_receiver", items);
  3740. ASSERT_TRUE(res);
  3741. EXPECT_EQ(StatusCode::OK_200, res->status);
  3742. }
  3743. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  3744. MultipartFormDataItems items = {
  3745. {"text1", "text default", "", ""},
  3746. {"text2", "aωb", "", ""},
  3747. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  3748. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  3749. {"file3", "", "", "application/octet-stream"},
  3750. };
  3751. auto boundary = std::string("+++++");
  3752. std::string body;
  3753. for (const auto &item : items) {
  3754. body += "--" + boundary + "\r\n";
  3755. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  3756. if (!item.filename.empty()) {
  3757. body += "; filename=\"" + item.filename + "\"";
  3758. }
  3759. body += "\r\n";
  3760. if (!item.content_type.empty()) {
  3761. body += "Content-Type: " + item.content_type + "\r\n";
  3762. }
  3763. body += "\r\n";
  3764. body += item.content + "\r\n";
  3765. }
  3766. body += "--" + boundary + "--\r\n";
  3767. std::string content_type = "multipart/form-data; boundary=" + boundary;
  3768. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  3769. ASSERT_TRUE(res);
  3770. EXPECT_EQ(StatusCode::OK_200, res->status);
  3771. }
  3772. TEST_F(ServerTest, PostContentReceiverGzip) {
  3773. cli_.set_compress(true);
  3774. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  3775. ASSERT_TRUE(res);
  3776. ASSERT_EQ(StatusCode::OK_200, res->status);
  3777. ASSERT_EQ("content", res->body);
  3778. }
  3779. TEST_F(ServerTest, PutContentReceiver) {
  3780. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  3781. ASSERT_TRUE(res);
  3782. ASSERT_EQ(StatusCode::OK_200, res->status);
  3783. ASSERT_EQ("content", res->body);
  3784. }
  3785. TEST_F(ServerTest, PatchContentReceiver) {
  3786. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  3787. ASSERT_TRUE(res);
  3788. ASSERT_EQ(StatusCode::OK_200, res->status);
  3789. ASSERT_EQ("content", res->body);
  3790. }
  3791. TEST_F(ServerTest, PostQueryStringAndBody) {
  3792. auto res =
  3793. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  3794. ASSERT_TRUE(res);
  3795. ASSERT_EQ(StatusCode::OK_200, res->status);
  3796. }
  3797. TEST_F(ServerTest, HTTP2Magic) {
  3798. Request req;
  3799. req.method = "PRI";
  3800. req.path = "*";
  3801. req.body = "SM";
  3802. auto res = std::make_shared<Response>();
  3803. auto error = Error::Success;
  3804. auto ret = cli_.send(req, *res, error);
  3805. ASSERT_TRUE(ret);
  3806. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  3807. }
  3808. TEST_F(ServerTest, KeepAlive) {
  3809. auto res = cli_.Get("/hi");
  3810. ASSERT_TRUE(res);
  3811. EXPECT_EQ(StatusCode::OK_200, res->status);
  3812. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3813. EXPECT_EQ("Hello World!", res->body);
  3814. res = cli_.Get("/hi");
  3815. ASSERT_TRUE(res);
  3816. EXPECT_EQ(StatusCode::OK_200, res->status);
  3817. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3818. EXPECT_EQ("Hello World!", res->body);
  3819. res = cli_.Get("/hi");
  3820. ASSERT_TRUE(res);
  3821. EXPECT_EQ(StatusCode::OK_200, res->status);
  3822. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3823. EXPECT_EQ("Hello World!", res->body);
  3824. res = cli_.Get("/not-exist");
  3825. ASSERT_TRUE(res);
  3826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3827. res = cli_.Post("/empty", "", "text/plain");
  3828. ASSERT_TRUE(res);
  3829. EXPECT_EQ(StatusCode::OK_200, res->status);
  3830. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3831. EXPECT_EQ("empty", res->body);
  3832. EXPECT_EQ("close", res->get_header_value("Connection"));
  3833. res = cli_.Post(
  3834. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3835. "text/plain");
  3836. ASSERT_TRUE(res);
  3837. EXPECT_EQ(StatusCode::OK_200, res->status);
  3838. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3839. EXPECT_EQ("empty", res->body);
  3840. cli_.set_keep_alive(false);
  3841. res = cli_.Get("/last-request");
  3842. ASSERT_TRUE(res);
  3843. EXPECT_EQ(StatusCode::OK_200, res->status);
  3844. EXPECT_EQ("close", res->get_header_value("Connection"));
  3845. }
  3846. TEST_F(ServerTest, TooManyRedirect) {
  3847. cli_.set_follow_location(true);
  3848. auto res = cli_.Get("/redirect/0");
  3849. ASSERT_TRUE(!res);
  3850. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3851. }
  3852. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3853. TEST_F(ServerTest, Gzip) {
  3854. Headers headers;
  3855. headers.emplace("Accept-Encoding", "gzip, deflate");
  3856. auto res = cli_.Get("/compress", headers);
  3857. ASSERT_TRUE(res);
  3858. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3859. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3860. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3861. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3862. "7890123456789012345678901234567890",
  3863. res->body);
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. }
  3866. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3867. auto res = cli_.Get("/compress");
  3868. ASSERT_TRUE(res);
  3869. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3870. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3871. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3872. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3873. "7890123456789012345678901234567890",
  3874. res->body);
  3875. EXPECT_EQ(StatusCode::OK_200, res->status);
  3876. }
  3877. TEST_F(ServerTest, GzipWithContentReceiver) {
  3878. Headers headers;
  3879. headers.emplace("Accept-Encoding", "gzip, deflate");
  3880. std::string body;
  3881. auto res = cli_.Get("/compress", headers,
  3882. [&](const char *data, uint64_t data_length) {
  3883. EXPECT_EQ(100U, data_length);
  3884. body.append(data, data_length);
  3885. return true;
  3886. });
  3887. ASSERT_TRUE(res);
  3888. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3889. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3890. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3891. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3892. "7890123456789012345678901234567890",
  3893. body);
  3894. EXPECT_EQ(StatusCode::OK_200, res->status);
  3895. }
  3896. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3897. Headers headers;
  3898. headers.emplace("Accept-Encoding", "gzip, deflate");
  3899. cli_.set_decompress(false);
  3900. auto res = cli_.Get("/compress", headers);
  3901. ASSERT_TRUE(res);
  3902. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3903. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3904. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3905. EXPECT_EQ(33U, res->body.size());
  3906. EXPECT_EQ(StatusCode::OK_200, res->status);
  3907. }
  3908. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3909. std::string body;
  3910. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3911. EXPECT_EQ(100U, data_length);
  3912. body.append(data, data_length);
  3913. return true;
  3914. });
  3915. ASSERT_TRUE(res);
  3916. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3917. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3918. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3919. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3920. "7890123456789012345678901234567890",
  3921. body);
  3922. EXPECT_EQ(StatusCode::OK_200, res->status);
  3923. }
  3924. TEST_F(ServerTest, NoGzip) {
  3925. Headers headers;
  3926. headers.emplace("Accept-Encoding", "gzip, deflate");
  3927. auto res = cli_.Get("/nocompress", headers);
  3928. ASSERT_TRUE(res);
  3929. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3930. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3931. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3932. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3933. "7890123456789012345678901234567890",
  3934. res->body);
  3935. EXPECT_EQ(StatusCode::OK_200, res->status);
  3936. }
  3937. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3938. Headers headers;
  3939. headers.emplace("Accept-Encoding", "gzip, deflate");
  3940. std::string body;
  3941. auto res = cli_.Get("/nocompress", headers,
  3942. [&](const char *data, uint64_t data_length) {
  3943. EXPECT_EQ(100U, data_length);
  3944. body.append(data, data_length);
  3945. return true;
  3946. });
  3947. ASSERT_TRUE(res);
  3948. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3949. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3950. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3951. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3952. "7890123456789012345678901234567890",
  3953. body);
  3954. EXPECT_EQ(StatusCode::OK_200, res->status);
  3955. }
  3956. TEST_F(ServerTest, MultipartFormDataGzip) {
  3957. MultipartFormDataItems items = {
  3958. {"key1", "test", "", ""},
  3959. {"key2", "--abcdefg123", "", ""},
  3960. };
  3961. cli_.set_compress(true);
  3962. auto res = cli_.Post("/compress-multipart", items);
  3963. ASSERT_TRUE(res);
  3964. EXPECT_EQ(StatusCode::OK_200, res->status);
  3965. }
  3966. #endif
  3967. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3968. TEST_F(ServerTest, Brotli) {
  3969. Headers headers;
  3970. headers.emplace("Accept-Encoding", "br");
  3971. auto res = cli_.Get("/compress", headers);
  3972. ASSERT_TRUE(res);
  3973. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3974. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3975. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3976. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3977. "7890123456789012345678901234567890",
  3978. res->body);
  3979. EXPECT_EQ(StatusCode::OK_200, res->status);
  3980. }
  3981. #endif
  3982. // Sends a raw request to a server listening at HOST:PORT.
  3983. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3984. std::string *resp = nullptr) {
  3985. auto error = Error::Success;
  3986. auto client_sock = detail::create_client_socket(
  3987. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3988. /*connection_timeout_sec=*/5, 0,
  3989. /*read_timeout_sec=*/5, 0,
  3990. /*write_timeout_sec=*/5, 0, std::string(), error);
  3991. if (client_sock == INVALID_SOCKET) { return false; }
  3992. auto ret = detail::process_client_socket(
  3993. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3994. if (req.size() !=
  3995. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3996. return false;
  3997. }
  3998. char buf[512];
  3999. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  4000. while (line_reader.getline()) {
  4001. if (resp) { *resp += line_reader.ptr(); }
  4002. }
  4003. return true;
  4004. });
  4005. detail::close_socket(client_sock);
  4006. return ret;
  4007. }
  4008. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  4009. Server svr;
  4010. std::string header_value;
  4011. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  4012. header_value = req.get_header_value("foo");
  4013. res.set_content("ok", "text/plain");
  4014. });
  4015. thread t = thread([&] { svr.listen(HOST, PORT); });
  4016. auto se = detail::scope_exit([&] {
  4017. svr.stop();
  4018. t.join();
  4019. ASSERT_FALSE(svr.is_running());
  4020. });
  4021. svr.wait_until_ready();
  4022. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  4023. // like characters are not treated the same - use vertical tab and escape.
  4024. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  4025. "foo: \t \v bar \x1B\t \r\n"
  4026. "Connection: close\r\n"
  4027. "\r\n";
  4028. ASSERT_TRUE(send_request(5, req));
  4029. EXPECT_EQ(header_value, "\v bar \x1B");
  4030. }
  4031. // Sends a raw request and verifies that there isn't a crash or exception.
  4032. static void test_raw_request(const std::string &req,
  4033. std::string *out = nullptr) {
  4034. Server svr;
  4035. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4036. res.set_content("ok", "text/plain");
  4037. });
  4038. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  4039. res.set_content("ok", "text/plain");
  4040. });
  4041. svr.Get("/header_field_value_check",
  4042. [&](const Request & /*req*/, Response &res) {
  4043. res.set_content("ok", "text/plain");
  4044. });
  4045. // Server read timeout must be longer than the client read timeout for the
  4046. // bug to reproduce, probably to force the server to process a request
  4047. // without a trailing blank line.
  4048. const time_t client_read_timeout_sec = 1;
  4049. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  4050. bool listen_thread_ok = false;
  4051. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. t.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. EXPECT_TRUE(listen_thread_ok);
  4057. });
  4058. svr.wait_until_ready();
  4059. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  4060. }
  4061. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  4062. // A certain header line causes an exception if the header property is parsed
  4063. // naively with a single regex. This occurs with libc++ but not libstdc++.
  4064. test_raw_request(
  4065. "GET /hi HTTP/1.1\r\n"
  4066. " : "
  4067. " "
  4068. " ");
  4069. }
  4070. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  4071. // A certain header line causes an exception if the header property *name* is
  4072. // parsed with a regular expression starting with "(.+?):" - this is a non-
  4073. // greedy matcher and requires backtracking when there are a lot of ":"
  4074. // characters.
  4075. // This occurs with libc++ but not libstdc++.
  4076. test_raw_request(
  4077. "GET /hi HTTP/1.1\r\n"
  4078. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  4079. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4080. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  4081. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  4082. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  4083. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  4084. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  4085. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  4086. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4087. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4088. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  4089. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4090. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  4091. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  4092. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  4093. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  4094. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  4095. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  4096. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  4097. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  4098. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  4099. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  4100. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  4101. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  4102. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  4103. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  4104. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  4105. "&&&%%%");
  4106. }
  4107. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  4108. // Make sure this doesn't crash the server.
  4109. // In a previous version of the header line regex, the "\r" rendered the line
  4110. // unparsable and the regex engine repeatedly backtracked, trying to look for
  4111. // a new position where the leading white space ended and the field value
  4112. // began.
  4113. // The crash occurs with libc++ but not libstdc++.
  4114. test_raw_request("GET /hi HTTP/1.1\r\n"
  4115. "a:" +
  4116. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  4117. "\r\n"
  4118. "\r\n");
  4119. }
  4120. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  4121. std::string out;
  4122. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4123. "Content-Type: text/plain\r\n"
  4124. "Transfer-Encoding: chunked\r\n"
  4125. "\r\n"
  4126. "nothex\r\n",
  4127. &out);
  4128. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4129. }
  4130. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  4131. std::string out;
  4132. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4133. "Content-Type: text/plain\r\n"
  4134. "Transfer-Encoding: chunked\r\n"
  4135. "\r\n"
  4136. "3\r\n"
  4137. "xyz\r\n"
  4138. "NaN\r\n",
  4139. &out);
  4140. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4141. }
  4142. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  4143. std::string out;
  4144. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  4145. "Content-Type: text/plain\r\n"
  4146. "Transfer-Encoding: chunked\r\n"
  4147. "\r\n"
  4148. // Length is too large for 64 bits.
  4149. "1ffffffffffffffff\r\n"
  4150. "xyz\r\n",
  4151. &out);
  4152. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4153. }
  4154. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  4155. test_raw_request("GET /hi HTTP/1.1\r\n"
  4156. "Content-Type: text/plain\r\n\r");
  4157. }
  4158. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  4159. std::string out;
  4160. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  4161. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4162. }
  4163. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  4164. std::string out;
  4165. std::string request(
  4166. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  4167. test_raw_request(request, &out);
  4168. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  4169. }
  4170. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  4171. Server svr;
  4172. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  4173. res.set_header("Cache-Control", "no-cache");
  4174. res.set_chunked_content_provider(
  4175. "text/event-stream", [](size_t offset, DataSink &sink) {
  4176. std::string s = "data:";
  4177. s += std::to_string(offset);
  4178. s += "\n\n";
  4179. auto ret = sink.write(s.data(), s.size());
  4180. EXPECT_TRUE(ret);
  4181. std::this_thread::sleep_for(std::chrono::seconds(1));
  4182. return true;
  4183. });
  4184. });
  4185. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4186. svr.wait_until_ready();
  4187. Client client(HOST, PORT);
  4188. const Headers headers = {{"Accept", "text/event-stream"}};
  4189. auto get_thread = std::thread([&client, &headers]() {
  4190. auto res = client.Get(
  4191. "/events", headers,
  4192. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  4193. });
  4194. auto se = detail::scope_exit([&] {
  4195. svr.stop();
  4196. get_thread.join();
  4197. listen_thread.join();
  4198. ASSERT_FALSE(svr.is_running());
  4199. });
  4200. // Give GET time to get a few messages.
  4201. std::this_thread::sleep_for(std::chrono::seconds(2));
  4202. }
  4203. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  4204. httplib::Server svr;
  4205. svr.Post("/hi",
  4206. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4207. res.status = StatusCode::OK_200;
  4208. });
  4209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4210. svr.wait_until_ready();
  4211. Client cli(HOST, PORT);
  4212. auto res = cli.Post("/hi", "data", "text/plain");
  4213. ASSERT_TRUE(res);
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. svr.stop();
  4216. thread.join();
  4217. ASSERT_FALSE(svr.is_running());
  4218. res = cli.Post("/hi", "data", "text/plain");
  4219. ASSERT_FALSE(res);
  4220. }
  4221. TEST(ServerStopTest, ListenFailure) {
  4222. Server svr;
  4223. auto t = thread([&]() {
  4224. auto ret = svr.listen("????", PORT);
  4225. EXPECT_FALSE(ret);
  4226. });
  4227. svr.wait_until_ready();
  4228. svr.stop();
  4229. t.join();
  4230. }
  4231. TEST(ServerStopTest, Decommision) {
  4232. Server svr;
  4233. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  4234. for (int i = 0; i < 4; i++) {
  4235. auto is_even = !(i % 2);
  4236. std::thread t{[&] {
  4237. try {
  4238. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4239. if (is_even) {
  4240. throw std::runtime_error("Some thing that happens to go wrong.");
  4241. }
  4242. svr.listen(HOST, PORT);
  4243. } catch (...) { svr.decommission(); }
  4244. }};
  4245. svr.wait_until_ready();
  4246. // Server is up
  4247. {
  4248. Client cli(HOST, PORT);
  4249. auto res = cli.Get("/hi");
  4250. if (is_even) {
  4251. EXPECT_FALSE(res);
  4252. } else {
  4253. EXPECT_TRUE(res);
  4254. EXPECT_EQ("hi...", res->body);
  4255. }
  4256. }
  4257. svr.stop();
  4258. t.join();
  4259. // Server is down...
  4260. {
  4261. Client cli(HOST, PORT);
  4262. auto res = cli.Get("/hi");
  4263. EXPECT_FALSE(res);
  4264. }
  4265. }
  4266. }
  4267. TEST(StreamingTest, NoContentLengthStreaming) {
  4268. Server svr;
  4269. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  4270. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  4271. if (offset < 6) {
  4272. sink.os << (offset < 3 ? "a" : "b");
  4273. } else {
  4274. sink.done();
  4275. }
  4276. return true;
  4277. });
  4278. });
  4279. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4280. auto listen_se = detail::scope_exit([&] {
  4281. svr.stop();
  4282. listen_thread.join();
  4283. ASSERT_FALSE(svr.is_running());
  4284. });
  4285. svr.wait_until_ready();
  4286. Client client(HOST, PORT);
  4287. auto get_thread = std::thread([&client]() {
  4288. std::string s;
  4289. auto res =
  4290. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  4291. s += std::string(data, len);
  4292. return true;
  4293. });
  4294. EXPECT_EQ("aaabbb", s);
  4295. });
  4296. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  4297. // Give GET time to get a few messages.
  4298. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4299. }
  4300. TEST(MountTest, Unmount) {
  4301. Server svr;
  4302. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4303. auto se = detail::scope_exit([&] {
  4304. svr.stop();
  4305. listen_thread.join();
  4306. ASSERT_FALSE(svr.is_running());
  4307. });
  4308. svr.wait_until_ready();
  4309. Client cli("localhost", PORT);
  4310. svr.set_mount_point("/mount2", "./www2");
  4311. auto res = cli.Get("/");
  4312. ASSERT_TRUE(res);
  4313. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4314. res = cli.Get("/mount2/dir/test.html");
  4315. ASSERT_TRUE(res);
  4316. EXPECT_EQ(StatusCode::OK_200, res->status);
  4317. svr.set_mount_point("/", "./www");
  4318. res = cli.Get("/dir/");
  4319. ASSERT_TRUE(res);
  4320. EXPECT_EQ(StatusCode::OK_200, res->status);
  4321. svr.remove_mount_point("/");
  4322. res = cli.Get("/dir/");
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4325. svr.remove_mount_point("/mount2");
  4326. res = cli.Get("/mount2/dir/test.html");
  4327. ASSERT_TRUE(res);
  4328. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4329. }
  4330. TEST(MountTest, Redicect) {
  4331. Server svr;
  4332. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4333. auto se = detail::scope_exit([&] {
  4334. svr.stop();
  4335. listen_thread.join();
  4336. ASSERT_FALSE(svr.is_running());
  4337. });
  4338. svr.set_mount_point("/", "./www");
  4339. svr.wait_until_ready();
  4340. Client cli("localhost", PORT);
  4341. auto res = cli.Get("/dir/");
  4342. ASSERT_TRUE(res);
  4343. EXPECT_EQ(StatusCode::OK_200, res->status);
  4344. res = cli.Get("/dir");
  4345. ASSERT_TRUE(res);
  4346. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  4347. res = cli.Get("/file");
  4348. ASSERT_TRUE(res);
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. res = cli.Get("/file/");
  4351. ASSERT_TRUE(res);
  4352. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4353. cli.set_follow_location(true);
  4354. res = cli.Get("/dir");
  4355. ASSERT_TRUE(res);
  4356. EXPECT_EQ(StatusCode::OK_200, res->status);
  4357. }
  4358. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4359. TEST(ExceptionTest, ThrowExceptionInHandler) {
  4360. Server svr;
  4361. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4362. throw std::runtime_error("exception...");
  4363. });
  4364. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4365. throw std::runtime_error("exception\r\n...");
  4366. });
  4367. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4368. auto se = detail::scope_exit([&] {
  4369. svr.stop();
  4370. listen_thread.join();
  4371. ASSERT_FALSE(svr.is_running());
  4372. });
  4373. svr.wait_until_ready();
  4374. Client cli("localhost", PORT);
  4375. {
  4376. auto res = cli.Get("/exception");
  4377. ASSERT_TRUE(res);
  4378. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4379. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4380. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  4381. }
  4382. {
  4383. auto res = cli.Get("/unknown");
  4384. ASSERT_TRUE(res);
  4385. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4386. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  4387. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  4388. }
  4389. }
  4390. #endif
  4391. TEST(KeepAliveTest, ReadTimeout) {
  4392. Server svr;
  4393. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4394. std::this_thread::sleep_for(std::chrono::seconds(2));
  4395. res.set_content("a", "text/plain");
  4396. });
  4397. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4398. res.set_content("b", "text/plain");
  4399. });
  4400. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4401. auto se = detail::scope_exit([&] {
  4402. svr.stop();
  4403. listen_thread.join();
  4404. ASSERT_FALSE(svr.is_running());
  4405. });
  4406. svr.wait_until_ready();
  4407. Client cli("localhost", PORT);
  4408. cli.set_keep_alive(true);
  4409. cli.set_read_timeout(std::chrono::seconds(1));
  4410. auto resa = cli.Get("/a");
  4411. ASSERT_FALSE(resa);
  4412. EXPECT_EQ(Error::Read, resa.error());
  4413. auto resb = cli.Get("/b");
  4414. ASSERT_TRUE(resb);
  4415. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4416. EXPECT_EQ("b", resb->body);
  4417. }
  4418. TEST(KeepAliveTest, Issue1041) {
  4419. Server svr;
  4420. svr.set_keep_alive_timeout(3);
  4421. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4422. res.set_content("Hello World!", "text/plain");
  4423. });
  4424. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4425. auto se = detail::scope_exit([&] {
  4426. svr.stop();
  4427. listen_thread.join();
  4428. ASSERT_FALSE(svr.is_running());
  4429. });
  4430. svr.wait_until_ready();
  4431. Client cli(HOST, PORT);
  4432. cli.set_keep_alive(true);
  4433. auto result = cli.Get("/hi");
  4434. ASSERT_TRUE(result);
  4435. EXPECT_EQ(StatusCode::OK_200, result->status);
  4436. std::this_thread::sleep_for(std::chrono::seconds(5));
  4437. result = cli.Get("/hi");
  4438. ASSERT_TRUE(result);
  4439. EXPECT_EQ(StatusCode::OK_200, result->status);
  4440. }
  4441. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4442. TEST(KeepAliveTest, SSLClientReconnection) {
  4443. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4444. ASSERT_TRUE(svr.is_valid());
  4445. svr.set_keep_alive_timeout(1);
  4446. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  4447. res.set_content("Hello World!", "text/plain");
  4448. });
  4449. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4450. auto se = detail::scope_exit([&] {
  4451. svr.stop();
  4452. listen_thread.join();
  4453. ASSERT_FALSE(svr.is_running());
  4454. });
  4455. svr.wait_until_ready();
  4456. SSLClient cli(HOST, PORT);
  4457. cli.enable_server_certificate_verification(false);
  4458. cli.set_keep_alive(true);
  4459. auto result = cli.Get("/hi");
  4460. ASSERT_TRUE(result);
  4461. EXPECT_EQ(StatusCode::OK_200, result->status);
  4462. result = cli.Get("/hi");
  4463. ASSERT_TRUE(result);
  4464. EXPECT_EQ(StatusCode::OK_200, result->status);
  4465. std::this_thread::sleep_for(std::chrono::seconds(2));
  4466. // Recoonect
  4467. result = cli.Get("/hi");
  4468. ASSERT_TRUE(result);
  4469. EXPECT_EQ(StatusCode::OK_200, result->status);
  4470. result = cli.Get("/hi");
  4471. ASSERT_TRUE(result);
  4472. EXPECT_EQ(StatusCode::OK_200, result->status);
  4473. }
  4474. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  4475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4476. ASSERT_TRUE(svr.is_valid());
  4477. svr.set_keep_alive_timeout(1);
  4478. std::string content = "reconnect";
  4479. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  4480. res.set_content("Hello World!", "text/plain");
  4481. });
  4482. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  4483. auto se = detail::scope_exit([&] {
  4484. svr.stop();
  4485. listen_thread.join();
  4486. ASSERT_FALSE(svr.is_running());
  4487. });
  4488. svr.wait_until_ready();
  4489. SSLClient cli(HOST, PORT);
  4490. cli.enable_server_certificate_verification(false);
  4491. cli.set_keep_alive(true);
  4492. auto result = cli.Post(
  4493. "/hi", content.size(),
  4494. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4495. sink.write(content.c_str(), content.size());
  4496. return true;
  4497. },
  4498. "text/plain");
  4499. ASSERT_TRUE(result);
  4500. EXPECT_EQ(200, result->status);
  4501. std::this_thread::sleep_for(std::chrono::seconds(2));
  4502. // Recoonect
  4503. result = cli.Post(
  4504. "/hi", content.size(),
  4505. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4506. sink.write(content.c_str(), content.size());
  4507. return true;
  4508. },
  4509. "text/plain");
  4510. ASSERT_TRUE(result);
  4511. EXPECT_EQ(200, result->status);
  4512. result = cli.Post(
  4513. "/hi", content.size(),
  4514. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4515. sink.write(content.c_str(), content.size());
  4516. return true;
  4517. },
  4518. "text/plain");
  4519. ASSERT_TRUE(result);
  4520. EXPECT_EQ(200, result->status);
  4521. }
  4522. #endif
  4523. TEST(ClientProblemDetectionTest, ContentProvider) {
  4524. Server svr;
  4525. size_t content_length = 1024 * 1024;
  4526. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4527. res.set_content_provider(
  4528. content_length, "text/plain",
  4529. [&](size_t offset, size_t length, DataSink &sink) {
  4530. auto out_len = std::min(length, static_cast<size_t>(1024));
  4531. std::string out(out_len, '@');
  4532. sink.write(out.data(), out_len);
  4533. return offset < 4096;
  4534. },
  4535. [](bool success) { ASSERT_FALSE(success); });
  4536. });
  4537. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  4538. res.set_content_provider(
  4539. 0, "text/plain",
  4540. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  4541. EXPECT_TRUE(false);
  4542. return true;
  4543. },
  4544. [](bool success) { ASSERT_FALSE(success); });
  4545. });
  4546. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4547. auto se = detail::scope_exit([&] {
  4548. svr.stop();
  4549. listen_thread.join();
  4550. ASSERT_FALSE(svr.is_running());
  4551. });
  4552. svr.wait_until_ready();
  4553. Client cli("localhost", PORT);
  4554. {
  4555. auto res = cli.Get("/hi", [&](const char * /*data*/,
  4556. size_t /*data_length*/) { return false; });
  4557. ASSERT_FALSE(res);
  4558. }
  4559. {
  4560. auto res = cli.Get("/empty", [&](const char * /*data*/,
  4561. size_t /*data_length*/) { return false; });
  4562. ASSERT_TRUE(res);
  4563. }
  4564. }
  4565. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  4566. Server svr;
  4567. svr.set_error_handler([](Request const &, Response &res) -> void {
  4568. res.set_chunked_content_provider(
  4569. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4570. sink.os << "hello";
  4571. sink.os << "world";
  4572. sink.done();
  4573. return true;
  4574. });
  4575. });
  4576. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4577. auto se = detail::scope_exit([&] {
  4578. svr.stop();
  4579. listen_thread.join();
  4580. ASSERT_FALSE(svr.is_running());
  4581. });
  4582. svr.wait_until_ready();
  4583. Client cli("localhost", PORT);
  4584. auto res = cli.Get("/");
  4585. ASSERT_TRUE(res);
  4586. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4587. EXPECT_EQ("helloworld", res->body);
  4588. }
  4589. TEST(LongPollingTest, ClientCloseDetection) {
  4590. Server svr;
  4591. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  4592. res.set_chunked_content_provider(
  4593. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  4594. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  4595. sink.os << "hello";
  4596. auto count = 10;
  4597. while (count > 0 && sink.is_writable()) {
  4598. this_thread::sleep_for(chrono::milliseconds(10));
  4599. }
  4600. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  4601. return true;
  4602. });
  4603. });
  4604. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4605. auto se = detail::scope_exit([&] {
  4606. svr.stop();
  4607. listen_thread.join();
  4608. ASSERT_FALSE(svr.is_running());
  4609. });
  4610. svr.wait_until_ready();
  4611. Client cli("localhost", PORT);
  4612. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  4613. EXPECT_EQ("hello", string(data, data_length));
  4614. return false; // close the socket immediately.
  4615. });
  4616. ASSERT_FALSE(res);
  4617. }
  4618. TEST(GetWithParametersTest, GetWithParameters) {
  4619. Server svr;
  4620. svr.Get("/", [&](const Request &req, Response &) {
  4621. EXPECT_EQ("world", req.get_param_value("hello"));
  4622. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4623. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4624. });
  4625. svr.Get("/params", [&](const Request &req, Response &) {
  4626. EXPECT_EQ("world", req.get_param_value("hello"));
  4627. EXPECT_EQ("world2", req.get_param_value("hello2"));
  4628. EXPECT_EQ("world3", req.get_param_value("hello3"));
  4629. });
  4630. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  4631. EXPECT_EQ("resource-id", req.matches[1]);
  4632. EXPECT_EQ("foo", req.get_param_value("param1"));
  4633. EXPECT_EQ("bar", req.get_param_value("param2"));
  4634. });
  4635. svr.Get("/users/:id", [&](const Request &req, Response &) {
  4636. EXPECT_EQ("user-id", req.path_params.at("id"));
  4637. EXPECT_EQ("foo", req.get_param_value("param1"));
  4638. EXPECT_EQ("bar", req.get_param_value("param2"));
  4639. });
  4640. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4641. auto se = detail::scope_exit([&] {
  4642. svr.stop();
  4643. listen_thread.join();
  4644. ASSERT_FALSE(svr.is_running());
  4645. });
  4646. svr.wait_until_ready();
  4647. {
  4648. Client cli(HOST, PORT);
  4649. Params params;
  4650. params.emplace("hello", "world");
  4651. params.emplace("hello2", "world2");
  4652. params.emplace("hello3", "world3");
  4653. auto res = cli.Get("/", params, Headers{});
  4654. ASSERT_TRUE(res);
  4655. EXPECT_EQ(StatusCode::OK_200, res->status);
  4656. }
  4657. {
  4658. Client cli(HOST, PORT);
  4659. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  4660. ASSERT_TRUE(res);
  4661. EXPECT_EQ(StatusCode::OK_200, res->status);
  4662. }
  4663. {
  4664. Client cli(HOST, PORT);
  4665. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  4666. ASSERT_TRUE(res);
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. }
  4669. {
  4670. Client cli(HOST, PORT);
  4671. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  4672. ASSERT_TRUE(res);
  4673. EXPECT_EQ(StatusCode::OK_200, res->status);
  4674. }
  4675. }
  4676. TEST(GetWithParametersTest, GetWithParameters2) {
  4677. Server svr;
  4678. svr.Get("/", [&](const Request &req, Response &res) {
  4679. auto text = req.get_param_value("hello");
  4680. res.set_content(text, "text/plain");
  4681. });
  4682. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4683. auto se = detail::scope_exit([&] {
  4684. svr.stop();
  4685. listen_thread.join();
  4686. ASSERT_FALSE(svr.is_running());
  4687. });
  4688. svr.wait_until_ready();
  4689. Client cli("localhost", PORT);
  4690. Params params;
  4691. params.emplace("hello", "world");
  4692. std::string body;
  4693. auto res = cli.Get("/", params, Headers{},
  4694. [&](const char *data, size_t data_length) {
  4695. body.append(data, data_length);
  4696. return true;
  4697. });
  4698. ASSERT_TRUE(res);
  4699. EXPECT_EQ(StatusCode::OK_200, res->status);
  4700. EXPECT_EQ("world", body);
  4701. }
  4702. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  4703. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4704. auto host = "httpbin.org";
  4705. auto path = std::string{"/range/32"};
  4706. #else
  4707. auto host = "nghttp2.org";
  4708. auto path = std::string{"/httpbin/range/32"};
  4709. #endif
  4710. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4711. SSLClient cli(host);
  4712. #else
  4713. Client cli(host);
  4714. #endif
  4715. cli.set_default_headers({make_range_header({{1, 10}})});
  4716. cli.set_connection_timeout(5);
  4717. {
  4718. auto res = cli.Get(path);
  4719. ASSERT_TRUE(res);
  4720. EXPECT_EQ("bcdefghijk", res->body);
  4721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4722. }
  4723. {
  4724. auto res = cli.Get(path);
  4725. ASSERT_TRUE(res);
  4726. EXPECT_EQ("bcdefghijk", res->body);
  4727. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  4728. }
  4729. }
  4730. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  4731. Server svr;
  4732. svr.set_default_headers({{"Hello", "World"}});
  4733. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4734. res.set_content("ok", "text/plain");
  4735. });
  4736. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4737. auto se = detail::scope_exit([&] {
  4738. svr.stop();
  4739. listen_thread.join();
  4740. ASSERT_FALSE(svr.is_running());
  4741. });
  4742. svr.wait_until_ready();
  4743. Client cli("localhost", PORT);
  4744. auto res = cli.Get("/");
  4745. ASSERT_TRUE(res);
  4746. EXPECT_EQ(StatusCode::OK_200, res->status);
  4747. EXPECT_EQ("ok", res->body);
  4748. EXPECT_EQ("World", res->get_header_value("Hello"));
  4749. }
  4750. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4751. TEST(KeepAliveTest, ReadTimeoutSSL) {
  4752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4753. ASSERT_TRUE(svr.is_valid());
  4754. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  4755. std::this_thread::sleep_for(std::chrono::seconds(2));
  4756. res.set_content("a", "text/plain");
  4757. });
  4758. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  4759. res.set_content("b", "text/plain");
  4760. });
  4761. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4762. auto se = detail::scope_exit([&] {
  4763. svr.stop();
  4764. listen_thread.join();
  4765. ASSERT_FALSE(svr.is_running());
  4766. });
  4767. svr.wait_until_ready();
  4768. SSLClient cli("localhost", PORT);
  4769. cli.enable_server_certificate_verification(false);
  4770. cli.set_keep_alive(true);
  4771. cli.set_read_timeout(std::chrono::seconds(1));
  4772. auto resa = cli.Get("/a");
  4773. ASSERT_TRUE(!resa);
  4774. EXPECT_EQ(Error::Read, resa.error());
  4775. auto resb = cli.Get("/b");
  4776. ASSERT_TRUE(resb);
  4777. EXPECT_EQ(StatusCode::OK_200, resb->status);
  4778. EXPECT_EQ("b", resb->body);
  4779. }
  4780. #endif
  4781. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  4782. protected:
  4783. ServerTestWithAI_PASSIVE()
  4784. : cli_(HOST, PORT)
  4785. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4786. ,
  4787. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4788. #endif
  4789. {
  4790. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4791. cli_.enable_server_certificate_verification(false);
  4792. #endif
  4793. }
  4794. virtual void SetUp() {
  4795. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  4796. res.set_content("Hello World!", "text/plain");
  4797. });
  4798. t_ = thread(
  4799. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  4800. svr_.wait_until_ready();
  4801. }
  4802. virtual void TearDown() {
  4803. svr_.stop();
  4804. t_.join();
  4805. }
  4806. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4807. SSLClient cli_;
  4808. SSLServer svr_;
  4809. #else
  4810. Client cli_;
  4811. Server svr_;
  4812. #endif
  4813. thread t_;
  4814. };
  4815. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  4816. auto res = cli_.Get("/hi");
  4817. ASSERT_TRUE(res);
  4818. EXPECT_EQ(StatusCode::OK_200, res->status);
  4819. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  4820. EXPECT_EQ("Hello World!", res->body);
  4821. }
  4822. class ServerUpDownTest : public ::testing::Test {
  4823. protected:
  4824. ServerUpDownTest() : cli_(HOST, PORT) {}
  4825. virtual void SetUp() {
  4826. t_ = thread([&]() {
  4827. svr_.bind_to_any_port(HOST);
  4828. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4829. ASSERT_TRUE(svr_.listen_after_bind());
  4830. });
  4831. svr_.wait_until_ready();
  4832. }
  4833. virtual void TearDown() {
  4834. svr_.stop();
  4835. t_.join();
  4836. }
  4837. Client cli_;
  4838. Server svr_;
  4839. thread t_;
  4840. };
  4841. TEST_F(ServerUpDownTest, QuickStartStop) {
  4842. // Should not crash, especially when run with
  4843. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  4844. }
  4845. class PayloadMaxLengthTest : public ::testing::Test {
  4846. protected:
  4847. PayloadMaxLengthTest()
  4848. : cli_(HOST, PORT)
  4849. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4850. ,
  4851. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4852. #endif
  4853. {
  4854. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4855. cli_.enable_server_certificate_verification(false);
  4856. #endif
  4857. }
  4858. virtual void SetUp() {
  4859. svr_.set_payload_max_length(8);
  4860. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  4861. res.set_content("test", "text/plain");
  4862. });
  4863. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  4864. svr_.wait_until_ready();
  4865. }
  4866. virtual void TearDown() {
  4867. svr_.stop();
  4868. t_.join();
  4869. }
  4870. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4871. SSLClient cli_;
  4872. SSLServer svr_;
  4873. #else
  4874. Client cli_;
  4875. Server svr_;
  4876. #endif
  4877. thread t_;
  4878. };
  4879. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  4880. auto res = cli_.Post("/test", "123456789", "text/plain");
  4881. ASSERT_TRUE(res);
  4882. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4883. res = cli_.Post("/test", "12345678", "text/plain");
  4884. ASSERT_TRUE(res);
  4885. EXPECT_EQ(StatusCode::OK_200, res->status);
  4886. }
  4887. TEST(HostAndPortPropertiesTest, NoSSL) {
  4888. httplib::Client cli("www.google.com", 1234);
  4889. ASSERT_EQ("www.google.com", cli.host());
  4890. ASSERT_EQ(1234, cli.port());
  4891. }
  4892. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  4893. httplib::Client cli("www.google.com:1234");
  4894. ASSERT_EQ("www.google.com", cli.host());
  4895. ASSERT_EQ(1234, cli.port());
  4896. }
  4897. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4898. TEST(HostAndPortPropertiesTest, SSL) {
  4899. httplib::SSLClient cli("www.google.com");
  4900. ASSERT_EQ("www.google.com", cli.host());
  4901. ASSERT_EQ(443, cli.port());
  4902. }
  4903. #endif
  4904. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4905. TEST(SSLClientTest, UpdateCAStore) {
  4906. httplib::SSLClient httplib_client("www.google.com");
  4907. auto ca_store_1 = X509_STORE_new();
  4908. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  4909. nullptr);
  4910. httplib_client.set_ca_cert_store(ca_store_1);
  4911. auto ca_store_2 = X509_STORE_new();
  4912. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  4913. nullptr);
  4914. httplib_client.set_ca_cert_store(ca_store_2);
  4915. }
  4916. TEST(SSLClientTest, ServerNameIndication_Online) {
  4917. #ifdef CPPHTTPLIB_DEFAULT_HTTPBIN
  4918. auto host = "httpbin.org";
  4919. auto path = std::string{"/get"};
  4920. #else
  4921. auto host = "nghttp2.org";
  4922. auto path = std::string{"/httpbin/get"};
  4923. #endif
  4924. SSLClient cli(host, 443);
  4925. auto res = cli.Get(path);
  4926. ASSERT_TRUE(res);
  4927. ASSERT_EQ(StatusCode::OK_200, res->status);
  4928. }
  4929. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  4930. Client cli("https://google.com");
  4931. auto res = cli.Get("/");
  4932. ASSERT_TRUE(res);
  4933. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4934. }
  4935. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  4936. SSLClient cli("google.com");
  4937. cli.enable_server_certificate_verification(true);
  4938. cli.set_ca_cert_path("hello");
  4939. auto res = cli.Get("/");
  4940. ASSERT_TRUE(!res);
  4941. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  4942. }
  4943. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  4944. SSLClient cli("google.com");
  4945. cli.set_ca_cert_path(CA_CERT_FILE);
  4946. auto res = cli.Get("/");
  4947. ASSERT_TRUE(res);
  4948. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4949. }
  4950. TEST(SSLClientTest, ServerCertificateVerification4) {
  4951. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4952. ASSERT_TRUE(svr.is_valid());
  4953. svr.Get("/test", [&](const Request &, Response &res) {
  4954. res.set_content("test", "text/plain");
  4955. svr.stop();
  4956. ASSERT_TRUE(true);
  4957. });
  4958. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4959. auto se = detail::scope_exit([&] {
  4960. t.join();
  4961. ASSERT_FALSE(svr.is_running());
  4962. });
  4963. svr.wait_until_ready();
  4964. SSLClient cli("127.0.0.1", PORT);
  4965. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4966. cli.enable_server_certificate_verification(true);
  4967. cli.set_connection_timeout(30);
  4968. auto res = cli.Get("/test");
  4969. ASSERT_TRUE(res);
  4970. ASSERT_EQ(StatusCode::OK_200, res->status);
  4971. }
  4972. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  4973. std::string cert;
  4974. detail::read_file(CA_CERT_FILE, cert);
  4975. SSLClient cli("google.com");
  4976. cli.load_ca_cert_store(cert.data(), cert.size());
  4977. const auto res = cli.Get("/");
  4978. ASSERT_TRUE(res);
  4979. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  4980. }
  4981. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  4982. // clang-format off
  4983. static constexpr char cert[] =
  4984. "GlobalSign Root CA\n"
  4985. "==================\n"
  4986. "-----BEGIN CERTIFICATE-----\n"
  4987. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  4988. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  4989. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  4990. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  4991. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  4992. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  4993. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  4994. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  4995. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  4996. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  4997. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  4998. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  4999. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  5000. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  5001. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  5002. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  5003. "-----END CERTIFICATE-----\n";
  5004. // clang-format on
  5005. SSLClient cli("google.com");
  5006. cli.load_ca_cert_store(cert, sizeof(cert));
  5007. const auto res = cli.Get("/");
  5008. ASSERT_TRUE(res);
  5009. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  5010. }
  5011. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  5012. SSLClient cli("www.youtube.com");
  5013. cli.set_ca_cert_path(CA_CERT_FILE);
  5014. cli.enable_server_certificate_verification(true);
  5015. cli.set_follow_location(true);
  5016. auto res = cli.Get("/");
  5017. ASSERT_TRUE(res);
  5018. ASSERT_EQ(StatusCode::OK_200, res->status);
  5019. }
  5020. #if 0
  5021. TEST(SSLClientTest, SetInterfaceWithINET6) {
  5022. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  5023. ASSERT_TRUE(cli != nullptr);
  5024. cli->set_address_family(AF_INET6);
  5025. cli->set_interface("en0");
  5026. auto res = cli->Get("/get");
  5027. ASSERT_TRUE(res);
  5028. ASSERT_EQ(StatusCode::OK_200, res->status);
  5029. }
  5030. #endif
  5031. void ClientCertPresent(
  5032. const std::string &client_cert_file,
  5033. const std::string &client_private_key_file,
  5034. const std::string &client_encrypted_private_key_pass = std::string()) {
  5035. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5036. CLIENT_CA_CERT_DIR);
  5037. ASSERT_TRUE(svr.is_valid());
  5038. svr.Get("/test", [&](const Request &req, Response &res) {
  5039. res.set_content("test", "text/plain");
  5040. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5041. ASSERT_TRUE(peer_cert != nullptr);
  5042. auto subject_name = X509_get_subject_name(peer_cert);
  5043. ASSERT_TRUE(subject_name != nullptr);
  5044. std::string common_name;
  5045. {
  5046. char name[BUFSIZ];
  5047. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5048. name, sizeof(name));
  5049. common_name.assign(name, static_cast<size_t>(name_len));
  5050. }
  5051. EXPECT_EQ("Common Name", common_name);
  5052. X509_free(peer_cert);
  5053. });
  5054. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5055. auto se = detail::scope_exit([&] {
  5056. svr.stop();
  5057. t.join();
  5058. ASSERT_FALSE(svr.is_running());
  5059. });
  5060. svr.wait_until_ready();
  5061. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  5062. client_encrypted_private_key_pass);
  5063. cli.enable_server_certificate_verification(false);
  5064. cli.set_connection_timeout(30);
  5065. auto res = cli.Get("/test");
  5066. ASSERT_TRUE(res);
  5067. ASSERT_EQ(StatusCode::OK_200, res->status);
  5068. }
  5069. TEST(SSLClientServerTest, ClientCertPresent) {
  5070. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5071. }
  5072. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  5073. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5074. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5075. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5076. }
  5077. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  5078. void MemoryClientCertPresent(
  5079. const std::string &client_cert_file,
  5080. const std::string &client_private_key_file,
  5081. const std::string &client_encrypted_private_key_pass = std::string()) {
  5082. auto f = fopen(SERVER_CERT_FILE, "r+");
  5083. auto server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5084. fclose(f);
  5085. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  5086. auto server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  5087. fclose(f);
  5088. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  5089. auto client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5090. auto client_ca_cert_store = X509_STORE_new();
  5091. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  5092. X509_free(client_cert);
  5093. fclose(f);
  5094. f = fopen(client_cert_file.c_str(), "r+");
  5095. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  5096. fclose(f);
  5097. f = fopen(client_private_key_file.c_str(), "r+");
  5098. auto client_private_key = PEM_read_PrivateKey(
  5099. f, nullptr, nullptr, (void *)client_encrypted_private_key_pass.c_str());
  5100. fclose(f);
  5101. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  5102. ASSERT_TRUE(svr.is_valid());
  5103. svr.Get("/test", [&](const Request &req, Response &res) {
  5104. res.set_content("test", "text/plain");
  5105. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5106. ASSERT_TRUE(peer_cert != nullptr);
  5107. auto subject_name = X509_get_subject_name(peer_cert);
  5108. ASSERT_TRUE(subject_name != nullptr);
  5109. std::string common_name;
  5110. {
  5111. char name[BUFSIZ];
  5112. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5113. name, sizeof(name));
  5114. common_name.assign(name, static_cast<size_t>(name_len));
  5115. }
  5116. EXPECT_EQ("Common Name", common_name);
  5117. X509_free(peer_cert);
  5118. });
  5119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5120. auto se = detail::scope_exit([&] {
  5121. svr.stop();
  5122. t.join();
  5123. ASSERT_FALSE(svr.is_running());
  5124. });
  5125. svr.wait_until_ready();
  5126. SSLClient cli(HOST, PORT, client_cert, client_private_key,
  5127. client_encrypted_private_key_pass);
  5128. cli.enable_server_certificate_verification(false);
  5129. cli.set_connection_timeout(30);
  5130. auto res = cli.Get("/test");
  5131. ASSERT_TRUE(res);
  5132. ASSERT_EQ(StatusCode::OK_200, res->status);
  5133. X509_free(server_cert);
  5134. EVP_PKEY_free(server_private_key);
  5135. X509_free(client_cert);
  5136. EVP_PKEY_free(client_private_key);
  5137. }
  5138. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  5139. MemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5140. }
  5141. TEST(SSLClientServerTest, MemoryClientEncryptedCertPresent) {
  5142. MemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  5143. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  5144. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  5145. }
  5146. #endif
  5147. TEST(SSLClientServerTest, ClientCertMissing) {
  5148. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  5149. CLIENT_CA_CERT_DIR);
  5150. ASSERT_TRUE(svr.is_valid());
  5151. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  5152. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5153. auto se = detail::scope_exit([&] {
  5154. svr.stop();
  5155. t.join();
  5156. ASSERT_FALSE(svr.is_running());
  5157. });
  5158. svr.wait_until_ready();
  5159. SSLClient cli(HOST, PORT);
  5160. auto res = cli.Get("/test");
  5161. cli.set_connection_timeout(30);
  5162. ASSERT_TRUE(!res);
  5163. EXPECT_EQ(Error::SSLServerVerification, res.error());
  5164. }
  5165. TEST(SSLClientServerTest, TrustDirOptional) {
  5166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  5167. ASSERT_TRUE(svr.is_valid());
  5168. svr.Get("/test", [&](const Request &, Response &res) {
  5169. res.set_content("test", "text/plain");
  5170. });
  5171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5172. auto se = detail::scope_exit([&] {
  5173. svr.stop();
  5174. t.join();
  5175. ASSERT_FALSE(svr.is_running());
  5176. });
  5177. svr.wait_until_ready();
  5178. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5179. cli.enable_server_certificate_verification(false);
  5180. cli.set_connection_timeout(30);
  5181. auto res = cli.Get("/test");
  5182. ASSERT_TRUE(res);
  5183. ASSERT_EQ(StatusCode::OK_200, res->status);
  5184. }
  5185. TEST(SSLClientServerTest, SSLConnectTimeout) {
  5186. class NoListenSSLServer : public SSLServer {
  5187. public:
  5188. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  5189. const char *client_ca_cert_file_path,
  5190. const char *client_ca_cert_dir_path = nullptr)
  5191. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  5192. client_ca_cert_dir_path),
  5193. stop_(false) {}
  5194. std::atomic_bool stop_;
  5195. private:
  5196. bool process_and_close_socket(socket_t /*sock*/) override {
  5197. // Don't create SSL context
  5198. while (!stop_.load()) {
  5199. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5200. }
  5201. return true;
  5202. }
  5203. };
  5204. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  5205. CLIENT_CA_CERT_FILE);
  5206. ASSERT_TRUE(svr.is_valid());
  5207. svr.Get("/test", [&](const Request &, Response &res) {
  5208. res.set_content("test", "text/plain");
  5209. });
  5210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5211. auto se = detail::scope_exit([&] {
  5212. svr.stop_ = true;
  5213. svr.stop();
  5214. t.join();
  5215. ASSERT_FALSE(svr.is_running());
  5216. });
  5217. svr.wait_until_ready();
  5218. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5219. cli.enable_server_certificate_verification(false);
  5220. cli.set_connection_timeout(1);
  5221. auto res = cli.Get("/test");
  5222. ASSERT_TRUE(!res);
  5223. EXPECT_EQ(Error::SSLConnection, res.error());
  5224. }
  5225. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  5226. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  5227. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  5228. SSL_CTX_set_options(&ssl_ctx,
  5229. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  5230. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  5231. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  5232. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  5233. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  5234. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  5235. "ECDHE-DSS-AES128-SHA256:"
  5236. "ECDHE-RSA-AES256-SHA256:"
  5237. "ECDHE-DSS-AES256-SHA256:";
  5238. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  5239. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  5240. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  5241. SSL_FILETYPE_PEM) != 1) {
  5242. return false;
  5243. }
  5244. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  5245. CLIENT_CA_CERT_DIR);
  5246. SSL_CTX_set_verify(
  5247. &ssl_ctx,
  5248. SSL_VERIFY_PEER |
  5249. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  5250. nullptr);
  5251. return true;
  5252. };
  5253. SSLServer svr(setup_ssl_ctx_callback);
  5254. ASSERT_TRUE(svr.is_valid());
  5255. svr.Get("/test", [&](const Request &req, Response &res) {
  5256. res.set_content("test", "text/plain");
  5257. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  5258. ASSERT_TRUE(peer_cert != nullptr);
  5259. auto subject_name = X509_get_subject_name(peer_cert);
  5260. ASSERT_TRUE(subject_name != nullptr);
  5261. std::string common_name;
  5262. {
  5263. char name[BUFSIZ];
  5264. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  5265. name, sizeof(name));
  5266. common_name.assign(name, static_cast<size_t>(name_len));
  5267. }
  5268. EXPECT_EQ("Common Name", common_name);
  5269. X509_free(peer_cert);
  5270. });
  5271. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5272. auto se = detail::scope_exit([&] {
  5273. svr.stop();
  5274. t.join();
  5275. ASSERT_FALSE(svr.is_running());
  5276. });
  5277. svr.wait_until_ready();
  5278. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  5279. cli.enable_server_certificate_verification(false);
  5280. cli.set_connection_timeout(30);
  5281. auto res = cli.Get("/test");
  5282. ASSERT_TRUE(res);
  5283. ASSERT_EQ(StatusCode::OK_200, res->status);
  5284. }
  5285. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  5286. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  5287. // prepare large data
  5288. std::random_device seed_gen;
  5289. std::mt19937 random(seed_gen());
  5290. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  5291. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  5292. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  5293. // server
  5294. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5295. ASSERT_TRUE(svr.is_valid());
  5296. svr.Post("/binary", [&](const Request &req, Response &res) {
  5297. EXPECT_EQ(large_size_byte, req.body.size());
  5298. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  5299. res.set_content(req.body, "application/octet-stream");
  5300. });
  5301. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5302. auto se = detail::scope_exit([&] {
  5303. svr.stop();
  5304. listen_thread.join();
  5305. ASSERT_FALSE(svr.is_running());
  5306. });
  5307. svr.wait_until_ready();
  5308. // client POST
  5309. SSLClient cli("localhost", PORT);
  5310. cli.enable_server_certificate_verification(false);
  5311. cli.set_read_timeout(std::chrono::seconds(100));
  5312. cli.set_write_timeout(std::chrono::seconds(100));
  5313. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  5314. large_size_byte, "application/octet-stream");
  5315. // compare
  5316. EXPECT_EQ(StatusCode::OK_200, res->status);
  5317. EXPECT_EQ(large_size_byte, res->body.size());
  5318. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  5319. }
  5320. #endif
  5321. #ifdef _WIN32
  5322. TEST(CleanupTest, WSACleanup) {
  5323. int ret = WSACleanup();
  5324. ASSERT_EQ(0, ret);
  5325. }
  5326. #endif
  5327. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  5328. TEST(NoSSLSupport, SimpleInterface) {
  5329. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  5330. }
  5331. #endif
  5332. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5333. TEST(InvalidScheme, SimpleInterface) {
  5334. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  5335. }
  5336. #endif
  5337. TEST(NoScheme, SimpleInterface) {
  5338. Client cli("yahoo.com:80");
  5339. ASSERT_TRUE(cli.is_valid());
  5340. }
  5341. TEST(SendAPI, SimpleInterface_Online) {
  5342. Client cli("http://yahoo.com");
  5343. Request req;
  5344. req.method = "GET";
  5345. req.path = "/";
  5346. auto res = cli.send(req);
  5347. ASSERT_TRUE(res);
  5348. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5349. }
  5350. TEST(ClientImplMethods, GetSocketTest) {
  5351. httplib::Server svr;
  5352. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  5353. res.status = StatusCode::OK_200;
  5354. });
  5355. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  5356. auto se = detail::scope_exit([&] {
  5357. svr.stop();
  5358. thread.join();
  5359. ASSERT_FALSE(svr.is_running());
  5360. });
  5361. svr.wait_until_ready();
  5362. {
  5363. httplib::Client cli("http://127.0.0.1:3333");
  5364. cli.set_keep_alive(true);
  5365. // Use the behavior of cpp-httplib of opening the connection
  5366. // only when the first request happens. If that changes,
  5367. // this test would be obsolete.
  5368. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  5369. // This also implicitly tests the server. But other tests would fail much
  5370. // earlier than this one to be considered.
  5371. auto res = cli.Get("/");
  5372. ASSERT_TRUE(res);
  5373. EXPECT_EQ(StatusCode::OK_200, res->status);
  5374. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  5375. }
  5376. }
  5377. // Disabled due to out-of-memory problem on GitHub Actions
  5378. #ifdef _WIN64
  5379. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  5380. // allocate content size larger than 2GB in memory
  5381. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  5382. char *content = (char *)malloc(content_size);
  5383. ASSERT_TRUE(content);
  5384. Server svr;
  5385. svr.Get("/foo",
  5386. [=](const httplib::Request & /*req*/, httplib::Response &res) {
  5387. res.set_content(content, content_size, "application/octet-stream");
  5388. });
  5389. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  5390. auto se = detail::scope_exit([&] {
  5391. svr.stop();
  5392. listen_thread.join();
  5393. if (content) free(content);
  5394. ASSERT_FALSE(svr.is_running());
  5395. });
  5396. svr.wait_until_ready();
  5397. Client cli(HOST, PORT);
  5398. auto res = cli.Get("/foo");
  5399. ASSERT_TRUE(res);
  5400. EXPECT_EQ(StatusCode::OK_200, res->status);
  5401. EXPECT_EQ(content_size, res->body.length());
  5402. }
  5403. #endif
  5404. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  5405. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  5406. Client cli("http://yahoo.com");
  5407. auto res = cli.Get("/");
  5408. ASSERT_TRUE(res);
  5409. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5410. cli.set_follow_location(true);
  5411. res = cli.Get("/");
  5412. ASSERT_TRUE(res);
  5413. EXPECT_EQ(StatusCode::OK_200, res->status);
  5414. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5415. }
  5416. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  5417. Client cli("https://yahoo.com");
  5418. auto res = cli.Get("/");
  5419. ASSERT_TRUE(res);
  5420. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5421. cli.set_follow_location(true);
  5422. res = cli.Get("/");
  5423. ASSERT_TRUE(res);
  5424. EXPECT_EQ(StatusCode::OK_200, res->status);
  5425. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5426. }
  5427. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  5428. Client cli("https://yahoo.com");
  5429. auto res = cli.Get("/");
  5430. ASSERT_TRUE(res);
  5431. ASSERT_FALSE(!res);
  5432. ASSERT_TRUE(res);
  5433. ASSERT_FALSE(res == nullptr);
  5434. ASSERT_TRUE(res != nullptr);
  5435. EXPECT_EQ(Error::Success, res.error());
  5436. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  5437. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  5438. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5439. cli.set_follow_location(true);
  5440. res = cli.Get("/");
  5441. ASSERT_TRUE(res);
  5442. EXPECT_EQ(Error::Success, res.error());
  5443. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  5444. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  5445. EXPECT_EQ(StatusCode::OK_200, res->status);
  5446. EXPECT_EQ("https://www.yahoo.com/", res->location);
  5447. }
  5448. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  5449. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  5450. Client cli("https://cdnjs.cloudflare.com");
  5451. auto res =
  5452. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  5453. ASSERT_TRUE(res);
  5454. EXPECT_EQ(StatusCode::OK_200, res->status);
  5455. EXPECT_EQ(287630U, res->body.size());
  5456. EXPECT_EQ("application/javascript; charset=utf-8",
  5457. res->get_header_value("Content-Type"));
  5458. }
  5459. #endif
  5460. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  5461. Client cli("https://nghttp2.org");
  5462. cli.set_follow_location(true);
  5463. auto res =
  5464. cli.Get("/httpbin/"
  5465. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  5466. ASSERT_TRUE(res);
  5467. EXPECT_EQ(StatusCode::OK_200, res->status);
  5468. }
  5469. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  5470. Client cli("https://nghttp2.org");
  5471. cli.set_follow_location(true);
  5472. Params params;
  5473. params.emplace("url", "http://www.google.com");
  5474. params.emplace("status_code", "302");
  5475. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  5476. ASSERT_TRUE(res);
  5477. EXPECT_EQ(StatusCode::OK_200, res->status);
  5478. }
  5479. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  5480. Client cli("https://nghttp2.org");
  5481. cli.set_follow_location(true);
  5482. Params params;
  5483. params.emplace("url", "http://www.google.com");
  5484. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  5485. ASSERT_TRUE(res);
  5486. EXPECT_EQ(StatusCode::OK_200, res->status);
  5487. }
  5488. TEST(HttpToHttpsRedirectTest, CertFile) {
  5489. Server svr;
  5490. ASSERT_TRUE(svr.is_valid());
  5491. svr.Get("/index", [&](const Request &, Response &res) {
  5492. res.set_redirect("https://127.0.0.1:1235/index");
  5493. svr.stop();
  5494. });
  5495. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  5496. ASSERT_TRUE(ssl_svr.is_valid());
  5497. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  5498. res.set_content("test", "text/plain");
  5499. ssl_svr.stop();
  5500. });
  5501. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  5502. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  5503. auto se = detail::scope_exit([&] {
  5504. t2.join();
  5505. t.join();
  5506. ASSERT_FALSE(svr.is_running());
  5507. });
  5508. svr.wait_until_ready();
  5509. ssl_svr.wait_until_ready();
  5510. Client cli("127.0.0.1", PORT);
  5511. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  5512. cli.enable_server_certificate_verification(true);
  5513. cli.set_follow_location(true);
  5514. cli.set_connection_timeout(30);
  5515. auto res = cli.Get("/index");
  5516. ASSERT_TRUE(res);
  5517. ASSERT_EQ(StatusCode::OK_200, res->status);
  5518. }
  5519. TEST(MultipartFormDataTest, LargeData) {
  5520. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5521. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  5522. const ContentReader &content_reader) {
  5523. if (req.is_multipart_form_data()) {
  5524. MultipartFormDataItems files;
  5525. content_reader(
  5526. [&](const MultipartFormData &file) {
  5527. files.push_back(file);
  5528. return true;
  5529. },
  5530. [&](const char *data, size_t data_length) {
  5531. files.back().content.append(data, data_length);
  5532. return true;
  5533. });
  5534. EXPECT_TRUE(std::string(files[0].name) == "document");
  5535. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5536. EXPECT_TRUE(files[0].filename == "2MB_data");
  5537. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5538. EXPECT_TRUE(files[1].name == "hello");
  5539. EXPECT_TRUE(files[1].content == "world");
  5540. EXPECT_TRUE(files[1].filename == "");
  5541. EXPECT_TRUE(files[1].content_type == "");
  5542. } else {
  5543. std::string body;
  5544. content_reader([&](const char *data, size_t data_length) {
  5545. body.append(data, data_length);
  5546. return true;
  5547. });
  5548. }
  5549. });
  5550. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5551. auto se = detail::scope_exit([&] {
  5552. svr.stop();
  5553. t.join();
  5554. ASSERT_FALSE(svr.is_running());
  5555. });
  5556. svr.wait_until_ready();
  5557. {
  5558. std::string data(1024 * 1024 * 2, '.');
  5559. std::stringstream buffer;
  5560. buffer << data;
  5561. Client cli("https://localhost:8080");
  5562. cli.enable_server_certificate_verification(false);
  5563. MultipartFormDataItems items{
  5564. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5565. {"hello", "world", "", ""},
  5566. };
  5567. auto res = cli.Post("/post", items);
  5568. ASSERT_TRUE(res);
  5569. ASSERT_EQ(StatusCode::OK_200, res->status);
  5570. }
  5571. }
  5572. TEST(MultipartFormDataTest, DataProviderItems) {
  5573. std::random_device seed_gen;
  5574. std::mt19937 random(seed_gen());
  5575. std::string rand1;
  5576. rand1.resize(1000);
  5577. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  5578. std::string rand2;
  5579. rand2.resize(3000);
  5580. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  5581. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5582. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  5583. const ContentReader &content_reader) {
  5584. ASSERT_FALSE(req.is_multipart_form_data());
  5585. std::string body;
  5586. content_reader([&](const char *data, size_t data_length) {
  5587. body.append(data, data_length);
  5588. return true;
  5589. });
  5590. EXPECT_EQ(body, "");
  5591. });
  5592. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  5593. const ContentReader &content_reader) {
  5594. ASSERT_TRUE(req.is_multipart_form_data());
  5595. MultipartFormDataItems files;
  5596. content_reader(
  5597. [&](const MultipartFormData &file) {
  5598. files.push_back(file);
  5599. return true;
  5600. },
  5601. [&](const char *data, size_t data_length) {
  5602. files.back().content.append(data, data_length);
  5603. return true;
  5604. });
  5605. ASSERT_TRUE(files.size() == 2);
  5606. EXPECT_EQ(std::string(files[0].name), "name1");
  5607. EXPECT_EQ(files[0].content, "Testing123");
  5608. EXPECT_EQ(files[0].filename, "filename1");
  5609. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5610. EXPECT_EQ(files[1].name, "name2");
  5611. EXPECT_EQ(files[1].content, "Testing456");
  5612. EXPECT_EQ(files[1].filename, "");
  5613. EXPECT_EQ(files[1].content_type, "");
  5614. });
  5615. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  5616. const ContentReader &content_reader) {
  5617. ASSERT_TRUE(req.is_multipart_form_data());
  5618. MultipartFormDataItems files;
  5619. content_reader(
  5620. [&](const MultipartFormData &file) {
  5621. files.push_back(file);
  5622. return true;
  5623. },
  5624. [&](const char *data, size_t data_length) {
  5625. files.back().content.append(data, data_length);
  5626. return true;
  5627. });
  5628. ASSERT_TRUE(files.size() == 2);
  5629. EXPECT_EQ(files[0].name, "name3");
  5630. EXPECT_EQ(files[0].content, rand1);
  5631. EXPECT_EQ(files[0].filename, "filename3");
  5632. EXPECT_EQ(files[0].content_type, "");
  5633. EXPECT_EQ(files[1].name, "name4");
  5634. EXPECT_EQ(files[1].content, rand2);
  5635. EXPECT_EQ(files[1].filename, "filename4");
  5636. EXPECT_EQ(files[1].content_type, "");
  5637. });
  5638. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  5639. const ContentReader &content_reader) {
  5640. ASSERT_TRUE(req.is_multipart_form_data());
  5641. MultipartFormDataItems files;
  5642. content_reader(
  5643. [&](const MultipartFormData &file) {
  5644. files.push_back(file);
  5645. return true;
  5646. },
  5647. [&](const char *data, size_t data_length) {
  5648. files.back().content.append(data, data_length);
  5649. return true;
  5650. });
  5651. ASSERT_TRUE(files.size() == 4);
  5652. EXPECT_EQ(std::string(files[0].name), "name1");
  5653. EXPECT_EQ(files[0].content, "Testing123");
  5654. EXPECT_EQ(files[0].filename, "filename1");
  5655. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  5656. EXPECT_EQ(files[1].name, "name2");
  5657. EXPECT_EQ(files[1].content, "Testing456");
  5658. EXPECT_EQ(files[1].filename, "");
  5659. EXPECT_EQ(files[1].content_type, "");
  5660. EXPECT_EQ(files[2].name, "name3");
  5661. EXPECT_EQ(files[2].content, rand1);
  5662. EXPECT_EQ(files[2].filename, "filename3");
  5663. EXPECT_EQ(files[2].content_type, "");
  5664. EXPECT_EQ(files[3].name, "name4");
  5665. EXPECT_EQ(files[3].content, rand2);
  5666. EXPECT_EQ(files[3].filename, "filename4");
  5667. EXPECT_EQ(files[3].content_type, "");
  5668. });
  5669. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5670. auto se = detail::scope_exit([&] {
  5671. svr.stop();
  5672. t.join();
  5673. ASSERT_FALSE(svr.is_running());
  5674. });
  5675. svr.wait_until_ready();
  5676. {
  5677. Client cli("https://localhost:8080");
  5678. cli.enable_server_certificate_verification(false);
  5679. MultipartFormDataItems items{
  5680. {"name1", "Testing123", "filename1", "application/octet-stream"},
  5681. {"name2", "Testing456", "", ""}, // not a file
  5682. };
  5683. {
  5684. auto res = cli.Post("/post-none", {}, {}, {});
  5685. ASSERT_TRUE(res);
  5686. ASSERT_EQ(StatusCode::OK_200, res->status);
  5687. }
  5688. MultipartFormDataProviderItems providers;
  5689. {
  5690. auto res =
  5691. cli.Post("/post-items", {}, items, providers); // empty providers
  5692. ASSERT_TRUE(res);
  5693. ASSERT_EQ(StatusCode::OK_200, res->status);
  5694. }
  5695. providers.push_back({"name3",
  5696. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5697. // test the offset is given correctly at each step
  5698. if (!offset)
  5699. sink.os.write(rand1.data(), 30);
  5700. else if (offset == 30)
  5701. sink.os.write(rand1.data() + 30, 300);
  5702. else if (offset == 330)
  5703. sink.os.write(rand1.data() + 330, 670);
  5704. else if (offset == rand1.size())
  5705. sink.done();
  5706. return true;
  5707. },
  5708. "filename3",
  5709. {}});
  5710. providers.push_back({"name4",
  5711. [&](size_t offset, httplib::DataSink &sink) -> bool {
  5712. // test the offset is given correctly at each step
  5713. if (!offset)
  5714. sink.os.write(rand2.data(), 2000);
  5715. else if (offset == 2000)
  5716. sink.os.write(rand2.data() + 2000, 1);
  5717. else if (offset == 2001)
  5718. sink.os.write(rand2.data() + 2001, 999);
  5719. else if (offset == rand2.size())
  5720. sink.done();
  5721. return true;
  5722. },
  5723. "filename4",
  5724. {}});
  5725. {
  5726. auto res = cli.Post("/post-providers", {}, {}, providers);
  5727. ASSERT_TRUE(res);
  5728. ASSERT_EQ(StatusCode::OK_200, res->status);
  5729. }
  5730. {
  5731. auto res = cli.Post("/post-both", {}, items, providers);
  5732. ASSERT_TRUE(res);
  5733. ASSERT_EQ(StatusCode::OK_200, res->status);
  5734. }
  5735. }
  5736. }
  5737. TEST(MultipartFormDataTest, BadHeader) {
  5738. Server svr;
  5739. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5740. res.set_content("ok", "text/plain");
  5741. });
  5742. thread t = thread([&] { svr.listen(HOST, PORT); });
  5743. auto se = detail::scope_exit([&] {
  5744. svr.stop();
  5745. t.join();
  5746. ASSERT_FALSE(svr.is_running());
  5747. });
  5748. svr.wait_until_ready();
  5749. const std::string body =
  5750. "This is the preamble. It is to be ignored, though it\r\n"
  5751. "is a handy place for composition agents to include an\r\n"
  5752. "explanatory note to non-MIME conformant readers.\r\n"
  5753. "\r\n"
  5754. "\r\n"
  5755. "--simple boundary\r\n"
  5756. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5757. ": BAD...\r\n"
  5758. "\r\n"
  5759. "value1\r\n"
  5760. "--simple boundary\r\n"
  5761. "Content-Disposition: form-data; name=\"field2\"; "
  5762. "filename=\"example.txt\"\r\n"
  5763. "\r\n"
  5764. "value2\r\n"
  5765. "--simple boundary--\r\n"
  5766. "This is the epilogue. It is also to be ignored.\r\n";
  5767. std::string content_type =
  5768. R"(multipart/form-data; boundary="simple boundary")";
  5769. Client cli(HOST, PORT);
  5770. auto res = cli.Post("/post", body, content_type.c_str());
  5771. ASSERT_TRUE(res);
  5772. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5773. }
  5774. TEST(MultipartFormDataTest, WithPreamble) {
  5775. Server svr;
  5776. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  5777. res.set_content("ok", "text/plain");
  5778. });
  5779. thread t = thread([&] { svr.listen(HOST, PORT); });
  5780. auto se = detail::scope_exit([&] {
  5781. svr.stop();
  5782. t.join();
  5783. ASSERT_FALSE(svr.is_running());
  5784. });
  5785. svr.wait_until_ready();
  5786. const std::string body =
  5787. "This is the preamble. It is to be ignored, though it\r\n"
  5788. "is a handy place for composition agents to include an\r\n"
  5789. "explanatory note to non-MIME conformant readers.\r\n"
  5790. "\r\n"
  5791. "\r\n"
  5792. "--simple boundary\r\n"
  5793. "Content-Disposition: form-data; name=\"field1\"\r\n"
  5794. "\r\n"
  5795. "value1\r\n"
  5796. "--simple boundary\r\n"
  5797. "Content-Disposition: form-data; name=\"field2\"; "
  5798. "filename=\"example.txt\"\r\n"
  5799. "\r\n"
  5800. "value2\r\n"
  5801. "--simple boundary--\r\n"
  5802. "This is the epilogue. It is also to be ignored.\r\n";
  5803. std::string content_type =
  5804. R"(multipart/form-data; boundary="simple boundary")";
  5805. Client cli(HOST, PORT);
  5806. auto res = cli.Post("/post", body, content_type.c_str());
  5807. ASSERT_TRUE(res);
  5808. EXPECT_EQ(StatusCode::OK_200, res->status);
  5809. }
  5810. TEST(MultipartFormDataTest, PostCustomBoundary) {
  5811. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5812. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  5813. const ContentReader &content_reader) {
  5814. if (req.is_multipart_form_data()) {
  5815. MultipartFormDataItems files;
  5816. content_reader(
  5817. [&](const MultipartFormData &file) {
  5818. files.push_back(file);
  5819. return true;
  5820. },
  5821. [&](const char *data, size_t data_length) {
  5822. files.back().content.append(data, data_length);
  5823. return true;
  5824. });
  5825. EXPECT_TRUE(std::string(files[0].name) == "document");
  5826. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5827. EXPECT_TRUE(files[0].filename == "2MB_data");
  5828. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5829. EXPECT_TRUE(files[1].name == "hello");
  5830. EXPECT_TRUE(files[1].content == "world");
  5831. EXPECT_TRUE(files[1].filename == "");
  5832. EXPECT_TRUE(files[1].content_type == "");
  5833. } else {
  5834. std::string body;
  5835. content_reader([&](const char *data, size_t data_length) {
  5836. body.append(data, data_length);
  5837. return true;
  5838. });
  5839. }
  5840. });
  5841. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5842. auto se = detail::scope_exit([&] {
  5843. svr.stop();
  5844. t.join();
  5845. ASSERT_FALSE(svr.is_running());
  5846. });
  5847. svr.wait_until_ready();
  5848. {
  5849. std::string data(1024 * 1024 * 2, '.');
  5850. std::stringstream buffer;
  5851. buffer << data;
  5852. Client cli("https://localhost:8080");
  5853. cli.enable_server_certificate_verification(false);
  5854. MultipartFormDataItems items{
  5855. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5856. {"hello", "world", "", ""},
  5857. };
  5858. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  5859. ASSERT_TRUE(res);
  5860. ASSERT_EQ(StatusCode::OK_200, res->status);
  5861. }
  5862. }
  5863. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  5864. std::string data(1024 * 1024 * 2, '&');
  5865. std::stringstream buffer;
  5866. buffer << data;
  5867. Client cli("https://localhost:8080");
  5868. MultipartFormDataItems items{
  5869. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5870. {"hello", "world", "", ""},
  5871. };
  5872. for (const char &c : " \t\r\n") {
  5873. auto res =
  5874. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  5875. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5876. ASSERT_FALSE(res);
  5877. }
  5878. }
  5879. TEST(MultipartFormDataTest, PutFormData) {
  5880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5881. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  5882. const ContentReader &content_reader) {
  5883. if (req.is_multipart_form_data()) {
  5884. MultipartFormDataItems files;
  5885. content_reader(
  5886. [&](const MultipartFormData &file) {
  5887. files.push_back(file);
  5888. return true;
  5889. },
  5890. [&](const char *data, size_t data_length) {
  5891. files.back().content.append(data, data_length);
  5892. return true;
  5893. });
  5894. EXPECT_TRUE(std::string(files[0].name) == "document");
  5895. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5896. EXPECT_TRUE(files[0].filename == "2MB_data");
  5897. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5898. EXPECT_TRUE(files[1].name == "hello");
  5899. EXPECT_TRUE(files[1].content == "world");
  5900. EXPECT_TRUE(files[1].filename == "");
  5901. EXPECT_TRUE(files[1].content_type == "");
  5902. } else {
  5903. std::string body;
  5904. content_reader([&](const char *data, size_t data_length) {
  5905. body.append(data, data_length);
  5906. return true;
  5907. });
  5908. }
  5909. });
  5910. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5911. auto se = detail::scope_exit([&] {
  5912. svr.stop();
  5913. t.join();
  5914. ASSERT_FALSE(svr.is_running());
  5915. });
  5916. svr.wait_until_ready();
  5917. {
  5918. std::string data(1024 * 1024 * 2, '&');
  5919. std::stringstream buffer;
  5920. buffer << data;
  5921. Client cli("https://localhost:8080");
  5922. cli.enable_server_certificate_verification(false);
  5923. MultipartFormDataItems items{
  5924. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5925. {"hello", "world", "", ""},
  5926. };
  5927. auto res = cli.Put("/put", items);
  5928. ASSERT_TRUE(res);
  5929. ASSERT_EQ(StatusCode::OK_200, res->status);
  5930. }
  5931. }
  5932. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  5933. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5934. svr.Put("/put_customboundary",
  5935. [&](const Request &req, const Response & /*res*/,
  5936. const ContentReader &content_reader) {
  5937. if (req.is_multipart_form_data()) {
  5938. MultipartFormDataItems files;
  5939. content_reader(
  5940. [&](const MultipartFormData &file) {
  5941. files.push_back(file);
  5942. return true;
  5943. },
  5944. [&](const char *data, size_t data_length) {
  5945. files.back().content.append(data, data_length);
  5946. return true;
  5947. });
  5948. EXPECT_TRUE(std::string(files[0].name) == "document");
  5949. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  5950. EXPECT_TRUE(files[0].filename == "2MB_data");
  5951. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  5952. EXPECT_TRUE(files[1].name == "hello");
  5953. EXPECT_TRUE(files[1].content == "world");
  5954. EXPECT_TRUE(files[1].filename == "");
  5955. EXPECT_TRUE(files[1].content_type == "");
  5956. } else {
  5957. std::string body;
  5958. content_reader([&](const char *data, size_t data_length) {
  5959. body.append(data, data_length);
  5960. return true;
  5961. });
  5962. }
  5963. });
  5964. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  5965. auto se = detail::scope_exit([&] {
  5966. svr.stop();
  5967. t.join();
  5968. ASSERT_FALSE(svr.is_running());
  5969. });
  5970. svr.wait_until_ready();
  5971. {
  5972. std::string data(1024 * 1024 * 2, '&');
  5973. std::stringstream buffer;
  5974. buffer << data;
  5975. Client cli("https://localhost:8080");
  5976. cli.enable_server_certificate_verification(false);
  5977. MultipartFormDataItems items{
  5978. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5979. {"hello", "world", "", ""},
  5980. };
  5981. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  5982. ASSERT_TRUE(res);
  5983. ASSERT_EQ(StatusCode::OK_200, res->status);
  5984. }
  5985. }
  5986. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  5987. std::string data(1024 * 1024 * 2, '&');
  5988. std::stringstream buffer;
  5989. buffer << data;
  5990. Client cli("https://localhost:8080");
  5991. cli.enable_server_certificate_verification(false);
  5992. MultipartFormDataItems items{
  5993. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  5994. {"hello", "world", "", ""},
  5995. };
  5996. for (const char &c : " \t\r\n") {
  5997. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  5998. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5999. ASSERT_FALSE(res);
  6000. }
  6001. }
  6002. TEST(MultipartFormDataTest, AlternateFilename) {
  6003. auto handled = false;
  6004. Server svr;
  6005. svr.Post("/test", [&](const Request &req, Response &res) {
  6006. ASSERT_EQ(3u, req.files.size());
  6007. auto it = req.files.begin();
  6008. ASSERT_EQ("file1", it->second.name);
  6009. ASSERT_EQ("A.txt", it->second.filename);
  6010. ASSERT_EQ("text/plain", it->second.content_type);
  6011. ASSERT_EQ("Content of a.txt.\r\n", it->second.content);
  6012. ++it;
  6013. ASSERT_EQ("file2", it->second.name);
  6014. ASSERT_EQ("a.html", it->second.filename);
  6015. ASSERT_EQ("text/html", it->second.content_type);
  6016. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  6017. it->second.content);
  6018. ++it;
  6019. ASSERT_EQ("text", it->second.name);
  6020. ASSERT_EQ("", it->second.filename);
  6021. ASSERT_EQ("", it->second.content_type);
  6022. ASSERT_EQ("text default", it->second.content);
  6023. res.set_content("ok", "text/plain");
  6024. handled = true;
  6025. });
  6026. thread t = thread([&] { svr.listen(HOST, PORT); });
  6027. auto se = detail::scope_exit([&] {
  6028. svr.stop();
  6029. t.join();
  6030. ASSERT_FALSE(svr.is_running());
  6031. ASSERT_TRUE(handled);
  6032. });
  6033. svr.wait_until_ready();
  6034. auto req = "POST /test HTTP/1.1\r\n"
  6035. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6036. "Content-Length: 399\r\n"
  6037. "\r\n"
  6038. "----------\r\n"
  6039. "Content-Disposition: form-data; name=\"text\"\r\n"
  6040. "\r\n"
  6041. "text default\r\n"
  6042. "----------\r\n"
  6043. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  6044. "filename=\"a.txt\"; name=\"file1\"\r\n"
  6045. "Content-Type: text/plain\r\n"
  6046. "\r\n"
  6047. "Content of a.txt.\r\n"
  6048. "\r\n"
  6049. "----------\r\n"
  6050. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  6051. "\"a.html\"\r\n"
  6052. "Content-Type: text/html\r\n"
  6053. "\r\n"
  6054. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  6055. "\r\n"
  6056. "------------\r\n";
  6057. ASSERT_TRUE(send_request(1, req));
  6058. }
  6059. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  6060. auto handled = false;
  6061. Server svr;
  6062. svr.Post("/test", [&](const Request &req, Response &) {
  6063. ASSERT_EQ(2u, req.files.size());
  6064. auto it = req.files.begin();
  6065. ASSERT_EQ("text1", it->second.name);
  6066. ASSERT_EQ("text1", it->second.content);
  6067. ++it;
  6068. ASSERT_EQ("text2", it->second.name);
  6069. ASSERT_EQ("text2", it->second.content);
  6070. handled = true;
  6071. });
  6072. thread t = thread([&] { svr.listen(HOST, PORT); });
  6073. auto se = detail::scope_exit([&] {
  6074. svr.stop();
  6075. t.join();
  6076. ASSERT_FALSE(svr.is_running());
  6077. ASSERT_TRUE(handled);
  6078. });
  6079. svr.wait_until_ready();
  6080. auto req = "POST /test HTTP/1.1\r\n"
  6081. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6082. "Content-Length: 146\r\n"
  6083. "\r\n----------\r\n"
  6084. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6085. "\r\n"
  6086. "text1"
  6087. "\r\n----------\r\n"
  6088. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6089. "\r\n"
  6090. "text2"
  6091. "\r\n------------";
  6092. std::string resonse;
  6093. ASSERT_TRUE(send_request(1, req, &resonse));
  6094. ASSERT_EQ("200", resonse.substr(9, 3));
  6095. }
  6096. TEST(MultipartFormDataTest, ContentLength) {
  6097. auto handled = false;
  6098. Server svr;
  6099. svr.Post("/test", [&](const Request &req, Response &) {
  6100. ASSERT_EQ(2u, req.files.size());
  6101. auto it = req.files.begin();
  6102. ASSERT_EQ("text1", it->second.name);
  6103. ASSERT_EQ("text1", it->second.content);
  6104. ++it;
  6105. ASSERT_EQ("text2", it->second.name);
  6106. ASSERT_EQ("text2", it->second.content);
  6107. handled = true;
  6108. });
  6109. thread t = thread([&] { svr.listen(HOST, PORT); });
  6110. auto se = detail::scope_exit([&] {
  6111. svr.stop();
  6112. t.join();
  6113. ASSERT_FALSE(svr.is_running());
  6114. ASSERT_TRUE(handled);
  6115. });
  6116. svr.wait_until_ready();
  6117. auto req = "POST /test HTTP/1.1\r\n"
  6118. "Content-Type: multipart/form-data;boundary=--------\r\n"
  6119. "Content-Length: 167\r\n"
  6120. "\r\n----------\r\n"
  6121. "Content-Disposition: form-data; name=\"text1\"\r\n"
  6122. "Content-Length: 5\r\n"
  6123. "\r\n"
  6124. "text1"
  6125. "\r\n----------\r\n"
  6126. "Content-Disposition: form-data; name=\"text2\"\r\n"
  6127. "\r\n"
  6128. "text2"
  6129. "\r\n------------\r\n";
  6130. std::string resonse;
  6131. ASSERT_TRUE(send_request(1, req, &resonse));
  6132. ASSERT_EQ("200", resonse.substr(9, 3));
  6133. }
  6134. #endif
  6135. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  6136. static constexpr unsigned int number_of_tasks{1000000};
  6137. std::atomic_uint count{0};
  6138. std::unique_ptr<TaskQueue> task_queue{
  6139. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  6140. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6141. auto queued = task_queue->enqueue(
  6142. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  6143. EXPECT_TRUE(queued);
  6144. }
  6145. EXPECT_NO_THROW(task_queue->shutdown());
  6146. EXPECT_EQ(number_of_tasks, count.load());
  6147. }
  6148. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  6149. static constexpr unsigned int number_of_tasks{1000000};
  6150. static constexpr unsigned int qlimit{2};
  6151. unsigned int queued_count{0};
  6152. std::atomic_uint count{0};
  6153. std::unique_ptr<TaskQueue> task_queue{
  6154. new ThreadPool{/*num_threads=*/1, qlimit}};
  6155. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  6156. if (task_queue->enqueue(
  6157. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  6158. queued_count++;
  6159. }
  6160. }
  6161. EXPECT_NO_THROW(task_queue->shutdown());
  6162. EXPECT_EQ(queued_count, count.load());
  6163. EXPECT_TRUE(queued_count <= number_of_tasks);
  6164. EXPECT_TRUE(queued_count >= qlimit);
  6165. }
  6166. TEST(TaskQueueTest, MaxQueuedRequests) {
  6167. static constexpr unsigned int qlimit{3};
  6168. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, qlimit}};
  6169. std::condition_variable sem_cv;
  6170. std::mutex sem_mtx;
  6171. int credits = 0;
  6172. bool queued;
  6173. /* Fill up the queue with tasks that will block until we give them credits to
  6174. * complete. */
  6175. for (unsigned int n = 0; n <= qlimit;) {
  6176. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  6177. std::unique_lock<std::mutex> lock(sem_mtx);
  6178. while (credits <= 0) {
  6179. sem_cv.wait(lock);
  6180. }
  6181. /* Consume the credit and signal the test code if they are all gone. */
  6182. if (--credits == 0) { sem_cv.notify_one(); }
  6183. });
  6184. if (n < qlimit) {
  6185. /* The first qlimit enqueues must succeed. */
  6186. EXPECT_TRUE(queued);
  6187. } else {
  6188. /* The last one will succeed only when the worker thread
  6189. * starts and dequeues the first blocking task. Although
  6190. * not necessary for the correctness of this test, we sleep for
  6191. * a short while to avoid busy waiting. */
  6192. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6193. }
  6194. if (queued) { n++; }
  6195. }
  6196. /* Further enqueues must fail since the queue is full. */
  6197. for (auto i = 0; i < 4; i++) {
  6198. queued = task_queue->enqueue([] {});
  6199. EXPECT_FALSE(queued);
  6200. }
  6201. /* Give the credits to allow the previous tasks to complete. */
  6202. {
  6203. std::unique_lock<std::mutex> lock(sem_mtx);
  6204. credits += qlimit + 1;
  6205. }
  6206. sem_cv.notify_all();
  6207. /* Wait for all the credits to be consumed. */
  6208. {
  6209. std::unique_lock<std::mutex> lock(sem_mtx);
  6210. while (credits > 0) {
  6211. sem_cv.wait(lock);
  6212. }
  6213. }
  6214. /* Check that we are able again to enqueue at least qlimit tasks. */
  6215. for (unsigned int i = 0; i < qlimit; i++) {
  6216. queued = task_queue->enqueue([] {});
  6217. EXPECT_TRUE(queued);
  6218. }
  6219. EXPECT_NO_THROW(task_queue->shutdown());
  6220. }
  6221. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  6222. Server svr;
  6223. svr.Get("/", [](const Request & /*req*/, Response &res) {
  6224. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  6225. });
  6226. svr.Get("/hello", [](const Request &req, Response &res) {
  6227. res.set_content(req.get_param_value("key"), "text/plain");
  6228. });
  6229. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6230. auto se = detail::scope_exit([&] {
  6231. svr.stop();
  6232. thread.join();
  6233. ASSERT_FALSE(svr.is_running());
  6234. });
  6235. svr.wait_until_ready();
  6236. {
  6237. Client cli(HOST, PORT);
  6238. cli.set_follow_location(true);
  6239. auto res = cli.Get("/");
  6240. ASSERT_TRUE(res);
  6241. EXPECT_EQ(StatusCode::OK_200, res->status);
  6242. EXPECT_EQ("val&key2=val2", res->body);
  6243. }
  6244. }
  6245. TEST(VulnerabilityTest, CRLFInjection) {
  6246. Server svr;
  6247. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  6248. res.set_content("Hello 1", "text/plain");
  6249. });
  6250. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  6251. res.set_content("Hello 2", "text/plain");
  6252. });
  6253. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  6254. res.set_content("Hello 3", "text/plain");
  6255. });
  6256. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  6257. res.set_content("Hello 4", "text/plain");
  6258. });
  6259. svr.set_logger([](const Request &req, const Response & /*res*/) {
  6260. for (const auto &x : req.headers) {
  6261. auto key = x.first;
  6262. EXPECT_STRNE("evil", key.c_str());
  6263. }
  6264. });
  6265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6266. auto se = detail::scope_exit([&] {
  6267. svr.stop();
  6268. thread.join();
  6269. ASSERT_FALSE(svr.is_running());
  6270. });
  6271. svr.wait_until_ready();
  6272. {
  6273. Client cli(HOST, PORT);
  6274. cli.Post("/test1", "A=B",
  6275. "application/x-www-form-urlencoded\r\nevil: hello1");
  6276. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  6277. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  6278. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  6279. }
  6280. }
  6281. TEST(PathParamsTest, StaticMatch) {
  6282. const auto pattern = "/users/all";
  6283. detail::PathParamsMatcher matcher(pattern);
  6284. Request request;
  6285. request.path = "/users/all";
  6286. ASSERT_TRUE(matcher.match(request));
  6287. std::unordered_map<std::string, std::string> expected_params = {};
  6288. EXPECT_EQ(request.path_params, expected_params);
  6289. }
  6290. TEST(PathParamsTest, StaticMismatch) {
  6291. const auto pattern = "/users/all";
  6292. detail::PathParamsMatcher matcher(pattern);
  6293. Request request;
  6294. request.path = "/users/1";
  6295. ASSERT_FALSE(matcher.match(request));
  6296. }
  6297. TEST(PathParamsTest, SingleParamInTheMiddle) {
  6298. const auto pattern = "/users/:id/subscriptions";
  6299. detail::PathParamsMatcher matcher(pattern);
  6300. Request request;
  6301. request.path = "/users/42/subscriptions";
  6302. ASSERT_TRUE(matcher.match(request));
  6303. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6304. EXPECT_EQ(request.path_params, expected_params);
  6305. }
  6306. TEST(PathParamsTest, SingleParamInTheEnd) {
  6307. const auto pattern = "/users/:id";
  6308. detail::PathParamsMatcher matcher(pattern);
  6309. Request request;
  6310. request.path = "/users/24";
  6311. ASSERT_TRUE(matcher.match(request));
  6312. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  6313. EXPECT_EQ(request.path_params, expected_params);
  6314. }
  6315. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  6316. const auto pattern = "/users/:id/";
  6317. detail::PathParamsMatcher matcher(pattern);
  6318. Request request;
  6319. request.path = "/users/42/";
  6320. ASSERT_TRUE(matcher.match(request));
  6321. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  6322. EXPECT_EQ(request.path_params, expected_params);
  6323. }
  6324. TEST(PathParamsTest, EmptyParam) {
  6325. const auto pattern = "/users/:id/";
  6326. detail::PathParamsMatcher matcher(pattern);
  6327. Request request;
  6328. request.path = "/users//";
  6329. ASSERT_TRUE(matcher.match(request));
  6330. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  6331. EXPECT_EQ(request.path_params, expected_params);
  6332. }
  6333. TEST(PathParamsTest, FragmentMismatch) {
  6334. const auto pattern = "/users/:id/";
  6335. detail::PathParamsMatcher matcher(pattern);
  6336. Request request;
  6337. request.path = "/admins/24/";
  6338. ASSERT_FALSE(matcher.match(request));
  6339. }
  6340. TEST(PathParamsTest, ExtraFragments) {
  6341. const auto pattern = "/users/:id";
  6342. detail::PathParamsMatcher matcher(pattern);
  6343. Request request;
  6344. request.path = "/users/42/subscriptions";
  6345. ASSERT_FALSE(matcher.match(request));
  6346. }
  6347. TEST(PathParamsTest, MissingTrailingParam) {
  6348. const auto pattern = "/users/:id";
  6349. detail::PathParamsMatcher matcher(pattern);
  6350. Request request;
  6351. request.path = "/users";
  6352. ASSERT_FALSE(matcher.match(request));
  6353. }
  6354. TEST(PathParamsTest, MissingParamInTheMiddle) {
  6355. const auto pattern = "/users/:id/subscriptions";
  6356. detail::PathParamsMatcher matcher(pattern);
  6357. Request request;
  6358. request.path = "/users/subscriptions";
  6359. ASSERT_FALSE(matcher.match(request));
  6360. }
  6361. TEST(PathParamsTest, MultipleParams) {
  6362. const auto pattern = "/users/:userid/subscriptions/:subid";
  6363. detail::PathParamsMatcher matcher(pattern);
  6364. Request request;
  6365. request.path = "/users/42/subscriptions/2";
  6366. ASSERT_TRUE(matcher.match(request));
  6367. std::unordered_map<std::string, std::string> expected_params = {
  6368. {"userid", "42"}, {"subid", "2"}};
  6369. EXPECT_EQ(request.path_params, expected_params);
  6370. }
  6371. TEST(PathParamsTest, SequenceOfParams) {
  6372. const auto pattern = "/values/:x/:y/:z";
  6373. detail::PathParamsMatcher matcher(pattern);
  6374. Request request;
  6375. request.path = "/values/1/2/3";
  6376. ASSERT_TRUE(matcher.match(request));
  6377. std::unordered_map<std::string, std::string> expected_params = {
  6378. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  6379. EXPECT_EQ(request.path_params, expected_params);
  6380. }
  6381. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  6382. const auto pattern = "/prefix:suffix";
  6383. detail::PathParamsMatcher matcher(pattern);
  6384. Request request;
  6385. request.path = "/prefix:suffix";
  6386. ASSERT_TRUE(matcher.match(request));
  6387. const std::unordered_map<std::string, std::string> expected_params = {};
  6388. EXPECT_EQ(request.path_params, expected_params);
  6389. }
  6390. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  6391. // If ipv6 regex working, regex match codepath is taken.
  6392. // else port will default to 80 in Client impl
  6393. int clientImplMagicPort = 80;
  6394. int port = 4321;
  6395. // above ports must be different to avoid false negative
  6396. EXPECT_NE(clientImplMagicPort, port);
  6397. std::string ipV6TestURL = "http://[ff06::c3]";
  6398. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  6399. CLIENT_PRIVATE_KEY_FILE);
  6400. EXPECT_EQ(cli.port(), port);
  6401. }
  6402. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  6403. auto file_path = "./www/dir/index.html";
  6404. auto dir_path = "./www/dir";
  6405. EXPECT_TRUE(detail::is_file(file_path));
  6406. EXPECT_FALSE(detail::is_dir(file_path));
  6407. EXPECT_FALSE(detail::is_file(dir_path));
  6408. EXPECT_TRUE(detail::is_dir(dir_path));
  6409. }
  6410. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  6411. Server svr;
  6412. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  6413. EXPECT_EQ(res.status, 400);
  6414. });
  6415. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6416. auto se = detail::scope_exit([&] {
  6417. svr.stop();
  6418. thread.join();
  6419. ASSERT_FALSE(svr.is_running());
  6420. });
  6421. svr.wait_until_ready();
  6422. Client cli(HOST, PORT);
  6423. cli.Get("/test", {{"Test", "_\n\r_\n\r_"}});
  6424. }
  6425. #ifndef _WIN32
  6426. TEST(Expect100ContinueTest, ServerClosesConnection) {
  6427. static constexpr char reject[] = "Unauthorized";
  6428. static constexpr char accept[] = "Upload accepted";
  6429. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  6430. Server svr;
  6431. svr.set_expect_100_continue_handler(
  6432. [](const Request & /*req*/, Response &res) {
  6433. res.status = StatusCode::Unauthorized_401;
  6434. res.set_content(reject, "text/plain");
  6435. return res.status;
  6436. });
  6437. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  6438. res.set_content(accept, "text/plain");
  6439. });
  6440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6441. auto se = detail::scope_exit([&] {
  6442. svr.stop();
  6443. thread.join();
  6444. ASSERT_FALSE(svr.is_running());
  6445. });
  6446. svr.wait_until_ready();
  6447. {
  6448. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  6449. curl_easy_init(), &curl_easy_cleanup};
  6450. ASSERT_NE(curl, nullptr);
  6451. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  6452. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  6453. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  6454. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  6455. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  6456. &curl_slist_free_all};
  6457. ASSERT_NE(list, nullptr);
  6458. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  6459. struct read_data {
  6460. size_t read_size;
  6461. size_t total_size;
  6462. } data = {0, total_size};
  6463. using read_callback_t =
  6464. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6465. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  6466. void *userdata) -> size_t {
  6467. read_data *data = (read_data *)userdata;
  6468. if (!userdata || data->read_size >= data->total_size) { return 0; }
  6469. std::fill_n(ptr, size * nmemb, 'A');
  6470. data->read_size += size * nmemb;
  6471. return size * nmemb;
  6472. };
  6473. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  6474. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  6475. std::vector<char> buffer;
  6476. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  6477. using write_callback_t =
  6478. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  6479. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  6480. void *userdata) -> size_t {
  6481. std::vector<char> *buffer = (std::vector<char> *)userdata;
  6482. buffer->reserve(buffer->size() + size * nmemb + 1);
  6483. buffer->insert(buffer->end(), (char *)ptr, (char *)ptr + size * nmemb);
  6484. return size * nmemb;
  6485. };
  6486. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  6487. {
  6488. const auto res = curl_easy_perform(curl.get());
  6489. ASSERT_EQ(res, CURLE_OK);
  6490. }
  6491. {
  6492. auto response_code = long{};
  6493. const auto res =
  6494. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  6495. ASSERT_EQ(res, CURLE_OK);
  6496. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  6497. }
  6498. {
  6499. auto dl = curl_off_t{};
  6500. const auto res =
  6501. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  6502. ASSERT_EQ(res, CURLE_OK);
  6503. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  6504. }
  6505. {
  6506. buffer.push_back('\0');
  6507. ASSERT_STRCASEEQ(buffer.data(), reject);
  6508. }
  6509. }
  6510. }
  6511. #endif