test.cc 222 KB

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