2
0

test.cc 206 KB

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