test.cc 240 KB

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