test.cc 237 KB

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