test.cc 234 KB

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