test.cc 182 KB

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