test.cc 179 KB

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