test.cc 224 KB

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