test.cc 209 KB

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