test.cc 207 KB

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