test.cc 190 KB

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