test.cc 239 KB

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