test.cc 224 KB

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