test.cc 253 KB

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