test.cc 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165
  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::atomic_size_t count{4};
  2455. std::vector<std::thread> threads;
  2456. for (auto i = count.load(); i != 0; --i) {
  2457. threads.emplace_back([&]() {
  2458. auto res = cli_.Get("/streamed-cancel",
  2459. [&](const char *, uint64_t) { return true; });
  2460. --count;
  2461. ASSERT_TRUE(!res);
  2462. EXPECT_TRUE(res.error() == Error::Canceled ||
  2463. res.error() == Error::Read || res.error() == Error::Write);
  2464. });
  2465. }
  2466. std::this_thread::sleep_for(std::chrono::seconds(2));
  2467. while (count != 0) {
  2468. cli_.stop();
  2469. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2470. }
  2471. for (auto &t : threads) {
  2472. t.join();
  2473. }
  2474. }
  2475. TEST_F(ServerTest, GetWithRange1) {
  2476. auto res = cli_.Get("/with-range", {{make_range_header({{3, 5}})}});
  2477. ASSERT_TRUE(res);
  2478. EXPECT_EQ(206, res->status);
  2479. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  2480. EXPECT_EQ(true, res->has_header("Content-Range"));
  2481. EXPECT_EQ(std::string("def"), res->body);
  2482. }
  2483. TEST_F(ServerTest, GetWithRange2) {
  2484. auto res = cli_.Get("/with-range", {{make_range_header({{1, -1}})}});
  2485. ASSERT_TRUE(res);
  2486. EXPECT_EQ(206, res->status);
  2487. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  2488. EXPECT_EQ(true, res->has_header("Content-Range"));
  2489. EXPECT_EQ(std::string("bcdefg"), res->body);
  2490. }
  2491. TEST_F(ServerTest, GetWithRange3) {
  2492. auto res = cli_.Get("/with-range", {{make_range_header({{0, 0}})}});
  2493. ASSERT_TRUE(res);
  2494. EXPECT_EQ(206, res->status);
  2495. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  2496. EXPECT_EQ(true, res->has_header("Content-Range"));
  2497. EXPECT_EQ(std::string("a"), res->body);
  2498. }
  2499. TEST_F(ServerTest, GetWithRange4) {
  2500. auto res = cli_.Get("/with-range", {{make_range_header({{-1, 2}})}});
  2501. ASSERT_TRUE(res);
  2502. EXPECT_EQ(206, res->status);
  2503. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  2504. EXPECT_EQ(true, res->has_header("Content-Range"));
  2505. EXPECT_EQ(std::string("fg"), res->body);
  2506. }
  2507. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  2508. auto res = cli_.Get("/with-range", {{make_range_header({{10000, 20000}})}});
  2509. ASSERT_TRUE(res);
  2510. EXPECT_EQ(416, res->status);
  2511. }
  2512. TEST_F(ServerTest, GetWithRangeMultipart) {
  2513. auto res = cli_.Get("/with-range", {{make_range_header({{1, 2}, {4, 5}})}});
  2514. ASSERT_TRUE(res);
  2515. EXPECT_EQ(206, res->status);
  2516. EXPECT_EQ("269", res->get_header_value("Content-Length"));
  2517. EXPECT_EQ(false, res->has_header("Content-Range"));
  2518. EXPECT_EQ(269U, res->body.size());
  2519. }
  2520. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  2521. auto res =
  2522. cli_.Get("/with-range", {{make_range_header({{-1, 2}, {10000, 30000}})}});
  2523. ASSERT_TRUE(res);
  2524. EXPECT_EQ(416, res->status);
  2525. }
  2526. TEST_F(ServerTest, GetStreamedChunked) {
  2527. auto res = cli_.Get("/streamed-chunked");
  2528. ASSERT_TRUE(res);
  2529. EXPECT_EQ(200, res->status);
  2530. EXPECT_EQ(std::string("123456789"), res->body);
  2531. }
  2532. TEST_F(ServerTest, GetStreamedChunked2) {
  2533. auto res = cli_.Get("/streamed-chunked2");
  2534. ASSERT_TRUE(res);
  2535. EXPECT_EQ(200, res->status);
  2536. EXPECT_EQ(std::string("123456789"), res->body);
  2537. }
  2538. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  2539. auto res = cli_.Get("/streamed-chunked-with-trailer");
  2540. ASSERT_TRUE(res);
  2541. EXPECT_EQ(200, res->status);
  2542. EXPECT_EQ(std::string("123456789"), res->body);
  2543. EXPECT_EQ(std::string("DummyVal1"), res->get_header_value("Dummy1"));
  2544. EXPECT_EQ(std::string("DummyVal2"), res->get_header_value("Dummy2"));
  2545. }
  2546. TEST_F(ServerTest, LargeChunkedPost) {
  2547. Request req;
  2548. req.method = "POST";
  2549. req.path = "/large-chunked";
  2550. std::string host_and_port;
  2551. host_and_port += HOST;
  2552. host_and_port += ":";
  2553. host_and_port += std::to_string(PORT);
  2554. req.headers.emplace("Host", host_and_port.c_str());
  2555. req.headers.emplace("Accept", "*/*");
  2556. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  2557. req.headers.emplace("Content-Type", "text/plain");
  2558. req.headers.emplace("Content-Length", "0");
  2559. req.headers.emplace("Transfer-Encoding", "chunked");
  2560. std::string long_string(30 * 1024u, 'a');
  2561. std::string chunk = "7800\r\n" + long_string + "\r\n";
  2562. // Attempt to make a large enough post to exceed OS buffers, to test that
  2563. // the server handles short reads if the full chunk data isn't available.
  2564. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  2565. auto res = std::make_shared<Response>();
  2566. auto error = Error::Success;
  2567. auto ret = cli_.send(req, *res, error);
  2568. ASSERT_TRUE(ret);
  2569. EXPECT_EQ(200, res->status);
  2570. }
  2571. TEST_F(ServerTest, GetMethodRemoteAddr) {
  2572. auto res = cli_.Get("/remote_addr");
  2573. ASSERT_TRUE(res);
  2574. EXPECT_EQ(200, res->status);
  2575. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2576. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  2577. }
  2578. TEST_F(ServerTest, GetMethodLocalAddr) {
  2579. auto res = cli_.Get("/local_addr");
  2580. ASSERT_TRUE(res);
  2581. EXPECT_EQ(200, res->status);
  2582. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  2583. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  2584. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  2585. }
  2586. TEST_F(ServerTest, HTTPResponseSplitting) {
  2587. auto res = cli_.Get("/http_response_splitting");
  2588. ASSERT_TRUE(res);
  2589. EXPECT_EQ(200, res->status);
  2590. }
  2591. TEST_F(ServerTest, SlowRequest) {
  2592. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2593. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2594. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  2595. }
  2596. #if 0
  2597. TEST_F(ServerTest, SlowPost) {
  2598. char buffer[64 * 1024];
  2599. memset(buffer, 0x42, sizeof(buffer));
  2600. auto res = cli_.Post(
  2601. "/slowpost", 64 * 1024 * 1024,
  2602. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2603. auto ret = sink.write(buffer, sizeof(buffer));
  2604. EXPECT_TRUE(ret);
  2605. return true;
  2606. },
  2607. "text/plain");
  2608. ASSERT_TRUE(res);
  2609. EXPECT_EQ(200, res->status);
  2610. }
  2611. TEST_F(ServerTest, SlowPostFail) {
  2612. char buffer[64 * 1024];
  2613. memset(buffer, 0x42, sizeof(buffer));
  2614. cli_.set_write_timeout(std::chrono::seconds(0));
  2615. auto res = cli_.Post(
  2616. "/slowpost", 64 * 1024 * 1024,
  2617. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2618. sink.write(buffer, sizeof(buffer));
  2619. return true;
  2620. },
  2621. "text/plain");
  2622. ASSERT_TRUE(!res);
  2623. EXPECT_EQ(Error::Write, res.error());
  2624. }
  2625. #endif
  2626. TEST_F(ServerTest, Put) {
  2627. auto res = cli_.Put("/put", "PUT", "text/plain");
  2628. ASSERT_TRUE(res);
  2629. EXPECT_EQ(200, res->status);
  2630. EXPECT_EQ("PUT", res->body);
  2631. }
  2632. TEST_F(ServerTest, PutWithContentProvider) {
  2633. auto res = cli_.Put(
  2634. "/put", 3,
  2635. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2636. sink.os << "PUT";
  2637. return true;
  2638. },
  2639. "text/plain");
  2640. ASSERT_TRUE(res);
  2641. EXPECT_EQ(200, res->status);
  2642. EXPECT_EQ("PUT", res->body);
  2643. }
  2644. TEST_F(ServerTest, PostWithContentProviderAbort) {
  2645. auto res = cli_.Post(
  2646. "/post", 42,
  2647. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2648. return false;
  2649. },
  2650. "text/plain");
  2651. ASSERT_TRUE(!res);
  2652. EXPECT_EQ(Error::Canceled, res.error());
  2653. }
  2654. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  2655. auto res = cli_.Put(
  2656. "/put",
  2657. [](size_t /*offset*/, DataSink &sink) {
  2658. sink.os << "PUT";
  2659. sink.done();
  2660. return true;
  2661. },
  2662. "text/plain");
  2663. ASSERT_TRUE(res);
  2664. EXPECT_EQ(200, res->status);
  2665. EXPECT_EQ("PUT", res->body);
  2666. }
  2667. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  2668. auto res = cli_.Post(
  2669. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2670. "text/plain");
  2671. ASSERT_TRUE(!res);
  2672. EXPECT_EQ(Error::Canceled, res.error());
  2673. }
  2674. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2675. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  2676. cli_.set_compress(true);
  2677. auto res = cli_.Put(
  2678. "/put", 3,
  2679. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  2680. sink.os << "PUT";
  2681. return true;
  2682. },
  2683. "text/plain");
  2684. ASSERT_TRUE(res);
  2685. EXPECT_EQ(200, res->status);
  2686. EXPECT_EQ("PUT", res->body);
  2687. }
  2688. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  2689. cli_.set_compress(true);
  2690. auto res = cli_.Post(
  2691. "/post", 42,
  2692. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  2693. return false;
  2694. },
  2695. "text/plain");
  2696. ASSERT_TRUE(!res);
  2697. EXPECT_EQ(Error::Canceled, res.error());
  2698. }
  2699. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  2700. cli_.set_compress(true);
  2701. auto res = cli_.Put(
  2702. "/put",
  2703. [](size_t /*offset*/, DataSink &sink) {
  2704. sink.os << "PUT";
  2705. sink.done();
  2706. return true;
  2707. },
  2708. "text/plain");
  2709. ASSERT_TRUE(res);
  2710. EXPECT_EQ(200, res->status);
  2711. EXPECT_EQ("PUT", res->body);
  2712. }
  2713. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  2714. cli_.set_compress(true);
  2715. auto res = cli_.Post(
  2716. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  2717. "text/plain");
  2718. ASSERT_TRUE(!res);
  2719. EXPECT_EQ(Error::Canceled, res.error());
  2720. }
  2721. TEST_F(ServerTest, PutLargeFileWithGzip) {
  2722. cli_.set_compress(true);
  2723. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  2724. ASSERT_TRUE(res);
  2725. EXPECT_EQ(200, res->status);
  2726. EXPECT_EQ(LARGE_DATA, res->body);
  2727. }
  2728. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  2729. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  2730. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  2731. Client cli(s.c_str());
  2732. cli.enable_server_certificate_verification(false);
  2733. #else
  2734. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  2735. Client cli(s.c_str());
  2736. #endif
  2737. cli.set_compress(true);
  2738. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  2739. ASSERT_TRUE(res);
  2740. EXPECT_EQ(200, res->status);
  2741. EXPECT_EQ(LARGE_DATA, res->body);
  2742. EXPECT_EQ(101942u, res.get_request_header_value<uint64_t>("Content-Length"));
  2743. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  2744. }
  2745. TEST_F(ServerTest, PutContentWithDeflate) {
  2746. cli_.set_compress(false);
  2747. Headers headers;
  2748. headers.emplace("Content-Encoding", "deflate");
  2749. // PUT in deflate format:
  2750. auto res = cli_.Put("/put", headers,
  2751. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  2752. ASSERT_TRUE(res);
  2753. EXPECT_EQ(200, res->status);
  2754. EXPECT_EQ("PUT", res->body);
  2755. }
  2756. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  2757. Headers headers;
  2758. headers.emplace("Accept-Encoding", "gzip, deflate");
  2759. auto res = cli_.Get("/streamed-chunked", headers);
  2760. ASSERT_TRUE(res);
  2761. EXPECT_EQ(200, res->status);
  2762. EXPECT_EQ(std::string("123456789"), res->body);
  2763. }
  2764. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  2765. Headers headers;
  2766. headers.emplace("Accept-Encoding", "gzip, deflate");
  2767. auto res = cli_.Get("/streamed-chunked2", headers);
  2768. ASSERT_TRUE(res);
  2769. EXPECT_EQ(200, res->status);
  2770. EXPECT_EQ(std::string("123456789"), res->body);
  2771. }
  2772. TEST(GzipDecompressor, ChunkedDecompression) {
  2773. std::string data;
  2774. for (size_t i = 0; i < 32 * 1024; ++i) {
  2775. data.push_back(static_cast<char>('a' + i % 26));
  2776. }
  2777. std::string compressed_data;
  2778. {
  2779. httplib::detail::gzip_compressor compressor;
  2780. bool result = compressor.compress(
  2781. data.data(), data.size(),
  2782. /*last=*/true,
  2783. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  2784. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  2785. compressed_data_size);
  2786. return true;
  2787. });
  2788. ASSERT_TRUE(result);
  2789. }
  2790. std::string decompressed_data;
  2791. {
  2792. httplib::detail::gzip_decompressor decompressor;
  2793. // Chunk size is chosen specifically to have a decompressed chunk size equal
  2794. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  2795. size_t chunk_size = 130;
  2796. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  2797. chunk_begin += chunk_size) {
  2798. size_t current_chunk_size =
  2799. std::min(compressed_data.size() - chunk_begin, chunk_size);
  2800. bool result = decompressor.decompress(
  2801. compressed_data.data() + chunk_begin, current_chunk_size,
  2802. [&](const char *decompressed_data_chunk,
  2803. size_t decompressed_data_chunk_size) {
  2804. decompressed_data.insert(decompressed_data.size(),
  2805. decompressed_data_chunk,
  2806. decompressed_data_chunk_size);
  2807. return true;
  2808. });
  2809. ASSERT_TRUE(result);
  2810. }
  2811. }
  2812. ASSERT_EQ(data, decompressed_data);
  2813. }
  2814. #ifdef _WIN32
  2815. TEST(GzipDecompressor, LargeRandomData) {
  2816. // prepare large random data that is difficult to be compressed and is
  2817. // expected to have large size even when compressed
  2818. std::random_device seed_gen;
  2819. std::mt19937 random(seed_gen());
  2820. constexpr auto large_size_byte = 4294967296UL; // 4GiB
  2821. constexpr auto data_size = large_size_byte + 134217728UL; // + 128MiB
  2822. std::vector<std::uint32_t> data(data_size / sizeof(std::uint32_t));
  2823. std::generate(data.begin(), data.end(), [&]() { return random(); });
  2824. // compress data over 4GiB
  2825. std::string compressed_data;
  2826. compressed_data.reserve(large_size_byte + 536870912UL); // + 512MiB reserved
  2827. httplib::detail::gzip_compressor compressor;
  2828. auto result = compressor.compress(reinterpret_cast<const char *>(data.data()),
  2829. data.size() * sizeof(std::uint32_t), true,
  2830. [&](const char *data, size_t size) {
  2831. compressed_data.insert(
  2832. compressed_data.size(), data, size);
  2833. return true;
  2834. });
  2835. ASSERT_TRUE(result);
  2836. // FIXME: compressed data size is expected to be greater than 4GiB,
  2837. // but there is no guarantee
  2838. // ASSERT_TRUE(compressed_data.size() >= large_size_byte);
  2839. // decompress data over 4GiB
  2840. std::string decompressed_data;
  2841. decompressed_data.reserve(data_size);
  2842. httplib::detail::gzip_decompressor decompressor;
  2843. result = decompressor.decompress(
  2844. compressed_data.data(), compressed_data.size(),
  2845. [&](const char *data, size_t size) {
  2846. decompressed_data.insert(decompressed_data.size(), data, size);
  2847. return true;
  2848. });
  2849. ASSERT_TRUE(result);
  2850. // compare
  2851. ASSERT_EQ(data_size, decompressed_data.size());
  2852. ASSERT_TRUE(std::memcmp(data.data(), decompressed_data.data(), data_size) ==
  2853. 0);
  2854. }
  2855. #endif
  2856. #endif
  2857. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2858. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  2859. Headers headers;
  2860. headers.emplace("Accept-Encoding", "br");
  2861. auto res = cli_.Get("/streamed-chunked", headers);
  2862. ASSERT_TRUE(res);
  2863. EXPECT_EQ(200, res->status);
  2864. EXPECT_EQ(std::string("123456789"), res->body);
  2865. }
  2866. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  2867. Headers headers;
  2868. headers.emplace("Accept-Encoding", "br");
  2869. auto res = cli_.Get("/streamed-chunked2", headers);
  2870. ASSERT_TRUE(res);
  2871. EXPECT_EQ(200, res->status);
  2872. EXPECT_EQ(std::string("123456789"), res->body);
  2873. }
  2874. #endif
  2875. TEST_F(ServerTest, Patch) {
  2876. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  2877. ASSERT_TRUE(res);
  2878. EXPECT_EQ(200, res->status);
  2879. EXPECT_EQ("PATCH", res->body);
  2880. }
  2881. TEST_F(ServerTest, Delete) {
  2882. auto res = cli_.Delete("/delete");
  2883. ASSERT_TRUE(res);
  2884. EXPECT_EQ(200, res->status);
  2885. EXPECT_EQ("DELETE", res->body);
  2886. }
  2887. TEST_F(ServerTest, DeleteContentReceiver) {
  2888. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  2889. ASSERT_TRUE(res);
  2890. EXPECT_EQ(200, res->status);
  2891. EXPECT_EQ("content", res->body);
  2892. }
  2893. TEST_F(ServerTest, Options) {
  2894. auto res = cli_.Options("*");
  2895. ASSERT_TRUE(res);
  2896. EXPECT_EQ(200, res->status);
  2897. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  2898. EXPECT_TRUE(res->body.empty());
  2899. }
  2900. TEST_F(ServerTest, URL) {
  2901. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  2902. ASSERT_TRUE(res);
  2903. EXPECT_EQ(200, res->status);
  2904. }
  2905. TEST_F(ServerTest, ArrayParam) {
  2906. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  2907. ASSERT_TRUE(res);
  2908. EXPECT_EQ(200, res->status);
  2909. }
  2910. TEST_F(ServerTest, NoMultipleHeaders) {
  2911. Headers headers = {{"Content-Length", "5"}};
  2912. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  2913. "text/plain");
  2914. ASSERT_TRUE(res);
  2915. EXPECT_EQ(200, res->status);
  2916. }
  2917. TEST_F(ServerTest, PostContentReceiver) {
  2918. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2919. ASSERT_TRUE(res);
  2920. ASSERT_EQ(200, res->status);
  2921. ASSERT_EQ("content", res->body);
  2922. }
  2923. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  2924. MultipartFormDataItems items = {
  2925. {"text1", "text default", "", ""},
  2926. {"text2", "aωb", "", ""},
  2927. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2928. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2929. {"file3", "", "", "application/octet-stream"},
  2930. };
  2931. auto res = cli_.Post("/content_receiver", items);
  2932. ASSERT_TRUE(res);
  2933. EXPECT_EQ(200, res->status);
  2934. }
  2935. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  2936. MultipartFormDataItems items = {
  2937. {"text1", "text default", "", ""},
  2938. {"text2", "aωb", "", ""},
  2939. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  2940. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  2941. {"file3", "", "", "application/octet-stream"},
  2942. };
  2943. auto boundary = std::string("+++++");
  2944. std::string body;
  2945. for (const auto &item : items) {
  2946. body += "--" + boundary + "\r\n";
  2947. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  2948. if (!item.filename.empty()) {
  2949. body += "; filename=\"" + item.filename + "\"";
  2950. }
  2951. body += "\r\n";
  2952. if (!item.content_type.empty()) {
  2953. body += "Content-Type: " + item.content_type + "\r\n";
  2954. }
  2955. body += "\r\n";
  2956. body += item.content + "\r\n";
  2957. }
  2958. body += "--" + boundary + "--\r\n";
  2959. std::string content_type = "multipart/form-data; boundary=" + boundary;
  2960. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  2961. ASSERT_TRUE(res);
  2962. EXPECT_EQ(200, res->status);
  2963. }
  2964. TEST_F(ServerTest, PostContentReceiverGzip) {
  2965. cli_.set_compress(true);
  2966. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  2967. ASSERT_TRUE(res);
  2968. ASSERT_EQ(200, res->status);
  2969. ASSERT_EQ("content", res->body);
  2970. }
  2971. TEST_F(ServerTest, PutContentReceiver) {
  2972. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  2973. ASSERT_TRUE(res);
  2974. ASSERT_EQ(200, res->status);
  2975. ASSERT_EQ("content", res->body);
  2976. }
  2977. TEST_F(ServerTest, PatchContentReceiver) {
  2978. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  2979. ASSERT_TRUE(res);
  2980. ASSERT_EQ(200, res->status);
  2981. ASSERT_EQ("content", res->body);
  2982. }
  2983. TEST_F(ServerTest, PostQueryStringAndBody) {
  2984. auto res =
  2985. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  2986. ASSERT_TRUE(res);
  2987. ASSERT_EQ(200, res->status);
  2988. }
  2989. TEST_F(ServerTest, HTTP2Magic) {
  2990. Request req;
  2991. req.method = "PRI";
  2992. req.path = "*";
  2993. req.body = "SM";
  2994. auto res = std::make_shared<Response>();
  2995. auto error = Error::Success;
  2996. auto ret = cli_.send(req, *res, error);
  2997. ASSERT_TRUE(ret);
  2998. EXPECT_EQ(400, res->status);
  2999. }
  3000. TEST_F(ServerTest, KeepAlive) {
  3001. auto res = cli_.Get("/hi");
  3002. ASSERT_TRUE(res);
  3003. EXPECT_EQ(200, res->status);
  3004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3005. EXPECT_EQ("Hello World!", res->body);
  3006. res = cli_.Get("/hi");
  3007. ASSERT_TRUE(res);
  3008. EXPECT_EQ(200, res->status);
  3009. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3010. EXPECT_EQ("Hello World!", res->body);
  3011. res = cli_.Get("/hi");
  3012. ASSERT_TRUE(res);
  3013. EXPECT_EQ(200, res->status);
  3014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3015. EXPECT_EQ("Hello World!", res->body);
  3016. res = cli_.Get("/not-exist");
  3017. ASSERT_TRUE(res);
  3018. EXPECT_EQ(404, res->status);
  3019. res = cli_.Post("/empty", "", "text/plain");
  3020. ASSERT_TRUE(res);
  3021. EXPECT_EQ(200, res->status);
  3022. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3023. EXPECT_EQ("empty", res->body);
  3024. EXPECT_EQ("close", res->get_header_value("Connection"));
  3025. res = cli_.Post(
  3026. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  3027. "text/plain");
  3028. ASSERT_TRUE(res);
  3029. EXPECT_EQ(200, res->status);
  3030. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3031. EXPECT_EQ("empty", res->body);
  3032. cli_.set_keep_alive(false);
  3033. res = cli_.Get("/last-request");
  3034. ASSERT_TRUE(res);
  3035. EXPECT_EQ(200, res->status);
  3036. EXPECT_EQ("close", res->get_header_value("Connection"));
  3037. }
  3038. TEST_F(ServerTest, TooManyRedirect) {
  3039. cli_.set_follow_location(true);
  3040. auto res = cli_.Get("/redirect/0");
  3041. ASSERT_TRUE(!res);
  3042. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3043. }
  3044. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  3045. TEST_F(ServerTest, Gzip) {
  3046. Headers headers;
  3047. headers.emplace("Accept-Encoding", "gzip, deflate");
  3048. auto res = cli_.Get("/compress", headers);
  3049. ASSERT_TRUE(res);
  3050. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3052. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3054. "7890123456789012345678901234567890",
  3055. res->body);
  3056. EXPECT_EQ(200, res->status);
  3057. }
  3058. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  3059. auto res = cli_.Get("/compress");
  3060. ASSERT_TRUE(res);
  3061. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3062. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3063. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3064. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3065. "7890123456789012345678901234567890",
  3066. res->body);
  3067. EXPECT_EQ(200, res->status);
  3068. }
  3069. TEST_F(ServerTest, GzipWithContentReceiver) {
  3070. Headers headers;
  3071. headers.emplace("Accept-Encoding", "gzip, deflate");
  3072. std::string body;
  3073. auto res = cli_.Get("/compress", headers,
  3074. [&](const char *data, uint64_t data_length) {
  3075. EXPECT_EQ(100U, data_length);
  3076. body.append(data, data_length);
  3077. return true;
  3078. });
  3079. ASSERT_TRUE(res);
  3080. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3081. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3082. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3083. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3084. "7890123456789012345678901234567890",
  3085. body);
  3086. EXPECT_EQ(200, res->status);
  3087. }
  3088. TEST_F(ServerTest, GzipWithoutDecompressing) {
  3089. Headers headers;
  3090. headers.emplace("Accept-Encoding", "gzip, deflate");
  3091. cli_.set_decompress(false);
  3092. auto res = cli_.Get("/compress", headers);
  3093. ASSERT_TRUE(res);
  3094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  3095. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3096. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  3097. EXPECT_EQ(33U, res->body.size());
  3098. EXPECT_EQ(200, res->status);
  3099. }
  3100. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  3101. std::string body;
  3102. auto res = cli_.Get("/compress", [&](const char *data, uint64_t data_length) {
  3103. EXPECT_EQ(100U, data_length);
  3104. body.append(data, data_length);
  3105. return true;
  3106. });
  3107. ASSERT_TRUE(res);
  3108. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  3109. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3110. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3111. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3112. "7890123456789012345678901234567890",
  3113. body);
  3114. EXPECT_EQ(200, res->status);
  3115. }
  3116. TEST_F(ServerTest, NoGzip) {
  3117. Headers headers;
  3118. headers.emplace("Accept-Encoding", "gzip, deflate");
  3119. auto res = cli_.Get("/nocompress", headers);
  3120. ASSERT_TRUE(res);
  3121. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3122. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3123. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3124. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3125. "7890123456789012345678901234567890",
  3126. res->body);
  3127. EXPECT_EQ(200, res->status);
  3128. }
  3129. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  3130. Headers headers;
  3131. headers.emplace("Accept-Encoding", "gzip, deflate");
  3132. std::string body;
  3133. auto res = cli_.Get("/nocompress", headers,
  3134. [&](const char *data, uint64_t data_length) {
  3135. EXPECT_EQ(100U, data_length);
  3136. body.append(data, data_length);
  3137. return true;
  3138. });
  3139. ASSERT_TRUE(res);
  3140. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  3141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  3142. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  3143. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3144. "7890123456789012345678901234567890",
  3145. body);
  3146. EXPECT_EQ(200, res->status);
  3147. }
  3148. TEST_F(ServerTest, MultipartFormDataGzip) {
  3149. MultipartFormDataItems items = {
  3150. {"key1", "test", "", ""},
  3151. {"key2", "--abcdefg123", "", ""},
  3152. };
  3153. cli_.set_compress(true);
  3154. auto res = cli_.Post("/compress-multipart", items);
  3155. ASSERT_TRUE(res);
  3156. EXPECT_EQ(200, res->status);
  3157. }
  3158. #endif
  3159. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  3160. TEST_F(ServerTest, Brotli) {
  3161. Headers headers;
  3162. headers.emplace("Accept-Encoding", "br");
  3163. auto res = cli_.Get("/compress", headers);
  3164. ASSERT_TRUE(res);
  3165. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  3166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3167. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  3168. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  3169. "7890123456789012345678901234567890",
  3170. res->body);
  3171. EXPECT_EQ(200, res->status);
  3172. }
  3173. #endif
  3174. // Sends a raw request to a server listening at HOST:PORT.
  3175. static bool send_request(time_t read_timeout_sec, const std::string &req,
  3176. std::string *resp = nullptr) {
  3177. auto error = Error::Success;
  3178. auto client_sock = detail::create_client_socket(
  3179. HOST, "", PORT, AF_UNSPEC, false, nullptr,
  3180. /*connection_timeout_sec=*/5, 0,
  3181. /*read_timeout_sec=*/5, 0,
  3182. /*write_timeout_sec=*/5, 0, std::string(), error);
  3183. if (client_sock == INVALID_SOCKET) { return false; }
  3184. auto ret = detail::process_client_socket(
  3185. client_sock, read_timeout_sec, 0, 0, 0, [&](Stream &strm) {
  3186. if (req.size() !=
  3187. static_cast<size_t>(strm.write(req.data(), req.size()))) {
  3188. return false;
  3189. }
  3190. char buf[512];
  3191. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  3192. while (line_reader.getline()) {
  3193. if (resp) { *resp += line_reader.ptr(); }
  3194. }
  3195. return true;
  3196. });
  3197. detail::close_socket(client_sock);
  3198. return ret;
  3199. }
  3200. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  3201. Server svr;
  3202. std::string header_value;
  3203. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  3204. header_value = req.get_header_value("foo");
  3205. res.set_content("ok", "text/plain");
  3206. });
  3207. thread t = thread([&] { svr.listen(HOST, PORT); });
  3208. auto se = detail::scope_exit([&] {
  3209. svr.stop();
  3210. t.join();
  3211. ASSERT_FALSE(svr.is_running());
  3212. });
  3213. while (!svr.is_running()) {
  3214. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3215. }
  3216. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  3217. // like characters are not treated the same - use vertical tab and escape.
  3218. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  3219. "foo: \t \v bar \x1B\t \r\n"
  3220. "Connection: close\r\n"
  3221. "\r\n";
  3222. ASSERT_TRUE(send_request(5, req));
  3223. EXPECT_EQ(header_value, "\v bar \x1B");
  3224. }
  3225. // Sends a raw request and verifies that there isn't a crash or exception.
  3226. static void test_raw_request(const std::string &req,
  3227. std::string *out = nullptr) {
  3228. Server svr;
  3229. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3230. res.set_content("ok", "text/plain");
  3231. });
  3232. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  3233. res.set_content("ok", "text/plain");
  3234. });
  3235. // Server read timeout must be longer than the client read timeout for the
  3236. // bug to reproduce, probably to force the server to process a request
  3237. // without a trailing blank line.
  3238. const time_t client_read_timeout_sec = 1;
  3239. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  3240. bool listen_thread_ok = false;
  3241. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  3242. auto se = detail::scope_exit([&] {
  3243. svr.stop();
  3244. t.join();
  3245. ASSERT_FALSE(svr.is_running());
  3246. EXPECT_TRUE(listen_thread_ok);
  3247. });
  3248. while (!svr.is_running()) {
  3249. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3250. }
  3251. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  3252. }
  3253. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  3254. // A certain header line causes an exception if the header property is parsed
  3255. // naively with a single regex. This occurs with libc++ but not libstdc++.
  3256. test_raw_request(
  3257. "GET /hi HTTP/1.1\r\n"
  3258. " : "
  3259. " "
  3260. " ");
  3261. }
  3262. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  3263. // A certain header line causes an exception if the header property *name* is
  3264. // parsed with a regular expression starting with "(.+?):" - this is a non-
  3265. // greedy matcher and requires backtracking when there are a lot of ":"
  3266. // characters.
  3267. // This occurs with libc++ but not libstdc++.
  3268. test_raw_request(
  3269. "GET /hi HTTP/1.1\r\n"
  3270. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  3271. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3272. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  3273. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  3274. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  3275. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  3276. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  3277. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  3278. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3279. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3280. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  3281. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3282. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  3283. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  3284. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  3285. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  3286. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  3287. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  3288. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  3289. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  3290. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  3291. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  3292. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  3293. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  3294. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  3295. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  3296. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  3297. "&&&%%%");
  3298. }
  3299. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  3300. // Make sure this doesn't crash the server.
  3301. // In a previous version of the header line regex, the "\r" rendered the line
  3302. // unparsable and the regex engine repeatedly backtracked, trying to look for
  3303. // a new position where the leading white space ended and the field value
  3304. // began.
  3305. // The crash occurs with libc++ but not libstdc++.
  3306. test_raw_request("GET /hi HTTP/1.1\r\n"
  3307. "a:" +
  3308. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  3309. "\r\n"
  3310. "\r\n");
  3311. }
  3312. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  3313. std::string out;
  3314. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3315. "Content-Type: text/plain\r\n"
  3316. "Transfer-Encoding: chunked\r\n"
  3317. "\r\n"
  3318. "nothex\r\n",
  3319. &out);
  3320. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3321. }
  3322. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  3323. std::string out;
  3324. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3325. "Content-Type: text/plain\r\n"
  3326. "Transfer-Encoding: chunked\r\n"
  3327. "\r\n"
  3328. "3\r\n"
  3329. "xyz\r\n"
  3330. "NaN\r\n",
  3331. &out);
  3332. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3333. }
  3334. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  3335. std::string out;
  3336. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  3337. "Content-Type: text/plain\r\n"
  3338. "Transfer-Encoding: chunked\r\n"
  3339. "\r\n"
  3340. // Length is too large for 64 bits.
  3341. "1ffffffffffffffff\r\n"
  3342. "xyz\r\n",
  3343. &out);
  3344. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3345. }
  3346. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  3347. test_raw_request("GET /hi HTTP/1.1\r\n"
  3348. "Content-Type: text/plain\r\n\r");
  3349. }
  3350. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  3351. std::string out;
  3352. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  3353. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  3354. }
  3355. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  3356. Server svr;
  3357. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  3358. res.set_header("Cache-Control", "no-cache");
  3359. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  3360. DataSink &sink) {
  3361. char buffer[27];
  3362. auto size = static_cast<size_t>(sprintf(buffer, "data:%zd\n\n", offset));
  3363. auto ret = sink.write(buffer, size);
  3364. EXPECT_TRUE(ret);
  3365. std::this_thread::sleep_for(std::chrono::seconds(1));
  3366. return true;
  3367. });
  3368. });
  3369. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3370. while (!svr.is_running()) {
  3371. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3372. }
  3373. Client client(HOST, PORT);
  3374. const Headers headers = {{"Accept", "text/event-stream"}};
  3375. auto get_thread = std::thread([&client, &headers]() {
  3376. auto res = client.Get(
  3377. "/events", headers,
  3378. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  3379. });
  3380. auto se = detail::scope_exit([&] {
  3381. svr.stop();
  3382. get_thread.join();
  3383. listen_thread.join();
  3384. ASSERT_FALSE(svr.is_running());
  3385. });
  3386. // Give GET time to get a few messages.
  3387. std::this_thread::sleep_for(std::chrono::seconds(2));
  3388. }
  3389. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  3390. httplib::Server svr;
  3391. svr.Post("/hi", [&](const httplib::Request & /*req*/,
  3392. httplib::Response &res) { res.status = 200; });
  3393. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3394. while (!svr.is_running()) {
  3395. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  3396. }
  3397. Client cli(HOST, PORT);
  3398. auto res = cli.Post("/hi", "data", "text/plain");
  3399. ASSERT_TRUE(res);
  3400. EXPECT_EQ(200, res->status);
  3401. svr.stop();
  3402. thread.join();
  3403. ASSERT_FALSE(svr.is_running());
  3404. res = cli.Post("/hi", "data", "text/plain");
  3405. ASSERT_FALSE(res);
  3406. }
  3407. TEST(StreamingTest, NoContentLengthStreaming) {
  3408. Server svr;
  3409. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  3410. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  3411. if (offset < 6) {
  3412. sink.os << (offset < 3 ? "a" : "b");
  3413. } else {
  3414. sink.done();
  3415. }
  3416. return true;
  3417. });
  3418. });
  3419. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3420. auto listen_se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. listen_thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. while (!svr.is_running()) {
  3426. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3427. }
  3428. Client client(HOST, PORT);
  3429. auto get_thread = std::thread([&client]() {
  3430. std::string s;
  3431. auto res =
  3432. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  3433. s += std::string(data, len);
  3434. return true;
  3435. });
  3436. EXPECT_EQ("aaabbb", s);
  3437. });
  3438. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  3439. // Give GET time to get a few messages.
  3440. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3441. }
  3442. TEST(MountTest, Unmount) {
  3443. Server svr;
  3444. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3445. auto se = detail::scope_exit([&] {
  3446. svr.stop();
  3447. listen_thread.join();
  3448. ASSERT_FALSE(svr.is_running());
  3449. });
  3450. while (!svr.is_running()) {
  3451. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3452. }
  3453. // Give GET time to get a few messages.
  3454. std::this_thread::sleep_for(std::chrono::seconds(1));
  3455. Client cli("localhost", PORT);
  3456. svr.set_mount_point("/mount2", "./www2");
  3457. auto res = cli.Get("/");
  3458. ASSERT_TRUE(res);
  3459. EXPECT_EQ(404, res->status);
  3460. res = cli.Get("/mount2/dir/test.html");
  3461. ASSERT_TRUE(res);
  3462. EXPECT_EQ(200, res->status);
  3463. svr.set_mount_point("/", "./www");
  3464. res = cli.Get("/dir/");
  3465. ASSERT_TRUE(res);
  3466. EXPECT_EQ(200, res->status);
  3467. svr.remove_mount_point("/");
  3468. res = cli.Get("/dir/");
  3469. ASSERT_TRUE(res);
  3470. EXPECT_EQ(404, res->status);
  3471. svr.remove_mount_point("/mount2");
  3472. res = cli.Get("/mount2/dir/test.html");
  3473. ASSERT_TRUE(res);
  3474. EXPECT_EQ(404, res->status);
  3475. }
  3476. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3477. TEST(ExceptionTest, ThrowExceptionInHandler) {
  3478. Server svr;
  3479. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3480. throw std::runtime_error("exception...");
  3481. });
  3482. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3483. throw std::runtime_error("exception\r\n...");
  3484. });
  3485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3486. auto se = detail::scope_exit([&] {
  3487. svr.stop();
  3488. listen_thread.join();
  3489. ASSERT_FALSE(svr.is_running());
  3490. });
  3491. while (!svr.is_running()) {
  3492. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3493. }
  3494. // Give GET time to get a few messages.
  3495. std::this_thread::sleep_for(std::chrono::seconds(1));
  3496. Client cli("localhost", PORT);
  3497. {
  3498. auto res = cli.Get("/exception");
  3499. ASSERT_TRUE(res);
  3500. EXPECT_EQ(500, res->status);
  3501. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3502. EXPECT_EQ("exception...", res->get_header_value("EXCEPTION_WHAT"));
  3503. }
  3504. {
  3505. auto res = cli.Get("/unknown");
  3506. ASSERT_TRUE(res);
  3507. EXPECT_EQ(500, res->status);
  3508. ASSERT_TRUE(res->has_header("EXCEPTION_WHAT"));
  3509. EXPECT_EQ("exception\\r\\n...", res->get_header_value("EXCEPTION_WHAT"));
  3510. }
  3511. }
  3512. #endif
  3513. TEST(KeepAliveTest, ReadTimeout) {
  3514. Server svr;
  3515. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3516. std::this_thread::sleep_for(std::chrono::seconds(2));
  3517. res.set_content("a", "text/plain");
  3518. });
  3519. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3520. res.set_content("b", "text/plain");
  3521. });
  3522. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3523. auto se = detail::scope_exit([&] {
  3524. svr.stop();
  3525. listen_thread.join();
  3526. ASSERT_FALSE(svr.is_running());
  3527. });
  3528. while (!svr.is_running()) {
  3529. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3530. }
  3531. // Give GET time to get a few messages.
  3532. std::this_thread::sleep_for(std::chrono::seconds(1));
  3533. Client cli("localhost", PORT);
  3534. cli.set_keep_alive(true);
  3535. cli.set_read_timeout(std::chrono::seconds(1));
  3536. auto resa = cli.Get("/a");
  3537. ASSERT_FALSE(resa);
  3538. EXPECT_EQ(Error::Read, resa.error());
  3539. auto resb = cli.Get("/b");
  3540. ASSERT_TRUE(resb);
  3541. EXPECT_EQ(200, resb->status);
  3542. EXPECT_EQ("b", resb->body);
  3543. }
  3544. TEST(KeepAliveTest, Issue1041) {
  3545. Server svr;
  3546. svr.set_keep_alive_timeout(3);
  3547. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3548. res.set_content("Hello World!", "text/plain");
  3549. });
  3550. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3551. auto se = detail::scope_exit([&] {
  3552. svr.stop();
  3553. listen_thread.join();
  3554. ASSERT_FALSE(svr.is_running());
  3555. });
  3556. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3557. Client cli(HOST, PORT);
  3558. cli.set_keep_alive(true);
  3559. auto result = cli.Get("/hi");
  3560. ASSERT_TRUE(result);
  3561. EXPECT_EQ(200, result->status);
  3562. std::this_thread::sleep_for(std::chrono::seconds(5));
  3563. result = cli.Get("/hi");
  3564. ASSERT_TRUE(result);
  3565. EXPECT_EQ(200, result->status);
  3566. }
  3567. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3568. TEST(KeepAliveTest, SSLClientReconnection) {
  3569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3570. ASSERT_TRUE(svr.is_valid());
  3571. svr.set_keep_alive_timeout(1);
  3572. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  3573. res.set_content("Hello World!", "text/plain");
  3574. });
  3575. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  3576. auto se = detail::scope_exit([&] {
  3577. svr.stop();
  3578. listen_thread.join();
  3579. ASSERT_FALSE(svr.is_running());
  3580. });
  3581. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3582. SSLClient cli(HOST, PORT);
  3583. cli.enable_server_certificate_verification(false);
  3584. cli.set_keep_alive(true);
  3585. auto result = cli.Get("/hi");
  3586. ASSERT_TRUE(result);
  3587. EXPECT_EQ(200, result->status);
  3588. result = cli.Get("/hi");
  3589. ASSERT_TRUE(result);
  3590. EXPECT_EQ(200, result->status);
  3591. std::this_thread::sleep_for(std::chrono::seconds(2));
  3592. // Recoonect
  3593. result = cli.Get("/hi");
  3594. ASSERT_TRUE(result);
  3595. EXPECT_EQ(200, result->status);
  3596. result = cli.Get("/hi");
  3597. ASSERT_TRUE(result);
  3598. EXPECT_EQ(200, result->status);
  3599. }
  3600. #endif
  3601. TEST(ClientProblemDetectionTest, ContentProvider) {
  3602. Server svr;
  3603. size_t content_length = 1024 * 1024;
  3604. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3605. res.set_content_provider(
  3606. content_length, "text/plain",
  3607. [&](size_t offset, size_t length, DataSink &sink) {
  3608. auto out_len = std::min(length, static_cast<size_t>(1024));
  3609. std::string out(out_len, '@');
  3610. sink.write(out.data(), out_len);
  3611. return offset < 4096;
  3612. },
  3613. [](bool success) { ASSERT_FALSE(success); });
  3614. });
  3615. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  3616. res.set_content_provider(
  3617. 0, "text/plain",
  3618. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  3619. EXPECT_TRUE(false);
  3620. return true;
  3621. },
  3622. [](bool success) { ASSERT_FALSE(success); });
  3623. });
  3624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3625. auto se = detail::scope_exit([&] {
  3626. svr.stop();
  3627. listen_thread.join();
  3628. ASSERT_FALSE(svr.is_running());
  3629. });
  3630. while (!svr.is_running()) {
  3631. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3632. }
  3633. // Give GET time to get a few messages.
  3634. std::this_thread::sleep_for(std::chrono::seconds(1));
  3635. Client cli("localhost", PORT);
  3636. {
  3637. auto res = cli.Get("/hi", [&](const char * /*data*/,
  3638. size_t /*data_length*/) { return false; });
  3639. ASSERT_FALSE(res);
  3640. }
  3641. {
  3642. auto res = cli.Get("/empty", [&](const char * /*data*/,
  3643. size_t /*data_length*/) { return false; });
  3644. ASSERT_TRUE(res);
  3645. }
  3646. }
  3647. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  3648. Server svr;
  3649. svr.set_error_handler([](Request const &, Response &res) -> void {
  3650. res.set_chunked_content_provider(
  3651. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  3652. sink.os << "hello";
  3653. sink.os << "world";
  3654. sink.done();
  3655. return true;
  3656. });
  3657. });
  3658. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3659. auto se = detail::scope_exit([&] {
  3660. svr.stop();
  3661. listen_thread.join();
  3662. ASSERT_FALSE(svr.is_running());
  3663. });
  3664. while (!svr.is_running()) {
  3665. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3666. }
  3667. // Give GET time to get a few messages.
  3668. std::this_thread::sleep_for(std::chrono::seconds(1));
  3669. Client cli("localhost", PORT);
  3670. auto res = cli.Get("/");
  3671. ASSERT_TRUE(res);
  3672. EXPECT_EQ(404, res->status);
  3673. EXPECT_EQ("helloworld", res->body);
  3674. }
  3675. TEST(GetWithParametersTest, GetWithParameters) {
  3676. Server svr;
  3677. svr.Get("/", [&](const Request &req, Response &) {
  3678. EXPECT_EQ("world", req.get_param_value("hello"));
  3679. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3680. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3681. });
  3682. svr.Get("/params", [&](const Request &req, Response &) {
  3683. EXPECT_EQ("world", req.get_param_value("hello"));
  3684. EXPECT_EQ("world2", req.get_param_value("hello2"));
  3685. EXPECT_EQ("world3", req.get_param_value("hello3"));
  3686. });
  3687. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  3688. EXPECT_EQ("resource-id", req.matches[1]);
  3689. EXPECT_EQ("foo", req.get_param_value("param1"));
  3690. EXPECT_EQ("bar", req.get_param_value("param2"));
  3691. });
  3692. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  3693. auto se = detail::scope_exit([&] {
  3694. svr.stop();
  3695. listen_thread.join();
  3696. ASSERT_FALSE(svr.is_running());
  3697. });
  3698. while (!svr.is_running()) {
  3699. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3700. }
  3701. std::this_thread::sleep_for(std::chrono::seconds(1));
  3702. {
  3703. Client cli(HOST, PORT);
  3704. Params params;
  3705. params.emplace("hello", "world");
  3706. params.emplace("hello2", "world2");
  3707. params.emplace("hello3", "world3");
  3708. auto res = cli.Get("/", params, Headers{});
  3709. ASSERT_TRUE(res);
  3710. EXPECT_EQ(200, res->status);
  3711. }
  3712. {
  3713. Client cli(HOST, PORT);
  3714. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  3715. ASSERT_TRUE(res);
  3716. EXPECT_EQ(200, res->status);
  3717. }
  3718. {
  3719. Client cli(HOST, PORT);
  3720. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  3721. ASSERT_TRUE(res);
  3722. EXPECT_EQ(200, res->status);
  3723. }
  3724. }
  3725. TEST(GetWithParametersTest, GetWithParameters2) {
  3726. Server svr;
  3727. svr.Get("/", [&](const Request &req, Response &res) {
  3728. auto text = req.get_param_value("hello");
  3729. res.set_content(text, "text/plain");
  3730. });
  3731. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3732. auto se = detail::scope_exit([&] {
  3733. svr.stop();
  3734. listen_thread.join();
  3735. ASSERT_FALSE(svr.is_running());
  3736. });
  3737. while (!svr.is_running()) {
  3738. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3739. }
  3740. std::this_thread::sleep_for(std::chrono::seconds(1));
  3741. Client cli("localhost", PORT);
  3742. Params params;
  3743. params.emplace("hello", "world");
  3744. std::string body;
  3745. auto res = cli.Get("/", params, Headers{},
  3746. [&](const char *data, size_t data_length) {
  3747. body.append(data, data_length);
  3748. return true;
  3749. });
  3750. ASSERT_TRUE(res);
  3751. EXPECT_EQ(200, res->status);
  3752. EXPECT_EQ("world", body);
  3753. }
  3754. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  3755. Client cli("httpbin.org");
  3756. cli.set_default_headers({make_range_header({{1, 10}})});
  3757. cli.set_connection_timeout(5);
  3758. {
  3759. auto res = cli.Get("/range/32");
  3760. ASSERT_TRUE(res);
  3761. EXPECT_EQ("bcdefghijk", res->body);
  3762. EXPECT_EQ(206, res->status);
  3763. }
  3764. {
  3765. auto res = cli.Get("/range/32");
  3766. ASSERT_TRUE(res);
  3767. EXPECT_EQ("bcdefghijk", res->body);
  3768. EXPECT_EQ(206, res->status);
  3769. }
  3770. }
  3771. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  3772. Server svr;
  3773. svr.set_default_headers({{"Hello", "World"}});
  3774. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  3775. res.set_content("ok", "text/plain");
  3776. });
  3777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3778. auto se = detail::scope_exit([&] {
  3779. svr.stop();
  3780. listen_thread.join();
  3781. ASSERT_FALSE(svr.is_running());
  3782. });
  3783. while (!svr.is_running()) {
  3784. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3785. }
  3786. std::this_thread::sleep_for(std::chrono::seconds(1));
  3787. Client cli("localhost", PORT);
  3788. auto res = cli.Get("/");
  3789. ASSERT_TRUE(res);
  3790. EXPECT_EQ(200, res->status);
  3791. EXPECT_EQ("ok", res->body);
  3792. EXPECT_EQ("World", res->get_header_value("Hello"));
  3793. }
  3794. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3795. TEST(KeepAliveTest, ReadTimeoutSSL) {
  3796. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3797. ASSERT_TRUE(svr.is_valid());
  3798. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  3799. std::this_thread::sleep_for(std::chrono::seconds(2));
  3800. res.set_content("a", "text/plain");
  3801. });
  3802. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  3803. res.set_content("b", "text/plain");
  3804. });
  3805. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3806. auto se = detail::scope_exit([&] {
  3807. svr.stop();
  3808. listen_thread.join();
  3809. ASSERT_FALSE(svr.is_running());
  3810. });
  3811. while (!svr.is_running()) {
  3812. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3813. }
  3814. // Give GET time to get a few messages.
  3815. std::this_thread::sleep_for(std::chrono::seconds(1));
  3816. SSLClient cli("localhost", PORT);
  3817. cli.enable_server_certificate_verification(false);
  3818. cli.set_keep_alive(true);
  3819. cli.set_read_timeout(std::chrono::seconds(1));
  3820. auto resa = cli.Get("/a");
  3821. ASSERT_TRUE(!resa);
  3822. EXPECT_EQ(Error::Read, resa.error());
  3823. auto resb = cli.Get("/b");
  3824. ASSERT_TRUE(resb);
  3825. EXPECT_EQ(200, resb->status);
  3826. EXPECT_EQ("b", resb->body);
  3827. }
  3828. #endif
  3829. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  3830. protected:
  3831. ServerTestWithAI_PASSIVE()
  3832. : cli_(HOST, PORT)
  3833. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3834. ,
  3835. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3836. #endif
  3837. {
  3838. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3839. cli_.enable_server_certificate_verification(false);
  3840. #endif
  3841. }
  3842. virtual void SetUp() {
  3843. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  3844. res.set_content("Hello World!", "text/plain");
  3845. });
  3846. t_ = thread(
  3847. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  3848. while (!svr_.is_running()) {
  3849. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3850. }
  3851. }
  3852. virtual void TearDown() {
  3853. svr_.stop();
  3854. t_.join();
  3855. }
  3856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3857. SSLClient cli_;
  3858. SSLServer svr_;
  3859. #else
  3860. Client cli_;
  3861. Server svr_;
  3862. #endif
  3863. thread t_;
  3864. };
  3865. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  3866. auto res = cli_.Get("/hi");
  3867. ASSERT_TRUE(res);
  3868. EXPECT_EQ(200, res->status);
  3869. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  3870. EXPECT_EQ("Hello World!", res->body);
  3871. }
  3872. class ServerUpDownTest : public ::testing::Test {
  3873. protected:
  3874. ServerUpDownTest() : cli_(HOST, PORT) {}
  3875. virtual void SetUp() {
  3876. t_ = thread([&]() {
  3877. svr_.bind_to_any_port(HOST);
  3878. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3879. ASSERT_TRUE(svr_.listen_after_bind());
  3880. });
  3881. while (!svr_.is_running()) {
  3882. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3883. }
  3884. }
  3885. virtual void TearDown() {
  3886. svr_.stop();
  3887. t_.join();
  3888. }
  3889. Client cli_;
  3890. Server svr_;
  3891. thread t_;
  3892. };
  3893. TEST_F(ServerUpDownTest, QuickStartStop) {
  3894. // Should not crash, especially when run with
  3895. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  3896. }
  3897. class PayloadMaxLengthTest : public ::testing::Test {
  3898. protected:
  3899. PayloadMaxLengthTest()
  3900. : cli_(HOST, PORT)
  3901. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3902. ,
  3903. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  3904. #endif
  3905. {
  3906. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3907. cli_.enable_server_certificate_verification(false);
  3908. #endif
  3909. }
  3910. virtual void SetUp() {
  3911. svr_.set_payload_max_length(8);
  3912. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  3913. res.set_content("test", "text/plain");
  3914. });
  3915. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  3916. while (!svr_.is_running()) {
  3917. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3918. }
  3919. }
  3920. virtual void TearDown() {
  3921. svr_.stop();
  3922. t_.join();
  3923. }
  3924. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3925. SSLClient cli_;
  3926. SSLServer svr_;
  3927. #else
  3928. Client cli_;
  3929. Server svr_;
  3930. #endif
  3931. thread t_;
  3932. };
  3933. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  3934. auto res = cli_.Post("/test", "123456789", "text/plain");
  3935. ASSERT_TRUE(res);
  3936. EXPECT_EQ(413, res->status);
  3937. res = cli_.Post("/test", "12345678", "text/plain");
  3938. ASSERT_TRUE(res);
  3939. EXPECT_EQ(200, res->status);
  3940. }
  3941. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  3942. TEST(SSLClientTest, UpdateCAStore) {
  3943. httplib::SSLClient httplib_client("www.google.com");
  3944. auto ca_store_1 = X509_STORE_new();
  3945. X509_STORE_load_locations(ca_store_1, "/etc/ssl/certs/ca-certificates.crt",
  3946. nullptr);
  3947. httplib_client.set_ca_cert_store(ca_store_1);
  3948. auto ca_store_2 = X509_STORE_new();
  3949. X509_STORE_load_locations(ca_store_2, "/etc/ssl/certs/ca-certificates.crt",
  3950. nullptr);
  3951. httplib_client.set_ca_cert_store(ca_store_2);
  3952. }
  3953. TEST(SSLClientTest, ServerNameIndication_Online) {
  3954. SSLClient cli("httpbin.org", 443);
  3955. auto res = cli.Get("/get");
  3956. ASSERT_TRUE(res);
  3957. ASSERT_EQ(200, res->status);
  3958. }
  3959. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  3960. Client cli("https://google.com");
  3961. auto res = cli.Get("/");
  3962. ASSERT_TRUE(res);
  3963. ASSERT_EQ(301, res->status);
  3964. }
  3965. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  3966. SSLClient cli("google.com");
  3967. cli.enable_server_certificate_verification(true);
  3968. cli.set_ca_cert_path("hello");
  3969. auto res = cli.Get("/");
  3970. ASSERT_TRUE(!res);
  3971. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  3972. }
  3973. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  3974. SSLClient cli("google.com");
  3975. cli.set_ca_cert_path(CA_CERT_FILE);
  3976. auto res = cli.Get("/");
  3977. ASSERT_TRUE(res);
  3978. ASSERT_EQ(301, res->status);
  3979. }
  3980. TEST(SSLClientTest, ServerCertificateVerification4) {
  3981. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  3982. ASSERT_TRUE(svr.is_valid());
  3983. svr.Get("/test", [&](const Request &, Response &res) {
  3984. res.set_content("test", "text/plain");
  3985. svr.stop();
  3986. ASSERT_TRUE(true);
  3987. });
  3988. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  3989. auto se = detail::scope_exit([&] {
  3990. t.join();
  3991. ASSERT_FALSE(svr.is_running());
  3992. });
  3993. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3994. SSLClient cli("127.0.0.1", PORT);
  3995. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  3996. cli.enable_server_certificate_verification(true);
  3997. cli.set_connection_timeout(30);
  3998. auto res = cli.Get("/test");
  3999. ASSERT_TRUE(res);
  4000. ASSERT_EQ(200, res->status);
  4001. }
  4002. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  4003. SSLClient cli("www.youtube.com");
  4004. cli.set_ca_cert_path(CA_CERT_FILE);
  4005. cli.enable_server_certificate_verification(true);
  4006. cli.set_follow_location(true);
  4007. auto res = cli.Get("/");
  4008. ASSERT_TRUE(res);
  4009. ASSERT_EQ(200, res->status);
  4010. }
  4011. #if 0
  4012. TEST(SSLClientTest, SetInterfaceWithINET6) {
  4013. auto cli = std::make_shared<httplib::Client>("https://httpbin.org");
  4014. ASSERT_TRUE(cli != nullptr);
  4015. cli->set_address_family(AF_INET6);
  4016. cli->set_interface("en0");
  4017. auto res = cli->Get("/get");
  4018. ASSERT_TRUE(res);
  4019. ASSERT_EQ(200, res->status);
  4020. }
  4021. #endif
  4022. TEST(SSLClientServerTest, ClientCertPresent) {
  4023. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4024. CLIENT_CA_CERT_DIR);
  4025. ASSERT_TRUE(svr.is_valid());
  4026. svr.Get("/test", [&](const Request &req, Response &res) {
  4027. res.set_content("test", "text/plain");
  4028. svr.stop();
  4029. ASSERT_TRUE(true);
  4030. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4031. ASSERT_TRUE(peer_cert != nullptr);
  4032. auto subject_name = X509_get_subject_name(peer_cert);
  4033. ASSERT_TRUE(subject_name != nullptr);
  4034. std::string common_name;
  4035. {
  4036. char name[BUFSIZ];
  4037. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4038. name, sizeof(name));
  4039. common_name.assign(name, static_cast<size_t>(name_len));
  4040. }
  4041. EXPECT_EQ("Common Name", common_name);
  4042. X509_free(peer_cert);
  4043. });
  4044. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4045. auto se = detail::scope_exit([&] {
  4046. t.join();
  4047. ASSERT_FALSE(svr.is_running());
  4048. });
  4049. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4050. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4051. cli.enable_server_certificate_verification(false);
  4052. cli.set_connection_timeout(30);
  4053. auto res = cli.Get("/test");
  4054. ASSERT_TRUE(res);
  4055. ASSERT_EQ(200, res->status);
  4056. }
  4057. #if !defined(_WIN32) || defined(OPENSSL_USE_APPLINK)
  4058. TEST(SSLClientServerTest, MemoryClientCertPresent) {
  4059. X509 *server_cert;
  4060. EVP_PKEY *server_private_key;
  4061. X509_STORE *client_ca_cert_store;
  4062. X509 *client_cert;
  4063. EVP_PKEY *client_private_key;
  4064. FILE *f = fopen(SERVER_CERT_FILE, "r+");
  4065. server_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4066. fclose(f);
  4067. f = fopen(SERVER_PRIVATE_KEY_FILE, "r+");
  4068. server_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4069. fclose(f);
  4070. f = fopen(CLIENT_CA_CERT_FILE, "r+");
  4071. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4072. client_ca_cert_store = X509_STORE_new();
  4073. X509_STORE_add_cert(client_ca_cert_store, client_cert);
  4074. X509_free(client_cert);
  4075. fclose(f);
  4076. f = fopen(CLIENT_CERT_FILE, "r+");
  4077. client_cert = PEM_read_X509(f, nullptr, nullptr, nullptr);
  4078. fclose(f);
  4079. f = fopen(CLIENT_PRIVATE_KEY_FILE, "r+");
  4080. client_private_key = PEM_read_PrivateKey(f, nullptr, nullptr, nullptr);
  4081. fclose(f);
  4082. SSLServer svr(server_cert, server_private_key, client_ca_cert_store);
  4083. ASSERT_TRUE(svr.is_valid());
  4084. svr.Get("/test", [&](const Request &req, Response &res) {
  4085. res.set_content("test", "text/plain");
  4086. svr.stop();
  4087. ASSERT_TRUE(true);
  4088. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4089. ASSERT_TRUE(peer_cert != nullptr);
  4090. auto subject_name = X509_get_subject_name(peer_cert);
  4091. ASSERT_TRUE(subject_name != nullptr);
  4092. std::string common_name;
  4093. {
  4094. char name[BUFSIZ];
  4095. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4096. name, sizeof(name));
  4097. common_name.assign(name, static_cast<size_t>(name_len));
  4098. }
  4099. EXPECT_EQ("Common Name", common_name);
  4100. X509_free(peer_cert);
  4101. });
  4102. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4103. auto se = detail::scope_exit([&] {
  4104. t.join();
  4105. ASSERT_FALSE(svr.is_running());
  4106. });
  4107. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4108. SSLClient cli(HOST, PORT, client_cert, client_private_key);
  4109. cli.enable_server_certificate_verification(false);
  4110. cli.set_connection_timeout(30);
  4111. auto res = cli.Get("/test");
  4112. ASSERT_TRUE(res);
  4113. ASSERT_EQ(200, res->status);
  4114. X509_free(server_cert);
  4115. EVP_PKEY_free(server_private_key);
  4116. X509_free(client_cert);
  4117. EVP_PKEY_free(client_private_key);
  4118. }
  4119. #endif
  4120. TEST(SSLClientServerTest, ClientCertMissing) {
  4121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4122. CLIENT_CA_CERT_DIR);
  4123. ASSERT_TRUE(svr.is_valid());
  4124. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  4125. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4126. auto se = detail::scope_exit([&] {
  4127. svr.stop();
  4128. t.join();
  4129. ASSERT_FALSE(svr.is_running());
  4130. });
  4131. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4132. SSLClient cli(HOST, PORT);
  4133. auto res = cli.Get("/test");
  4134. cli.set_connection_timeout(30);
  4135. ASSERT_TRUE(!res);
  4136. EXPECT_EQ(Error::SSLServerVerification, res.error());
  4137. }
  4138. TEST(SSLClientServerTest, TrustDirOptional) {
  4139. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4140. ASSERT_TRUE(svr.is_valid());
  4141. svr.Get("/test", [&](const Request &, Response &res) {
  4142. res.set_content("test", "text/plain");
  4143. svr.stop();
  4144. });
  4145. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4146. auto se = detail::scope_exit([&] {
  4147. t.join();
  4148. ASSERT_FALSE(svr.is_running());
  4149. });
  4150. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4151. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4152. cli.enable_server_certificate_verification(false);
  4153. cli.set_connection_timeout(30);
  4154. auto res = cli.Get("/test");
  4155. ASSERT_TRUE(res);
  4156. ASSERT_EQ(200, res->status);
  4157. }
  4158. TEST(SSLClientServerTest, SSLConnectTimeout) {
  4159. class NoListenSSLServer : public SSLServer {
  4160. public:
  4161. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  4162. const char *client_ca_cert_file_path,
  4163. const char *client_ca_cert_dir_path = nullptr)
  4164. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  4165. client_ca_cert_dir_path),
  4166. stop_(false) {}
  4167. bool stop_;
  4168. private:
  4169. bool process_and_close_socket(socket_t /*sock*/) override {
  4170. // Don't create SSL context
  4171. while (!stop_) {
  4172. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  4173. }
  4174. return true;
  4175. }
  4176. };
  4177. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  4178. CLIENT_CA_CERT_FILE);
  4179. ASSERT_TRUE(svr.is_valid());
  4180. svr.Get("/test", [&](const Request &, Response &res) {
  4181. res.set_content("test", "text/plain");
  4182. });
  4183. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4184. auto se = detail::scope_exit([&] {
  4185. svr.stop_ = true;
  4186. svr.stop();
  4187. t.join();
  4188. ASSERT_FALSE(svr.is_running());
  4189. });
  4190. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4191. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4192. cli.enable_server_certificate_verification(false);
  4193. cli.set_connection_timeout(1);
  4194. auto res = cli.Get("/test");
  4195. ASSERT_TRUE(!res);
  4196. EXPECT_EQ(Error::SSLConnection, res.error());
  4197. }
  4198. TEST(SSLClientServerTest, CustomizeServerSSLCtx) {
  4199. auto setup_ssl_ctx_callback = [](SSL_CTX &ssl_ctx) {
  4200. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_COMPRESSION);
  4201. SSL_CTX_set_options(&ssl_ctx,
  4202. SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
  4203. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv2);
  4204. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_SSLv3);
  4205. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1);
  4206. SSL_CTX_set_options(&ssl_ctx, SSL_OP_NO_TLSv1_1);
  4207. auto ciphers = "ECDHE-RSA-AES128-SHA256:"
  4208. "ECDHE-DSS-AES128-SHA256:"
  4209. "ECDHE-RSA-AES256-SHA256:"
  4210. "ECDHE-DSS-AES256-SHA256:";
  4211. SSL_CTX_set_cipher_list(&ssl_ctx, ciphers);
  4212. if (SSL_CTX_use_certificate_chain_file(&ssl_ctx, SERVER_CERT_FILE) != 1 ||
  4213. SSL_CTX_use_PrivateKey_file(&ssl_ctx, SERVER_PRIVATE_KEY_FILE,
  4214. SSL_FILETYPE_PEM) != 1) {
  4215. return false;
  4216. }
  4217. SSL_CTX_load_verify_locations(&ssl_ctx, CLIENT_CA_CERT_FILE,
  4218. CLIENT_CA_CERT_DIR);
  4219. SSL_CTX_set_verify(
  4220. &ssl_ctx,
  4221. SSL_VERIFY_PEER |
  4222. SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
  4223. nullptr);
  4224. return true;
  4225. };
  4226. SSLServer svr(setup_ssl_ctx_callback);
  4227. ASSERT_TRUE(svr.is_valid());
  4228. svr.Get("/test", [&](const Request &req, Response &res) {
  4229. res.set_content("test", "text/plain");
  4230. svr.stop();
  4231. ASSERT_TRUE(true);
  4232. auto peer_cert = SSL_get_peer_certificate(req.ssl);
  4233. ASSERT_TRUE(peer_cert != nullptr);
  4234. auto subject_name = X509_get_subject_name(peer_cert);
  4235. ASSERT_TRUE(subject_name != nullptr);
  4236. std::string common_name;
  4237. {
  4238. char name[BUFSIZ];
  4239. auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
  4240. name, sizeof(name));
  4241. common_name.assign(name, static_cast<size_t>(name_len));
  4242. }
  4243. EXPECT_EQ("Common Name", common_name);
  4244. X509_free(peer_cert);
  4245. });
  4246. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4247. auto se = detail::scope_exit([&] {
  4248. t.join();
  4249. ASSERT_FALSE(svr.is_running());
  4250. });
  4251. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4252. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4253. cli.enable_server_certificate_verification(false);
  4254. cli.set_connection_timeout(30);
  4255. auto res = cli.Get("/test");
  4256. ASSERT_TRUE(res);
  4257. ASSERT_EQ(200, res->status);
  4258. }
  4259. // Disabled due to the out-of-memory problem on GitHub Actions Workflows
  4260. TEST(SSLClientServerTest, DISABLED_LargeDataTransfer) {
  4261. // prepare large data
  4262. std::random_device seed_gen;
  4263. std::mt19937 random(seed_gen());
  4264. constexpr auto large_size_byte = 2147483648UL + 1048576UL; // 2GiB + 1MiB
  4265. std::vector<std::uint32_t> binary(large_size_byte / sizeof(std::uint32_t));
  4266. std::generate(binary.begin(), binary.end(), [&random]() { return random(); });
  4267. // server
  4268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4269. ASSERT_TRUE(svr.is_valid());
  4270. svr.Post("/binary", [&](const Request &req, Response &res) {
  4271. EXPECT_EQ(large_size_byte, req.body.size());
  4272. EXPECT_EQ(0, std::memcmp(binary.data(), req.body.data(), large_size_byte));
  4273. res.set_content(req.body, "application/octet-stream");
  4274. });
  4275. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4276. auto se = detail::scope_exit([&] {
  4277. svr.stop();
  4278. listen_thread.join();
  4279. ASSERT_FALSE(svr.is_running());
  4280. });
  4281. while (!svr.is_running()) {
  4282. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4283. }
  4284. // client POST
  4285. SSLClient cli("localhost", PORT);
  4286. cli.enable_server_certificate_verification(false);
  4287. cli.set_read_timeout(std::chrono::seconds(100));
  4288. cli.set_write_timeout(std::chrono::seconds(100));
  4289. auto res = cli.Post("/binary", reinterpret_cast<char *>(binary.data()),
  4290. large_size_byte, "application/octet-stream");
  4291. // compare
  4292. EXPECT_EQ(200, res->status);
  4293. EXPECT_EQ(large_size_byte, res->body.size());
  4294. EXPECT_EQ(0, std::memcmp(binary.data(), res->body.data(), large_size_byte));
  4295. }
  4296. #endif
  4297. #ifdef _WIN32
  4298. TEST(CleanupTest, WSACleanup) {
  4299. int ret = WSACleanup();
  4300. ASSERT_EQ(0, ret);
  4301. }
  4302. #endif
  4303. #ifndef CPPHTTPLIB_OPENSSL_SUPPORT
  4304. TEST(NoSSLSupport, SimpleInterface) {
  4305. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  4306. }
  4307. #endif
  4308. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4309. TEST(InvalidScheme, SimpleInterface) {
  4310. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  4311. }
  4312. #endif
  4313. TEST(NoScheme, SimpleInterface) {
  4314. Client cli("yahoo.com:80");
  4315. ASSERT_TRUE(cli.is_valid());
  4316. }
  4317. TEST(SendAPI, SimpleInterface_Online) {
  4318. Client cli("http://yahoo.com");
  4319. Request req;
  4320. req.method = "GET";
  4321. req.path = "/";
  4322. auto res = cli.send(req);
  4323. ASSERT_TRUE(res);
  4324. EXPECT_EQ(301, res->status);
  4325. }
  4326. TEST(ClientImplMethods, GetSocketTest) {
  4327. httplib::Server svr;
  4328. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  4329. res.status = 200;
  4330. });
  4331. auto thread = std::thread([&]() { svr.listen("127.0.0.1", 3333); });
  4332. auto se = detail::scope_exit([&] {
  4333. svr.stop();
  4334. thread.join();
  4335. ASSERT_FALSE(svr.is_running());
  4336. });
  4337. while (!svr.is_running()) {
  4338. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  4339. }
  4340. {
  4341. httplib::Client cli("http://127.0.0.1:3333");
  4342. cli.set_keep_alive(true);
  4343. // Use the behavior of cpp-httplib of opening the connection
  4344. // only when the first request happens. If that changes,
  4345. // this test would be obsolete.
  4346. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  4347. // This also implicitly tests the server. But other tests would fail much
  4348. // earlier than this one to be considered.
  4349. auto res = cli.Get("/");
  4350. ASSERT_TRUE(res);
  4351. EXPECT_EQ(200, res->status);
  4352. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  4353. }
  4354. }
  4355. // Disabled due to out-of-memory problem on GitHub Actions
  4356. #ifdef _WIN64
  4357. TEST(ServerLargeContentTest, DISABLED_SendLargeContent) {
  4358. // allocate content size larger than 2GB in memory
  4359. const size_t content_size = 2LL * 1024LL * 1024LL * 1024LL + 1LL;
  4360. char *content = (char *)malloc(content_size);
  4361. ASSERT_TRUE(content);
  4362. Server svr;
  4363. svr.Get("/foo", [=](const httplib::Request &req, httplib::Response &resp) {
  4364. resp.set_content(content, content_size, "application/octet-stream");
  4365. });
  4366. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. listen_thread.join();
  4370. if (content) free(content);
  4371. ASSERT_FALSE(svr.is_running());
  4372. });
  4373. while (!svr.is_running()) {
  4374. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4375. }
  4376. // Give GET time to get a few messages.
  4377. std::this_thread::sleep_for(std::chrono::seconds(1));
  4378. Client cli(HOST, PORT);
  4379. auto res = cli.Get("/foo");
  4380. ASSERT_TRUE(res);
  4381. EXPECT_EQ(200, res->status);
  4382. EXPECT_EQ(content_size, res->body.length());
  4383. }
  4384. #endif
  4385. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4386. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  4387. Client cli("http://yahoo.com");
  4388. auto res = cli.Get("/");
  4389. ASSERT_TRUE(res);
  4390. EXPECT_EQ(301, res->status);
  4391. cli.set_follow_location(true);
  4392. res = cli.Get("/");
  4393. ASSERT_TRUE(res);
  4394. EXPECT_EQ(200, res->status);
  4395. EXPECT_EQ("https://yahoo.com/", res->location);
  4396. }
  4397. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  4398. Client cli("https://yahoo.com");
  4399. auto res = cli.Get("/");
  4400. ASSERT_TRUE(res);
  4401. EXPECT_EQ(301, res->status);
  4402. cli.set_follow_location(true);
  4403. res = cli.Get("/");
  4404. ASSERT_TRUE(res);
  4405. EXPECT_EQ(200, res->status);
  4406. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4407. }
  4408. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  4409. Client cli("https://yahoo.com");
  4410. auto res = cli.Get("/");
  4411. ASSERT_TRUE(res);
  4412. ASSERT_FALSE(!res);
  4413. ASSERT_TRUE(res);
  4414. ASSERT_FALSE(res == nullptr);
  4415. ASSERT_TRUE(res != nullptr);
  4416. EXPECT_EQ(Error::Success, res.error());
  4417. EXPECT_EQ(301, res.value().status);
  4418. EXPECT_EQ(301, (*res).status);
  4419. EXPECT_EQ(301, res->status);
  4420. cli.set_follow_location(true);
  4421. res = cli.Get("/");
  4422. ASSERT_TRUE(res);
  4423. EXPECT_EQ(Error::Success, res.error());
  4424. EXPECT_EQ(200, res.value().status);
  4425. EXPECT_EQ(200, (*res).status);
  4426. EXPECT_EQ(200, res->status);
  4427. EXPECT_EQ("https://www.yahoo.com/", res->location);
  4428. }
  4429. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  4430. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  4431. Client cli("https://cdnjs.cloudflare.com");
  4432. auto res =
  4433. cli.Get("/ajax/libs/jquery/3.5.1/jquery.js", {{"Accept-Encoding", "br"}});
  4434. ASSERT_TRUE(res);
  4435. EXPECT_EQ(200, res->status);
  4436. EXPECT_EQ(287630U, res->body.size());
  4437. EXPECT_EQ("application/javascript; charset=utf-8",
  4438. res->get_header_value("Content-Type"));
  4439. }
  4440. #endif
  4441. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  4442. Client cli("https://nghttp2.org");
  4443. cli.set_follow_location(true);
  4444. auto res =
  4445. cli.Get("/httpbin/"
  4446. "redirect-to?url=http%3A%2F%2Fwww.google.com&status_code=302");
  4447. ASSERT_TRUE(res);
  4448. EXPECT_EQ(200, res->status);
  4449. }
  4450. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  4451. Client cli("https://nghttp2.org");
  4452. cli.set_follow_location(true);
  4453. Params params;
  4454. params.emplace("url", "http://www.google.com");
  4455. params.emplace("status_code", "302");
  4456. auto res = cli.Get("/httpbin/redirect-to", params, Headers{});
  4457. ASSERT_TRUE(res);
  4458. EXPECT_EQ(200, res->status);
  4459. }
  4460. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  4461. Client cli("https://nghttp2.org");
  4462. cli.set_follow_location(true);
  4463. Params params;
  4464. params.emplace("url", "http://www.google.com");
  4465. auto res = cli.Get("/httpbin/redirect-to?status_code=302", params, Headers{});
  4466. ASSERT_TRUE(res);
  4467. EXPECT_EQ(200, res->status);
  4468. }
  4469. TEST(HttpToHttpsRedirectTest, CertFile) {
  4470. Server svr;
  4471. ASSERT_TRUE(svr.is_valid());
  4472. svr.Get("/index", [&](const Request &, Response &res) {
  4473. res.set_redirect("https://127.0.0.1:1235/index");
  4474. svr.stop();
  4475. });
  4476. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  4477. ASSERT_TRUE(ssl_svr.is_valid());
  4478. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  4479. res.set_content("test", "text/plain");
  4480. ssl_svr.stop();
  4481. });
  4482. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  4483. thread t2 = thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", 1235)); });
  4484. auto se = detail::scope_exit([&] {
  4485. t2.join();
  4486. t.join();
  4487. ASSERT_FALSE(svr.is_running());
  4488. });
  4489. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4490. Client cli("127.0.0.1", PORT);
  4491. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  4492. cli.enable_server_certificate_verification(true);
  4493. cli.set_follow_location(true);
  4494. cli.set_connection_timeout(30);
  4495. auto res = cli.Get("/index");
  4496. ASSERT_TRUE(res);
  4497. ASSERT_EQ(200, res->status);
  4498. }
  4499. TEST(MultipartFormDataTest, LargeData) {
  4500. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4501. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  4502. const ContentReader &content_reader) {
  4503. if (req.is_multipart_form_data()) {
  4504. MultipartFormDataItems files;
  4505. content_reader(
  4506. [&](const MultipartFormData &file) {
  4507. files.push_back(file);
  4508. return true;
  4509. },
  4510. [&](const char *data, size_t data_length) {
  4511. files.back().content.append(data, data_length);
  4512. return true;
  4513. });
  4514. EXPECT_TRUE(std::string(files[0].name) == "document");
  4515. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4516. EXPECT_TRUE(files[0].filename == "2MB_data");
  4517. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4518. EXPECT_TRUE(files[1].name == "hello");
  4519. EXPECT_TRUE(files[1].content == "world");
  4520. EXPECT_TRUE(files[1].filename == "");
  4521. EXPECT_TRUE(files[1].content_type == "");
  4522. } else {
  4523. std::string body;
  4524. content_reader([&](const char *data, size_t data_length) {
  4525. body.append(data, data_length);
  4526. return true;
  4527. });
  4528. }
  4529. });
  4530. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4531. auto se = detail::scope_exit([&] {
  4532. svr.stop();
  4533. t.join();
  4534. ASSERT_FALSE(svr.is_running());
  4535. });
  4536. while (!svr.is_running()) {
  4537. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4538. }
  4539. std::this_thread::sleep_for(std::chrono::seconds(1));
  4540. {
  4541. std::string data(1024 * 1024 * 2, '.');
  4542. std::stringstream buffer;
  4543. buffer << data;
  4544. Client cli("https://localhost:8080");
  4545. cli.enable_server_certificate_verification(false);
  4546. MultipartFormDataItems items{
  4547. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4548. {"hello", "world", "", ""},
  4549. };
  4550. auto res = cli.Post("/post", items);
  4551. ASSERT_TRUE(res);
  4552. ASSERT_EQ(200, res->status);
  4553. }
  4554. }
  4555. TEST(MultipartFormDataTest, DataProviderItems) {
  4556. std::random_device seed_gen;
  4557. std::mt19937 random(seed_gen());
  4558. std::string rand1;
  4559. rand1.resize(1000);
  4560. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  4561. std::string rand2;
  4562. rand2.resize(3000);
  4563. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  4564. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4565. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  4566. const ContentReader &content_reader) {
  4567. ASSERT_FALSE(req.is_multipart_form_data());
  4568. std::string body;
  4569. content_reader([&](const char *data, size_t data_length) {
  4570. body.append(data, data_length);
  4571. return true;
  4572. });
  4573. EXPECT_EQ(body, "");
  4574. });
  4575. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  4576. const ContentReader &content_reader) {
  4577. ASSERT_TRUE(req.is_multipart_form_data());
  4578. MultipartFormDataItems files;
  4579. content_reader(
  4580. [&](const MultipartFormData &file) {
  4581. files.push_back(file);
  4582. return true;
  4583. },
  4584. [&](const char *data, size_t data_length) {
  4585. files.back().content.append(data, data_length);
  4586. return true;
  4587. });
  4588. ASSERT_TRUE(files.size() == 2);
  4589. EXPECT_EQ(std::string(files[0].name), "name1");
  4590. EXPECT_EQ(files[0].content, "Testing123");
  4591. EXPECT_EQ(files[0].filename, "filename1");
  4592. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4593. EXPECT_EQ(files[1].name, "name2");
  4594. EXPECT_EQ(files[1].content, "Testing456");
  4595. EXPECT_EQ(files[1].filename, "");
  4596. EXPECT_EQ(files[1].content_type, "");
  4597. });
  4598. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  4599. const ContentReader &content_reader) {
  4600. ASSERT_TRUE(req.is_multipart_form_data());
  4601. MultipartFormDataItems files;
  4602. content_reader(
  4603. [&](const MultipartFormData &file) {
  4604. files.push_back(file);
  4605. return true;
  4606. },
  4607. [&](const char *data, size_t data_length) {
  4608. files.back().content.append(data, data_length);
  4609. return true;
  4610. });
  4611. ASSERT_TRUE(files.size() == 2);
  4612. EXPECT_EQ(files[0].name, "name3");
  4613. EXPECT_EQ(files[0].content, rand1);
  4614. EXPECT_EQ(files[0].filename, "filename3");
  4615. EXPECT_EQ(files[0].content_type, "");
  4616. EXPECT_EQ(files[1].name, "name4");
  4617. EXPECT_EQ(files[1].content, rand2);
  4618. EXPECT_EQ(files[1].filename, "filename4");
  4619. EXPECT_EQ(files[1].content_type, "");
  4620. });
  4621. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  4622. const ContentReader &content_reader) {
  4623. ASSERT_TRUE(req.is_multipart_form_data());
  4624. MultipartFormDataItems files;
  4625. content_reader(
  4626. [&](const MultipartFormData &file) {
  4627. files.push_back(file);
  4628. return true;
  4629. },
  4630. [&](const char *data, size_t data_length) {
  4631. files.back().content.append(data, data_length);
  4632. return true;
  4633. });
  4634. ASSERT_TRUE(files.size() == 4);
  4635. EXPECT_EQ(std::string(files[0].name), "name1");
  4636. EXPECT_EQ(files[0].content, "Testing123");
  4637. EXPECT_EQ(files[0].filename, "filename1");
  4638. EXPECT_EQ(files[0].content_type, "application/octet-stream");
  4639. EXPECT_EQ(files[1].name, "name2");
  4640. EXPECT_EQ(files[1].content, "Testing456");
  4641. EXPECT_EQ(files[1].filename, "");
  4642. EXPECT_EQ(files[1].content_type, "");
  4643. EXPECT_EQ(files[2].name, "name3");
  4644. EXPECT_EQ(files[2].content, rand1);
  4645. EXPECT_EQ(files[2].filename, "filename3");
  4646. EXPECT_EQ(files[2].content_type, "");
  4647. EXPECT_EQ(files[3].name, "name4");
  4648. EXPECT_EQ(files[3].content, rand2);
  4649. EXPECT_EQ(files[3].filename, "filename4");
  4650. EXPECT_EQ(files[3].content_type, "");
  4651. });
  4652. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4653. auto se = detail::scope_exit([&] {
  4654. svr.stop();
  4655. t.join();
  4656. ASSERT_FALSE(svr.is_running());
  4657. });
  4658. while (!svr.is_running()) {
  4659. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4660. }
  4661. std::this_thread::sleep_for(std::chrono::seconds(1));
  4662. {
  4663. Client cli("https://localhost:8080");
  4664. cli.enable_server_certificate_verification(false);
  4665. MultipartFormDataItems items{
  4666. {"name1", "Testing123", "filename1", "application/octet-stream"},
  4667. {"name2", "Testing456", "", ""}, // not a file
  4668. };
  4669. {
  4670. auto res = cli.Post("/post-none", {}, {}, {});
  4671. ASSERT_TRUE(res);
  4672. ASSERT_EQ(200, res->status);
  4673. }
  4674. MultipartFormDataProviderItems providers;
  4675. {
  4676. auto res =
  4677. cli.Post("/post-items", {}, items, providers); // empty providers
  4678. ASSERT_TRUE(res);
  4679. ASSERT_EQ(200, res->status);
  4680. }
  4681. providers.push_back({"name3",
  4682. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4683. // test the offset is given correctly at each step
  4684. if (!offset)
  4685. sink.os.write(rand1.data(), 30);
  4686. else if (offset == 30)
  4687. sink.os.write(rand1.data() + 30, 300);
  4688. else if (offset == 330)
  4689. sink.os.write(rand1.data() + 330, 670);
  4690. else if (offset == rand1.size())
  4691. sink.done();
  4692. return true;
  4693. },
  4694. "filename3",
  4695. {}});
  4696. providers.push_back({"name4",
  4697. [&](size_t offset, httplib::DataSink &sink) -> bool {
  4698. // test the offset is given correctly at each step
  4699. if (!offset)
  4700. sink.os.write(rand2.data(), 2000);
  4701. else if (offset == 2000)
  4702. sink.os.write(rand2.data() + 2000, 1);
  4703. else if (offset == 2001)
  4704. sink.os.write(rand2.data() + 2001, 999);
  4705. else if (offset == rand2.size())
  4706. sink.done();
  4707. return true;
  4708. },
  4709. "filename4",
  4710. {}});
  4711. {
  4712. auto res = cli.Post("/post-providers", {}, {}, providers);
  4713. ASSERT_TRUE(res);
  4714. ASSERT_EQ(200, res->status);
  4715. }
  4716. {
  4717. auto res = cli.Post("/post-both", {}, items, providers);
  4718. ASSERT_TRUE(res);
  4719. ASSERT_EQ(200, res->status);
  4720. }
  4721. }
  4722. }
  4723. TEST(MultipartFormDataTest, BadHeader) {
  4724. Server svr;
  4725. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4726. res.set_content("ok", "text/plain");
  4727. });
  4728. thread t = thread([&] { svr.listen(HOST, PORT); });
  4729. auto se = detail::scope_exit([&] {
  4730. svr.stop();
  4731. t.join();
  4732. ASSERT_FALSE(svr.is_running());
  4733. });
  4734. while (!svr.is_running()) {
  4735. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4736. }
  4737. const std::string body =
  4738. "This is the preamble. It is to be ignored, though it\r\n"
  4739. "is a handy place for composition agents to include an\r\n"
  4740. "explanatory note to non-MIME conformant readers.\r\n"
  4741. "\r\n"
  4742. "\r\n"
  4743. "--simple boundary\r\n"
  4744. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4745. ": BAD...\r\n"
  4746. "\r\n"
  4747. "value1\r\n"
  4748. "--simple boundary\r\n"
  4749. "Content-Disposition: form-data; name=\"field2\"; "
  4750. "filename=\"example.txt\"\r\n"
  4751. "\r\n"
  4752. "value2\r\n"
  4753. "--simple boundary--\r\n"
  4754. "This is the epilogue. It is also to be ignored.\r\n";
  4755. std::string content_type =
  4756. R"(multipart/form-data; boundary="simple boundary")";
  4757. Client cli(HOST, PORT);
  4758. auto res = cli.Post("/post", body, content_type.c_str());
  4759. ASSERT_TRUE(res);
  4760. EXPECT_EQ(400, res->status);
  4761. }
  4762. TEST(MultipartFormDataTest, WithPreamble) {
  4763. Server svr;
  4764. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  4765. res.set_content("ok", "text/plain");
  4766. });
  4767. thread t = thread([&] { svr.listen(HOST, PORT); });
  4768. auto se = detail::scope_exit([&] {
  4769. svr.stop();
  4770. t.join();
  4771. ASSERT_FALSE(svr.is_running());
  4772. });
  4773. while (!svr.is_running()) {
  4774. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4775. }
  4776. const std::string body =
  4777. "This is the preamble. It is to be ignored, though it\r\n"
  4778. "is a handy place for composition agents to include an\r\n"
  4779. "explanatory note to non-MIME conformant readers.\r\n"
  4780. "\r\n"
  4781. "\r\n"
  4782. "--simple boundary\r\n"
  4783. "Content-Disposition: form-data; name=\"field1\"\r\n"
  4784. "\r\n"
  4785. "value1\r\n"
  4786. "--simple boundary\r\n"
  4787. "Content-Disposition: form-data; name=\"field2\"; "
  4788. "filename=\"example.txt\"\r\n"
  4789. "\r\n"
  4790. "value2\r\n"
  4791. "--simple boundary--\r\n"
  4792. "This is the epilogue. It is also to be ignored.\r\n";
  4793. std::string content_type =
  4794. R"(multipart/form-data; boundary="simple boundary")";
  4795. Client cli(HOST, PORT);
  4796. auto res = cli.Post("/post", body, content_type.c_str());
  4797. ASSERT_TRUE(res);
  4798. EXPECT_EQ(200, res->status);
  4799. }
  4800. TEST(MultipartFormDataTest, PostCustomBoundary) {
  4801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4802. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  4803. const ContentReader &content_reader) {
  4804. if (req.is_multipart_form_data()) {
  4805. MultipartFormDataItems files;
  4806. content_reader(
  4807. [&](const MultipartFormData &file) {
  4808. files.push_back(file);
  4809. return true;
  4810. },
  4811. [&](const char *data, size_t data_length) {
  4812. files.back().content.append(data, data_length);
  4813. return true;
  4814. });
  4815. EXPECT_TRUE(std::string(files[0].name) == "document");
  4816. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4817. EXPECT_TRUE(files[0].filename == "2MB_data");
  4818. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4819. EXPECT_TRUE(files[1].name == "hello");
  4820. EXPECT_TRUE(files[1].content == "world");
  4821. EXPECT_TRUE(files[1].filename == "");
  4822. EXPECT_TRUE(files[1].content_type == "");
  4823. } else {
  4824. std::string body;
  4825. content_reader([&](const char *data, size_t data_length) {
  4826. body.append(data, data_length);
  4827. return true;
  4828. });
  4829. }
  4830. });
  4831. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4832. auto se = detail::scope_exit([&] {
  4833. svr.stop();
  4834. t.join();
  4835. ASSERT_FALSE(svr.is_running());
  4836. });
  4837. while (!svr.is_running()) {
  4838. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4839. }
  4840. std::this_thread::sleep_for(std::chrono::seconds(1));
  4841. {
  4842. std::string data(1024 * 1024 * 2, '.');
  4843. std::stringstream buffer;
  4844. buffer << data;
  4845. Client cli("https://localhost:8080");
  4846. cli.enable_server_certificate_verification(false);
  4847. MultipartFormDataItems items{
  4848. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4849. {"hello", "world", "", ""},
  4850. };
  4851. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  4852. ASSERT_TRUE(res);
  4853. ASSERT_EQ(200, res->status);
  4854. }
  4855. }
  4856. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  4857. std::this_thread::sleep_for(std::chrono::seconds(1));
  4858. std::string data(1024 * 1024 * 2, '&');
  4859. std::stringstream buffer;
  4860. buffer << data;
  4861. Client cli("https://localhost:8080");
  4862. MultipartFormDataItems items{
  4863. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4864. {"hello", "world", "", ""},
  4865. };
  4866. for (const char &c : " \t\r\n") {
  4867. auto res =
  4868. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  4869. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  4870. ASSERT_FALSE(res);
  4871. }
  4872. }
  4873. TEST(MultipartFormDataTest, PutFormData) {
  4874. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4875. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  4876. const ContentReader &content_reader) {
  4877. if (req.is_multipart_form_data()) {
  4878. MultipartFormDataItems files;
  4879. content_reader(
  4880. [&](const MultipartFormData &file) {
  4881. files.push_back(file);
  4882. return true;
  4883. },
  4884. [&](const char *data, size_t data_length) {
  4885. files.back().content.append(data, data_length);
  4886. return true;
  4887. });
  4888. EXPECT_TRUE(std::string(files[0].name) == "document");
  4889. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4890. EXPECT_TRUE(files[0].filename == "2MB_data");
  4891. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4892. EXPECT_TRUE(files[1].name == "hello");
  4893. EXPECT_TRUE(files[1].content == "world");
  4894. EXPECT_TRUE(files[1].filename == "");
  4895. EXPECT_TRUE(files[1].content_type == "");
  4896. } else {
  4897. std::string body;
  4898. content_reader([&](const char *data, size_t data_length) {
  4899. body.append(data, data_length);
  4900. return true;
  4901. });
  4902. }
  4903. });
  4904. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4905. auto se = detail::scope_exit([&] {
  4906. svr.stop();
  4907. t.join();
  4908. ASSERT_FALSE(svr.is_running());
  4909. });
  4910. while (!svr.is_running()) {
  4911. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4912. }
  4913. std::this_thread::sleep_for(std::chrono::seconds(1));
  4914. {
  4915. std::string data(1024 * 1024 * 2, '&');
  4916. std::stringstream buffer;
  4917. buffer << data;
  4918. Client cli("https://localhost:8080");
  4919. cli.enable_server_certificate_verification(false);
  4920. MultipartFormDataItems items{
  4921. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4922. {"hello", "world", "", ""},
  4923. };
  4924. auto res = cli.Put("/put", items);
  4925. ASSERT_TRUE(res);
  4926. ASSERT_EQ(200, res->status);
  4927. }
  4928. }
  4929. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  4930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4931. svr.Put("/put_customboundary",
  4932. [&](const Request &req, const Response & /*res*/,
  4933. const ContentReader &content_reader) {
  4934. if (req.is_multipart_form_data()) {
  4935. MultipartFormDataItems files;
  4936. content_reader(
  4937. [&](const MultipartFormData &file) {
  4938. files.push_back(file);
  4939. return true;
  4940. },
  4941. [&](const char *data, size_t data_length) {
  4942. files.back().content.append(data, data_length);
  4943. return true;
  4944. });
  4945. EXPECT_TRUE(std::string(files[0].name) == "document");
  4946. EXPECT_EQ(size_t(1024 * 1024 * 2), files[0].content.size());
  4947. EXPECT_TRUE(files[0].filename == "2MB_data");
  4948. EXPECT_TRUE(files[0].content_type == "application/octet-stream");
  4949. EXPECT_TRUE(files[1].name == "hello");
  4950. EXPECT_TRUE(files[1].content == "world");
  4951. EXPECT_TRUE(files[1].filename == "");
  4952. EXPECT_TRUE(files[1].content_type == "");
  4953. } else {
  4954. std::string body;
  4955. content_reader([&](const char *data, size_t data_length) {
  4956. body.append(data, data_length);
  4957. return true;
  4958. });
  4959. }
  4960. });
  4961. auto t = std::thread([&]() { svr.listen("localhost", 8080); });
  4962. auto se = detail::scope_exit([&] {
  4963. svr.stop();
  4964. t.join();
  4965. ASSERT_FALSE(svr.is_running());
  4966. });
  4967. while (!svr.is_running()) {
  4968. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4969. }
  4970. std::this_thread::sleep_for(std::chrono::seconds(1));
  4971. {
  4972. std::string data(1024 * 1024 * 2, '&');
  4973. std::stringstream buffer;
  4974. buffer << data;
  4975. Client cli("https://localhost:8080");
  4976. cli.enable_server_certificate_verification(false);
  4977. MultipartFormDataItems items{
  4978. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4979. {"hello", "world", "", ""},
  4980. };
  4981. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  4982. ASSERT_TRUE(res);
  4983. ASSERT_EQ(200, res->status);
  4984. }
  4985. }
  4986. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  4987. std::this_thread::sleep_for(std::chrono::seconds(1));
  4988. std::string data(1024 * 1024 * 2, '&');
  4989. std::stringstream buffer;
  4990. buffer << data;
  4991. Client cli("https://localhost:8080");
  4992. cli.enable_server_certificate_verification(false);
  4993. MultipartFormDataItems items{
  4994. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  4995. {"hello", "world", "", ""},
  4996. };
  4997. for (const char &c : " \t\r\n") {
  4998. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  4999. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  5000. ASSERT_FALSE(res);
  5001. }
  5002. }
  5003. #endif
  5004. #ifndef _WIN32
  5005. class UnixSocketTest : public ::testing::Test {
  5006. protected:
  5007. void TearDown() override { std::remove(pathname_.c_str()); }
  5008. void client_GET(const std::string &addr) {
  5009. httplib::Client cli{addr};
  5010. cli.set_address_family(AF_UNIX);
  5011. ASSERT_TRUE(cli.is_valid());
  5012. const auto &result = cli.Get(pattern_);
  5013. ASSERT_TRUE(result) << "error: " << result.error();
  5014. const auto &resp = result.value();
  5015. EXPECT_EQ(resp.status, 200);
  5016. EXPECT_EQ(resp.body, content_);
  5017. }
  5018. const std::string pathname_{"./httplib-server.sock"};
  5019. const std::string pattern_{"/hi"};
  5020. const std::string content_{"Hello World!"};
  5021. };
  5022. TEST_F(UnixSocketTest, pathname) {
  5023. httplib::Server svr;
  5024. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5025. res.set_content(content_, "text/plain");
  5026. });
  5027. std::thread t{[&] {
  5028. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5029. }};
  5030. auto se = detail::scope_exit([&] {
  5031. svr.stop();
  5032. t.join();
  5033. ASSERT_FALSE(svr.is_running());
  5034. });
  5035. while (!svr.is_running()) {
  5036. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5037. }
  5038. ASSERT_TRUE(svr.is_running());
  5039. client_GET(pathname_);
  5040. }
  5041. #if defined(__linux__) || \
  5042. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  5043. TEST_F(UnixSocketTest, PeerPid) {
  5044. httplib::Server svr;
  5045. std::string remote_port_val;
  5046. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  5047. res.set_content(content_, "text/plain");
  5048. remote_port_val = req.get_header_value("REMOTE_PORT");
  5049. });
  5050. std::thread t{[&] {
  5051. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  5052. }};
  5053. auto se = detail::scope_exit([&] {
  5054. svr.stop();
  5055. t.join();
  5056. ASSERT_FALSE(svr.is_running());
  5057. });
  5058. while (!svr.is_running()) {
  5059. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5060. }
  5061. ASSERT_TRUE(svr.is_running());
  5062. client_GET(pathname_);
  5063. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  5064. }
  5065. #endif
  5066. #ifdef __linux__
  5067. TEST_F(UnixSocketTest, abstract) {
  5068. constexpr char svr_path[]{"\x00httplib-server.sock"};
  5069. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  5070. httplib::Server svr;
  5071. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  5072. res.set_content(content_, "text/plain");
  5073. });
  5074. std::thread t{[&] {
  5075. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  5076. }};
  5077. auto se = detail::scope_exit([&] {
  5078. svr.stop();
  5079. t.join();
  5080. ASSERT_FALSE(svr.is_running());
  5081. });
  5082. while (!svr.is_running()) {
  5083. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  5084. }
  5085. ASSERT_TRUE(svr.is_running());
  5086. client_GET(abstract_addr);
  5087. }
  5088. #endif
  5089. TEST(SocketStream, is_writable_UNIX) {
  5090. int fds[2];
  5091. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  5092. const auto asSocketStream = [&](socket_t fd,
  5093. std::function<bool(Stream &)> func) {
  5094. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5095. };
  5096. asSocketStream(fds[0], [&](Stream &s0) {
  5097. EXPECT_EQ(s0.socket(), fds[0]);
  5098. EXPECT_TRUE(s0.is_writable());
  5099. EXPECT_EQ(0, close(fds[1]));
  5100. EXPECT_FALSE(s0.is_writable());
  5101. return true;
  5102. });
  5103. EXPECT_EQ(0, close(fds[0]));
  5104. }
  5105. TEST(SocketStream, is_writable_INET) {
  5106. sockaddr_in addr;
  5107. memset(&addr, 0, sizeof(addr));
  5108. addr.sin_family = AF_INET;
  5109. addr.sin_port = htons(PORT + 1);
  5110. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  5111. int disconnected_svr_sock = -1;
  5112. std::thread svr{[&] {
  5113. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5114. ASSERT_LE(0, s);
  5115. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5116. ASSERT_EQ(0, listen(s, 1));
  5117. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  5118. ASSERT_EQ(0, close(s));
  5119. }};
  5120. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  5121. std::thread cli{[&] {
  5122. const int s = socket(AF_INET, SOCK_STREAM, 0);
  5123. ASSERT_LE(0, s);
  5124. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  5125. ASSERT_EQ(0, close(s));
  5126. }};
  5127. cli.join();
  5128. svr.join();
  5129. ASSERT_NE(disconnected_svr_sock, -1);
  5130. const auto asSocketStream = [&](socket_t fd,
  5131. std::function<bool(Stream &)> func) {
  5132. return detail::process_client_socket(fd, 0, 0, 0, 0, func);
  5133. };
  5134. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  5135. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  5136. EXPECT_FALSE(ss.is_writable());
  5137. return true;
  5138. });
  5139. ASSERT_EQ(0, close(disconnected_svr_sock));
  5140. }
  5141. #endif // #ifndef _WIN32
  5142. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  5143. static constexpr unsigned int number_of_task{1000000};
  5144. std::atomic_uint count{0};
  5145. std::unique_ptr<TaskQueue> task_queue{
  5146. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  5147. for (unsigned int i = 0; i < number_of_task; ++i) {
  5148. task_queue->enqueue(
  5149. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  5150. }
  5151. EXPECT_NO_THROW(task_queue->shutdown());
  5152. EXPECT_EQ(number_of_task, count.load());
  5153. }
  5154. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  5155. Server svr;
  5156. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5157. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  5158. });
  5159. svr.Get("/hello", [](const Request &req, Response &res) {
  5160. res.set_content(req.get_param_value("key"), "text/plain");
  5161. });
  5162. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5163. auto se = detail::scope_exit([&] {
  5164. svr.stop();
  5165. thread.join();
  5166. ASSERT_FALSE(svr.is_running());
  5167. });
  5168. std::this_thread::sleep_for(std::chrono::seconds(1));
  5169. {
  5170. Client cli(HOST, PORT);
  5171. cli.set_follow_location(true);
  5172. auto res = cli.Get("/");
  5173. ASSERT_TRUE(res);
  5174. EXPECT_EQ(200, res->status);
  5175. EXPECT_EQ("val&key2=val2", res->body);
  5176. }
  5177. }