2
0

test.cc 210 KB

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