test.cc 220 KB

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