nats.go 149 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688
  1. // Copyright 2012-2023 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. // A Go client for the NATS messaging system (https://nats.io).
  14. package nats
  15. import (
  16. "bufio"
  17. "bytes"
  18. "crypto/tls"
  19. "crypto/x509"
  20. "encoding/base64"
  21. "encoding/json"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "math/rand"
  26. "net"
  27. "net/http"
  28. "net/textproto"
  29. "net/url"
  30. "os"
  31. "path/filepath"
  32. "regexp"
  33. "runtime"
  34. "strconv"
  35. "strings"
  36. "sync"
  37. "sync/atomic"
  38. "time"
  39. "github.com/nats-io/nkeys"
  40. "github.com/nats-io/nuid"
  41. "github.com/nats-io/nats.go/util"
  42. )
  43. // Default Constants
  44. const (
  45. Version = "1.31.0"
  46. DefaultURL = "nats://127.0.0.1:4222"
  47. DefaultPort = 4222
  48. DefaultMaxReconnect = 60
  49. DefaultReconnectWait = 2 * time.Second
  50. DefaultReconnectJitter = 100 * time.Millisecond
  51. DefaultReconnectJitterTLS = time.Second
  52. DefaultTimeout = 2 * time.Second
  53. DefaultPingInterval = 2 * time.Minute
  54. DefaultMaxPingOut = 2
  55. DefaultMaxChanLen = 64 * 1024 // 64k
  56. DefaultReconnectBufSize = 8 * 1024 * 1024 // 8MB
  57. RequestChanLen = 8
  58. DefaultDrainTimeout = 30 * time.Second
  59. DefaultFlusherTimeout = time.Minute
  60. LangString = "go"
  61. )
  62. const (
  63. // STALE_CONNECTION is for detection and proper handling of stale connections.
  64. STALE_CONNECTION = "stale connection"
  65. // PERMISSIONS_ERR is for when nats server subject authorization has failed.
  66. PERMISSIONS_ERR = "permissions violation"
  67. // AUTHORIZATION_ERR is for when nats server user authorization has failed.
  68. AUTHORIZATION_ERR = "authorization violation"
  69. // AUTHENTICATION_EXPIRED_ERR is for when nats server user authorization has expired.
  70. AUTHENTICATION_EXPIRED_ERR = "user authentication expired"
  71. // AUTHENTICATION_REVOKED_ERR is for when user authorization has been revoked.
  72. AUTHENTICATION_REVOKED_ERR = "user authentication revoked"
  73. // ACCOUNT_AUTHENTICATION_EXPIRED_ERR is for when nats server account authorization has expired.
  74. ACCOUNT_AUTHENTICATION_EXPIRED_ERR = "account authentication expired"
  75. // MAX_CONNECTIONS_ERR is for when nats server denies the connection due to server max_connections limit
  76. MAX_CONNECTIONS_ERR = "maximum connections exceeded"
  77. )
  78. // Errors
  79. var (
  80. ErrConnectionClosed = errors.New("nats: connection closed")
  81. ErrConnectionDraining = errors.New("nats: connection draining")
  82. ErrDrainTimeout = errors.New("nats: draining connection timed out")
  83. ErrConnectionReconnecting = errors.New("nats: connection reconnecting")
  84. ErrSecureConnRequired = errors.New("nats: secure connection required")
  85. ErrSecureConnWanted = errors.New("nats: secure connection not available")
  86. ErrBadSubscription = errors.New("nats: invalid subscription")
  87. ErrTypeSubscription = errors.New("nats: invalid subscription type")
  88. ErrBadSubject = errors.New("nats: invalid subject")
  89. ErrBadQueueName = errors.New("nats: invalid queue name")
  90. ErrSlowConsumer = errors.New("nats: slow consumer, messages dropped")
  91. ErrTimeout = errors.New("nats: timeout")
  92. ErrBadTimeout = errors.New("nats: timeout invalid")
  93. ErrAuthorization = errors.New("nats: authorization violation")
  94. ErrAuthExpired = errors.New("nats: authentication expired")
  95. ErrAuthRevoked = errors.New("nats: authentication revoked")
  96. ErrAccountAuthExpired = errors.New("nats: account authentication expired")
  97. ErrNoServers = errors.New("nats: no servers available for connection")
  98. ErrJsonParse = errors.New("nats: connect message, json parse error")
  99. ErrChanArg = errors.New("nats: argument needs to be a channel type")
  100. ErrMaxPayload = errors.New("nats: maximum payload exceeded")
  101. ErrMaxMessages = errors.New("nats: maximum messages delivered")
  102. ErrSyncSubRequired = errors.New("nats: illegal call on an async subscription")
  103. ErrMultipleTLSConfigs = errors.New("nats: multiple tls.Configs not allowed")
  104. ErrNoInfoReceived = errors.New("nats: protocol exception, INFO not received")
  105. ErrReconnectBufExceeded = errors.New("nats: outbound buffer limit exceeded")
  106. ErrInvalidConnection = errors.New("nats: invalid connection")
  107. ErrInvalidMsg = errors.New("nats: invalid message or message nil")
  108. ErrInvalidArg = errors.New("nats: invalid argument")
  109. ErrInvalidContext = errors.New("nats: invalid context")
  110. ErrNoDeadlineContext = errors.New("nats: context requires a deadline")
  111. ErrNoEchoNotSupported = errors.New("nats: no echo option not supported by this server")
  112. ErrClientIDNotSupported = errors.New("nats: client ID not supported by this server")
  113. ErrUserButNoSigCB = errors.New("nats: user callback defined without a signature handler")
  114. ErrNkeyButNoSigCB = errors.New("nats: nkey defined without a signature handler")
  115. ErrNoUserCB = errors.New("nats: user callback not defined")
  116. ErrNkeyAndUser = errors.New("nats: user callback and nkey defined")
  117. ErrNkeysNotSupported = errors.New("nats: nkeys not supported by the server")
  118. ErrStaleConnection = errors.New("nats: " + STALE_CONNECTION)
  119. ErrTokenAlreadySet = errors.New("nats: token and token handler both set")
  120. ErrMsgNotBound = errors.New("nats: message is not bound to subscription/connection")
  121. ErrMsgNoReply = errors.New("nats: message does not have a reply")
  122. ErrClientIPNotSupported = errors.New("nats: client IP not supported by this server")
  123. ErrDisconnected = errors.New("nats: server is disconnected")
  124. ErrHeadersNotSupported = errors.New("nats: headers not supported by this server")
  125. ErrBadHeaderMsg = errors.New("nats: message could not decode headers")
  126. ErrNoResponders = errors.New("nats: no responders available for request")
  127. ErrMaxConnectionsExceeded = errors.New("nats: server maximum connections exceeded")
  128. ErrConnectionNotTLS = errors.New("nats: connection is not tls")
  129. )
  130. // GetDefaultOptions returns default configuration options for the client.
  131. func GetDefaultOptions() Options {
  132. return Options{
  133. AllowReconnect: true,
  134. MaxReconnect: DefaultMaxReconnect,
  135. ReconnectWait: DefaultReconnectWait,
  136. ReconnectJitter: DefaultReconnectJitter,
  137. ReconnectJitterTLS: DefaultReconnectJitterTLS,
  138. Timeout: DefaultTimeout,
  139. PingInterval: DefaultPingInterval,
  140. MaxPingsOut: DefaultMaxPingOut,
  141. SubChanLen: DefaultMaxChanLen,
  142. ReconnectBufSize: DefaultReconnectBufSize,
  143. DrainTimeout: DefaultDrainTimeout,
  144. FlusherTimeout: DefaultFlusherTimeout,
  145. }
  146. }
  147. // DEPRECATED: Use GetDefaultOptions() instead.
  148. // DefaultOptions is not safe for use by multiple clients.
  149. // For details see #308.
  150. var DefaultOptions = GetDefaultOptions()
  151. // Status represents the state of the connection.
  152. type Status int
  153. const (
  154. DISCONNECTED = Status(iota)
  155. CONNECTED
  156. CLOSED
  157. RECONNECTING
  158. CONNECTING
  159. DRAINING_SUBS
  160. DRAINING_PUBS
  161. )
  162. func (s Status) String() string {
  163. switch s {
  164. case DISCONNECTED:
  165. return "DISCONNECTED"
  166. case CONNECTED:
  167. return "CONNECTED"
  168. case CLOSED:
  169. return "CLOSED"
  170. case RECONNECTING:
  171. return "RECONNECTING"
  172. case CONNECTING:
  173. return "CONNECTING"
  174. case DRAINING_SUBS:
  175. return "DRAINING_SUBS"
  176. case DRAINING_PUBS:
  177. return "DRAINING_PUBS"
  178. }
  179. return "unknown status"
  180. }
  181. // ConnHandler is used for asynchronous events such as
  182. // disconnected and closed connections.
  183. type ConnHandler func(*Conn)
  184. // ConnErrHandler is used to process asynchronous events like
  185. // disconnected connection with the error (if any).
  186. type ConnErrHandler func(*Conn, error)
  187. // ErrHandler is used to process asynchronous errors encountered
  188. // while processing inbound messages.
  189. type ErrHandler func(*Conn, *Subscription, error)
  190. // UserJWTHandler is used to fetch and return the account signed
  191. // JWT for this user.
  192. type UserJWTHandler func() (string, error)
  193. // TLSCertHandler is used to fetch and return tls certificate.
  194. type TLSCertHandler func() (tls.Certificate, error)
  195. // RootCAsHandler is used to fetch and return a set of root certificate
  196. // authorities that clients use when verifying server certificates.
  197. type RootCAsHandler func() (*x509.CertPool, error)
  198. // SignatureHandler is used to sign a nonce from the server while
  199. // authenticating with nkeys. The user should sign the nonce and
  200. // return the raw signature. The client will base64 encode this to
  201. // send to the server.
  202. type SignatureHandler func([]byte) ([]byte, error)
  203. // AuthTokenHandler is used to generate a new token.
  204. type AuthTokenHandler func() string
  205. // ReconnectDelayHandler is used to get from the user the desired
  206. // delay the library should pause before attempting to reconnect
  207. // again. Note that this is invoked after the library tried the
  208. // whole list of URLs and failed to reconnect.
  209. type ReconnectDelayHandler func(attempts int) time.Duration
  210. // asyncCB is used to preserve order for async callbacks.
  211. type asyncCB struct {
  212. f func()
  213. next *asyncCB
  214. }
  215. type asyncCallbacksHandler struct {
  216. mu sync.Mutex
  217. cond *sync.Cond
  218. head *asyncCB
  219. tail *asyncCB
  220. }
  221. // Option is a function on the options for a connection.
  222. type Option func(*Options) error
  223. // CustomDialer can be used to specify any dialer, not necessarily a
  224. // *net.Dialer. A CustomDialer may also implement `SkipTLSHandshake() bool`
  225. // in order to skip the TLS handshake in case not required.
  226. type CustomDialer interface {
  227. Dial(network, address string) (net.Conn, error)
  228. }
  229. type InProcessConnProvider interface {
  230. InProcessConn() (net.Conn, error)
  231. }
  232. // Options can be used to create a customized connection.
  233. type Options struct {
  234. // Url represents a single NATS server url to which the client
  235. // will be connecting. If the Servers option is also set, it
  236. // then becomes the first server in the Servers array.
  237. Url string
  238. // InProcessServer represents a NATS server running within the
  239. // same process. If this is set then we will attempt to connect
  240. // to the server directly rather than using external TCP conns.
  241. InProcessServer InProcessConnProvider
  242. // Servers is a configured set of servers which this client
  243. // will use when attempting to connect.
  244. Servers []string
  245. // NoRandomize configures whether we will randomize the
  246. // server pool.
  247. NoRandomize bool
  248. // NoEcho configures whether the server will echo back messages
  249. // that are sent on this connection if we also have matching subscriptions.
  250. // Note this is supported on servers >= version 1.2. Proto 1 or greater.
  251. NoEcho bool
  252. // Name is an optional name label which will be sent to the server
  253. // on CONNECT to identify the client.
  254. Name string
  255. // Verbose signals the server to send an OK ack for commands
  256. // successfully processed by the server.
  257. Verbose bool
  258. // Pedantic signals the server whether it should be doing further
  259. // validation of subjects.
  260. Pedantic bool
  261. // Secure enables TLS secure connections that skip server
  262. // verification by default. NOT RECOMMENDED.
  263. Secure bool
  264. // TLSConfig is a custom TLS configuration to use for secure
  265. // transports.
  266. TLSConfig *tls.Config
  267. // TLSCertCB is used to fetch and return custom tls certificate.
  268. TLSCertCB TLSCertHandler
  269. // TLSHandshakeFirst is used to instruct the library perform
  270. // the TLS handshake right after the connect and before receiving
  271. // the INFO protocol from the server. If this option is enabled
  272. // but the server is not configured to perform the TLS handshake
  273. // first, the connection will fail.
  274. TLSHandshakeFirst bool
  275. // RootCAsCB is used to fetch and return a set of root certificate
  276. // authorities that clients use when verifying server certificates.
  277. RootCAsCB RootCAsHandler
  278. // AllowReconnect enables reconnection logic to be used when we
  279. // encounter a disconnect from the current server.
  280. AllowReconnect bool
  281. // MaxReconnect sets the number of reconnect attempts that will be
  282. // tried before giving up. If negative, then it will never give up
  283. // trying to reconnect.
  284. // Defaults to 60.
  285. MaxReconnect int
  286. // ReconnectWait sets the time to backoff after attempting a reconnect
  287. // to a server that we were already connected to previously.
  288. // Defaults to 2s.
  289. ReconnectWait time.Duration
  290. // CustomReconnectDelayCB is invoked after the library tried every
  291. // URL in the server list and failed to reconnect. It passes to the
  292. // user the current number of attempts. This function returns the
  293. // amount of time the library will sleep before attempting to reconnect
  294. // again. It is strongly recommended that this value contains some
  295. // jitter to prevent all connections to attempt reconnecting at the same time.
  296. CustomReconnectDelayCB ReconnectDelayHandler
  297. // ReconnectJitter sets the upper bound for a random delay added to
  298. // ReconnectWait during a reconnect when no TLS is used.
  299. // Defaults to 100ms.
  300. ReconnectJitter time.Duration
  301. // ReconnectJitterTLS sets the upper bound for a random delay added to
  302. // ReconnectWait during a reconnect when TLS is used.
  303. // Defaults to 1s.
  304. ReconnectJitterTLS time.Duration
  305. // Timeout sets the timeout for a Dial operation on a connection.
  306. // Defaults to 2s.
  307. Timeout time.Duration
  308. // DrainTimeout sets the timeout for a Drain Operation to complete.
  309. // Defaults to 30s.
  310. DrainTimeout time.Duration
  311. // FlusherTimeout is the maximum time to wait for write operations
  312. // to the underlying connection to complete (including the flusher loop).
  313. // Defaults to 1m.
  314. FlusherTimeout time.Duration
  315. // PingInterval is the period at which the client will be sending ping
  316. // commands to the server, disabled if 0 or negative.
  317. // Defaults to 2m.
  318. PingInterval time.Duration
  319. // MaxPingsOut is the maximum number of pending ping commands that can
  320. // be awaiting a response before raising an ErrStaleConnection error.
  321. // Defaults to 2.
  322. MaxPingsOut int
  323. // ClosedCB sets the closed handler that is called when a client will
  324. // no longer be connected.
  325. ClosedCB ConnHandler
  326. // DisconnectedCB sets the disconnected handler that is called
  327. // whenever the connection is disconnected.
  328. // Will not be called if DisconnectedErrCB is set
  329. // DEPRECATED. Use DisconnectedErrCB which passes error that caused
  330. // the disconnect event.
  331. DisconnectedCB ConnHandler
  332. // DisconnectedErrCB sets the disconnected error handler that is called
  333. // whenever the connection is disconnected.
  334. // Disconnected error could be nil, for instance when user explicitly closes the connection.
  335. // DisconnectedCB will not be called if DisconnectedErrCB is set
  336. DisconnectedErrCB ConnErrHandler
  337. // ConnectedCB sets the connected handler called when the initial connection
  338. // is established. It is not invoked on successful reconnects - for reconnections,
  339. // use ReconnectedCB. ConnectedCB can be used in conjunction with RetryOnFailedConnect
  340. // to detect whether the initial connect was successful.
  341. ConnectedCB ConnHandler
  342. // ReconnectedCB sets the reconnected handler called whenever
  343. // the connection is successfully reconnected.
  344. ReconnectedCB ConnHandler
  345. // DiscoveredServersCB sets the callback that is invoked whenever a new
  346. // server has joined the cluster.
  347. DiscoveredServersCB ConnHandler
  348. // AsyncErrorCB sets the async error handler (e.g. slow consumer errors)
  349. AsyncErrorCB ErrHandler
  350. // ReconnectBufSize is the size of the backing bufio during reconnect.
  351. // Once this has been exhausted publish operations will return an error.
  352. // Defaults to 8388608 bytes (8MB).
  353. ReconnectBufSize int
  354. // SubChanLen is the size of the buffered channel used between the socket
  355. // Go routine and the message delivery for SyncSubscriptions.
  356. // NOTE: This does not affect AsyncSubscriptions which are
  357. // dictated by PendingLimits()
  358. // Defaults to 65536.
  359. SubChanLen int
  360. // UserJWT sets the callback handler that will fetch a user's JWT.
  361. UserJWT UserJWTHandler
  362. // Nkey sets the public nkey that will be used to authenticate
  363. // when connecting to the server. UserJWT and Nkey are mutually exclusive
  364. // and if defined, UserJWT will take precedence.
  365. Nkey string
  366. // SignatureCB designates the function used to sign the nonce
  367. // presented from the server.
  368. SignatureCB SignatureHandler
  369. // User sets the username to be used when connecting to the server.
  370. User string
  371. // Password sets the password to be used when connecting to a server.
  372. Password string
  373. // Token sets the token to be used when connecting to a server.
  374. Token string
  375. // TokenHandler designates the function used to generate the token to be used when connecting to a server.
  376. TokenHandler AuthTokenHandler
  377. // Dialer allows a custom net.Dialer when forming connections.
  378. // DEPRECATED: should use CustomDialer instead.
  379. Dialer *net.Dialer
  380. // CustomDialer allows to specify a custom dialer (not necessarily
  381. // a *net.Dialer).
  382. CustomDialer CustomDialer
  383. // UseOldRequestStyle forces the old method of Requests that utilize
  384. // a new Inbox and a new Subscription for each request.
  385. UseOldRequestStyle bool
  386. // NoCallbacksAfterClientClose allows preventing the invocation of
  387. // callbacks after Close() is called. Client won't receive notifications
  388. // when Close is invoked by user code. Default is to invoke the callbacks.
  389. NoCallbacksAfterClientClose bool
  390. // LameDuckModeHandler sets the callback to invoke when the server notifies
  391. // the connection that it entered lame duck mode, that is, going to
  392. // gradually disconnect all its connections before shutting down. This is
  393. // often used in deployments when upgrading NATS Servers.
  394. LameDuckModeHandler ConnHandler
  395. // RetryOnFailedConnect sets the connection in reconnecting state right
  396. // away if it can't connect to a server in the initial set. The
  397. // MaxReconnect and ReconnectWait options are used for this process,
  398. // similarly to when an established connection is disconnected.
  399. // If a ReconnectHandler is set, it will be invoked on the first
  400. // successful reconnect attempt (if the initial connect fails),
  401. // and if a ClosedHandler is set, it will be invoked if
  402. // it fails to connect (after exhausting the MaxReconnect attempts).
  403. RetryOnFailedConnect bool
  404. // For websocket connections, indicates to the server that the connection
  405. // supports compression. If the server does too, then data will be compressed.
  406. Compression bool
  407. // For websocket connections, adds a path to connections url.
  408. // This is useful when connecting to NATS behind a proxy.
  409. ProxyPath string
  410. // InboxPrefix allows the default _INBOX prefix to be customized
  411. InboxPrefix string
  412. // IgnoreAuthErrorAbort - if set to true, client opts out of the default connect behavior of aborting
  413. // subsequent reconnect attempts if server returns the same auth error twice (regardless of reconnect policy).
  414. IgnoreAuthErrorAbort bool
  415. // SkipHostLookup skips the DNS lookup for the server hostname.
  416. SkipHostLookup bool
  417. }
  418. const (
  419. // Scratch storage for assembling protocol headers
  420. scratchSize = 512
  421. // The size of the bufio reader/writer on top of the socket.
  422. defaultBufSize = 32768
  423. // The buffered size of the flush "kick" channel
  424. flushChanSize = 1
  425. // Default server pool size
  426. srvPoolSize = 4
  427. // NUID size
  428. nuidSize = 22
  429. // Default ports used if none is specified in given URL(s)
  430. defaultWSPortString = "80"
  431. defaultWSSPortString = "443"
  432. defaultPortString = "4222"
  433. )
  434. // A Conn represents a bare connection to a nats-server.
  435. // It can send and receive []byte payloads.
  436. // The connection is safe to use in multiple Go routines concurrently.
  437. type Conn struct {
  438. // Keep all members for which we use atomic at the beginning of the
  439. // struct and make sure they are all 64bits (or use padding if necessary).
  440. // atomic.* functions crash on 32bit machines if operand is not aligned
  441. // at 64bit. See https://github.com/golang/go/issues/599
  442. Statistics
  443. mu sync.RWMutex
  444. // Opts holds the configuration of the Conn.
  445. // Modifying the configuration of a running Conn is a race.
  446. Opts Options
  447. wg sync.WaitGroup
  448. srvPool []*srv
  449. current *srv
  450. urls map[string]struct{} // Keep track of all known URLs (used by processInfo)
  451. conn net.Conn
  452. bw *natsWriter
  453. br *natsReader
  454. fch chan struct{}
  455. info serverInfo
  456. ssid int64
  457. subsMu sync.RWMutex
  458. subs map[int64]*Subscription
  459. ach *asyncCallbacksHandler
  460. pongs []chan struct{}
  461. scratch [scratchSize]byte
  462. status Status
  463. statListeners map[Status][]chan Status
  464. initc bool // true if the connection is performing the initial connect
  465. err error
  466. ps *parseState
  467. ptmr *time.Timer
  468. pout int
  469. ar bool // abort reconnect
  470. rqch chan struct{}
  471. ws bool // true if a websocket connection
  472. // New style response handler
  473. respSub string // The wildcard subject
  474. respSubPrefix string // the wildcard prefix including trailing .
  475. respSubLen int // the length of the wildcard prefix excluding trailing .
  476. respScanf string // The scanf template to extract mux token
  477. respMux *Subscription // A single response subscription
  478. respMap map[string]chan *Msg // Request map for the response msg channels
  479. respRand *rand.Rand // Used for generating suffix
  480. // Msg filters for testing.
  481. // Protected by subsMu
  482. filters map[string]msgFilter
  483. }
  484. type natsReader struct {
  485. r io.Reader
  486. buf []byte
  487. off int
  488. n int
  489. }
  490. type natsWriter struct {
  491. w io.Writer
  492. bufs []byte
  493. limit int
  494. pending *bytes.Buffer
  495. plimit int
  496. }
  497. // Subscription represents interest in a given subject.
  498. type Subscription struct {
  499. mu sync.Mutex
  500. sid int64
  501. // Subject that represents this subscription. This can be different
  502. // than the received subject inside a Msg if this is a wildcard.
  503. Subject string
  504. // Optional queue group name. If present, all subscriptions with the
  505. // same name will form a distributed queue, and each message will
  506. // only be processed by one member of the group.
  507. Queue string
  508. // For holding information about a JetStream consumer.
  509. jsi *jsSub
  510. delivered uint64
  511. max uint64
  512. conn *Conn
  513. mcb MsgHandler
  514. mch chan *Msg
  515. closed bool
  516. sc bool
  517. connClosed bool
  518. // Type of Subscription
  519. typ SubscriptionType
  520. // Async linked list
  521. pHead *Msg
  522. pTail *Msg
  523. pCond *sync.Cond
  524. pDone func(subject string)
  525. // Pending stats, async subscriptions, high-speed etc.
  526. pMsgs int
  527. pBytes int
  528. pMsgsMax int
  529. pBytesMax int
  530. pMsgsLimit int
  531. pBytesLimit int
  532. dropped int
  533. }
  534. // Msg represents a message delivered by NATS. This structure is used
  535. // by Subscribers and PublishMsg().
  536. //
  537. // # Types of Acknowledgements
  538. //
  539. // In case using JetStream, there are multiple ways to ack a Msg:
  540. //
  541. // // Acknowledgement that a message has been processed.
  542. // msg.Ack()
  543. //
  544. // // Negatively acknowledges a message.
  545. // msg.Nak()
  546. //
  547. // // Terminate a message so that it is not redelivered further.
  548. // msg.Term()
  549. //
  550. // // Signal the server that the message is being worked on and reset redelivery timer.
  551. // msg.InProgress()
  552. type Msg struct {
  553. Subject string
  554. Reply string
  555. Header Header
  556. Data []byte
  557. Sub *Subscription
  558. // Internal
  559. next *Msg
  560. wsz int
  561. barrier *barrierInfo
  562. ackd uint32
  563. }
  564. // Compares two msgs, ignores sub but checks all other public fields.
  565. func (m *Msg) Equal(msg *Msg) bool {
  566. if m == msg {
  567. return true
  568. }
  569. if m == nil || msg == nil {
  570. return false
  571. }
  572. if m.Subject != msg.Subject || m.Reply != msg.Reply {
  573. return false
  574. }
  575. if !bytes.Equal(m.Data, msg.Data) {
  576. return false
  577. }
  578. if len(m.Header) != len(msg.Header) {
  579. return false
  580. }
  581. for k, v := range m.Header {
  582. val, ok := msg.Header[k]
  583. if !ok || len(v) != len(val) {
  584. return false
  585. }
  586. for i, hdr := range v {
  587. if hdr != val[i] {
  588. return false
  589. }
  590. }
  591. }
  592. return true
  593. }
  594. // Size returns a message size in bytes.
  595. func (m *Msg) Size() int {
  596. if m.wsz != 0 {
  597. return m.wsz
  598. }
  599. hdr, _ := m.headerBytes()
  600. return len(m.Subject) + len(m.Reply) + len(hdr) + len(m.Data)
  601. }
  602. func (m *Msg) headerBytes() ([]byte, error) {
  603. var hdr []byte
  604. if len(m.Header) == 0 {
  605. return hdr, nil
  606. }
  607. var b bytes.Buffer
  608. _, err := b.WriteString(hdrLine)
  609. if err != nil {
  610. return nil, ErrBadHeaderMsg
  611. }
  612. err = http.Header(m.Header).Write(&b)
  613. if err != nil {
  614. return nil, ErrBadHeaderMsg
  615. }
  616. _, err = b.WriteString(crlf)
  617. if err != nil {
  618. return nil, ErrBadHeaderMsg
  619. }
  620. return b.Bytes(), nil
  621. }
  622. type barrierInfo struct {
  623. refs int64
  624. f func()
  625. }
  626. // Tracks various stats received and sent on this connection,
  627. // including counts for messages and bytes.
  628. type Statistics struct {
  629. InMsgs uint64
  630. OutMsgs uint64
  631. InBytes uint64
  632. OutBytes uint64
  633. Reconnects uint64
  634. }
  635. // Tracks individual backend servers.
  636. type srv struct {
  637. url *url.URL
  638. didConnect bool
  639. reconnects int
  640. lastErr error
  641. isImplicit bool
  642. tlsName string
  643. }
  644. // The INFO block received from the server.
  645. type serverInfo struct {
  646. ID string `json:"server_id"`
  647. Name string `json:"server_name"`
  648. Proto int `json:"proto"`
  649. Version string `json:"version"`
  650. Host string `json:"host"`
  651. Port int `json:"port"`
  652. Headers bool `json:"headers"`
  653. AuthRequired bool `json:"auth_required,omitempty"`
  654. TLSRequired bool `json:"tls_required,omitempty"`
  655. TLSAvailable bool `json:"tls_available,omitempty"`
  656. MaxPayload int64 `json:"max_payload"`
  657. CID uint64 `json:"client_id,omitempty"`
  658. ClientIP string `json:"client_ip,omitempty"`
  659. Nonce string `json:"nonce,omitempty"`
  660. Cluster string `json:"cluster,omitempty"`
  661. ConnectURLs []string `json:"connect_urls,omitempty"`
  662. LameDuckMode bool `json:"ldm,omitempty"`
  663. }
  664. const (
  665. // clientProtoZero is the original client protocol from 2009.
  666. // http://nats.io/documentation/internals/nats-protocol/
  667. /* clientProtoZero */ _ = iota
  668. // clientProtoInfo signals a client can receive more then the original INFO block.
  669. // This can be used to update clients on other cluster members, etc.
  670. clientProtoInfo
  671. )
  672. type connectInfo struct {
  673. Verbose bool `json:"verbose"`
  674. Pedantic bool `json:"pedantic"`
  675. UserJWT string `json:"jwt,omitempty"`
  676. Nkey string `json:"nkey,omitempty"`
  677. Signature string `json:"sig,omitempty"`
  678. User string `json:"user,omitempty"`
  679. Pass string `json:"pass,omitempty"`
  680. Token string `json:"auth_token,omitempty"`
  681. TLS bool `json:"tls_required"`
  682. Name string `json:"name"`
  683. Lang string `json:"lang"`
  684. Version string `json:"version"`
  685. Protocol int `json:"protocol"`
  686. Echo bool `json:"echo"`
  687. Headers bool `json:"headers"`
  688. NoResponders bool `json:"no_responders"`
  689. }
  690. // MsgHandler is a callback function that processes messages delivered to
  691. // asynchronous subscribers.
  692. type MsgHandler func(msg *Msg)
  693. // Connect will attempt to connect to the NATS system.
  694. // The url can contain username/password semantics. e.g. nats://derek:pass@localhost:4222
  695. // Comma separated arrays are also supported, e.g. urlA, urlB.
  696. // Options start with the defaults but can be overridden.
  697. // To connect to a NATS Server's websocket port, use the `ws` or `wss` scheme, such as
  698. // `ws://localhost:8080`. Note that websocket schemes cannot be mixed with others (nats/tls).
  699. func Connect(url string, options ...Option) (*Conn, error) {
  700. opts := GetDefaultOptions()
  701. opts.Servers = processUrlString(url)
  702. for _, opt := range options {
  703. if opt != nil {
  704. if err := opt(&opts); err != nil {
  705. return nil, err
  706. }
  707. }
  708. }
  709. return opts.Connect()
  710. }
  711. // Options that can be passed to Connect.
  712. // Name is an Option to set the client name.
  713. func Name(name string) Option {
  714. return func(o *Options) error {
  715. o.Name = name
  716. return nil
  717. }
  718. }
  719. // InProcessServer is an Option that will try to establish a direction to a NATS server
  720. // running within the process instead of dialing via TCP.
  721. func InProcessServer(server InProcessConnProvider) Option {
  722. return func(o *Options) error {
  723. o.InProcessServer = server
  724. return nil
  725. }
  726. }
  727. // Secure is an Option to enable TLS secure connections that skip server verification by default.
  728. // Pass a TLS Configuration for proper TLS.
  729. // NOTE: This should NOT be used in a production setting.
  730. func Secure(tls ...*tls.Config) Option {
  731. return func(o *Options) error {
  732. o.Secure = true
  733. // Use of variadic just simplifies testing scenarios. We only take the first one.
  734. if len(tls) > 1 {
  735. return ErrMultipleTLSConfigs
  736. }
  737. if len(tls) == 1 {
  738. o.TLSConfig = tls[0]
  739. }
  740. return nil
  741. }
  742. }
  743. // RootCAs is a helper option to provide the RootCAs pool from a list of filenames.
  744. // If Secure is not already set this will set it as well.
  745. func RootCAs(file ...string) Option {
  746. return func(o *Options) error {
  747. rootCAsCB := func() (*x509.CertPool, error) {
  748. pool := x509.NewCertPool()
  749. for _, f := range file {
  750. rootPEM, err := os.ReadFile(f)
  751. if err != nil || rootPEM == nil {
  752. return nil, fmt.Errorf("nats: error loading or parsing rootCA file: %w", err)
  753. }
  754. ok := pool.AppendCertsFromPEM(rootPEM)
  755. if !ok {
  756. return nil, fmt.Errorf("nats: failed to parse root certificate from %q", f)
  757. }
  758. }
  759. return pool, nil
  760. }
  761. if o.TLSConfig == nil {
  762. o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
  763. }
  764. if _, err := rootCAsCB(); err != nil {
  765. return err
  766. }
  767. o.RootCAsCB = rootCAsCB
  768. o.Secure = true
  769. return nil
  770. }
  771. }
  772. // ClientCert is a helper option to provide the client certificate from a file.
  773. // If Secure is not already set this will set it as well.
  774. func ClientCert(certFile, keyFile string) Option {
  775. return func(o *Options) error {
  776. tlsCertCB := func() (tls.Certificate, error) {
  777. cert, err := tls.LoadX509KeyPair(certFile, keyFile)
  778. if err != nil {
  779. return tls.Certificate{}, fmt.Errorf("nats: error loading client certificate: %w", err)
  780. }
  781. cert.Leaf, err = x509.ParseCertificate(cert.Certificate[0])
  782. if err != nil {
  783. return tls.Certificate{}, fmt.Errorf("nats: error parsing client certificate: %w", err)
  784. }
  785. return cert, nil
  786. }
  787. if o.TLSConfig == nil {
  788. o.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
  789. }
  790. if _, err := tlsCertCB(); err != nil {
  791. return err
  792. }
  793. o.TLSCertCB = tlsCertCB
  794. o.Secure = true
  795. return nil
  796. }
  797. }
  798. // NoReconnect is an Option to turn off reconnect behavior.
  799. func NoReconnect() Option {
  800. return func(o *Options) error {
  801. o.AllowReconnect = false
  802. return nil
  803. }
  804. }
  805. // DontRandomize is an Option to turn off randomizing the server pool.
  806. func DontRandomize() Option {
  807. return func(o *Options) error {
  808. o.NoRandomize = true
  809. return nil
  810. }
  811. }
  812. // NoEcho is an Option to turn off messages echoing back from a server.
  813. // Note this is supported on servers >= version 1.2. Proto 1 or greater.
  814. func NoEcho() Option {
  815. return func(o *Options) error {
  816. o.NoEcho = true
  817. return nil
  818. }
  819. }
  820. // ReconnectWait is an Option to set the wait time between reconnect attempts.
  821. // Defaults to 2s.
  822. func ReconnectWait(t time.Duration) Option {
  823. return func(o *Options) error {
  824. o.ReconnectWait = t
  825. return nil
  826. }
  827. }
  828. // MaxReconnects is an Option to set the maximum number of reconnect attempts.
  829. // If negative, it will never stop trying to reconnect.
  830. // Defaults to 60.
  831. func MaxReconnects(max int) Option {
  832. return func(o *Options) error {
  833. o.MaxReconnect = max
  834. return nil
  835. }
  836. }
  837. // ReconnectJitter is an Option to set the upper bound of a random delay added ReconnectWait.
  838. // Defaults to 100ms and 1s, respectively.
  839. func ReconnectJitter(jitter, jitterForTLS time.Duration) Option {
  840. return func(o *Options) error {
  841. o.ReconnectJitter = jitter
  842. o.ReconnectJitterTLS = jitterForTLS
  843. return nil
  844. }
  845. }
  846. // CustomReconnectDelay is an Option to set the CustomReconnectDelayCB option.
  847. // See CustomReconnectDelayCB Option for more details.
  848. func CustomReconnectDelay(cb ReconnectDelayHandler) Option {
  849. return func(o *Options) error {
  850. o.CustomReconnectDelayCB = cb
  851. return nil
  852. }
  853. }
  854. // PingInterval is an Option to set the period for client ping commands.
  855. // Defaults to 2m.
  856. func PingInterval(t time.Duration) Option {
  857. return func(o *Options) error {
  858. o.PingInterval = t
  859. return nil
  860. }
  861. }
  862. // MaxPingsOutstanding is an Option to set the maximum number of ping requests
  863. // that can go unanswered by the server before closing the connection.
  864. // Defaults to 2.
  865. func MaxPingsOutstanding(max int) Option {
  866. return func(o *Options) error {
  867. o.MaxPingsOut = max
  868. return nil
  869. }
  870. }
  871. // ReconnectBufSize sets the buffer size of messages kept while busy reconnecting.
  872. // Defaults to 8388608 bytes (8MB). It can be disabled by setting it to -1.
  873. func ReconnectBufSize(size int) Option {
  874. return func(o *Options) error {
  875. o.ReconnectBufSize = size
  876. return nil
  877. }
  878. }
  879. // Timeout is an Option to set the timeout for Dial on a connection.
  880. // Defaults to 2s.
  881. func Timeout(t time.Duration) Option {
  882. return func(o *Options) error {
  883. o.Timeout = t
  884. return nil
  885. }
  886. }
  887. // FlusherTimeout is an Option to set the write (and flush) timeout on a connection.
  888. func FlusherTimeout(t time.Duration) Option {
  889. return func(o *Options) error {
  890. o.FlusherTimeout = t
  891. return nil
  892. }
  893. }
  894. // DrainTimeout is an Option to set the timeout for draining a connection.
  895. // Defaults to 30s.
  896. func DrainTimeout(t time.Duration) Option {
  897. return func(o *Options) error {
  898. o.DrainTimeout = t
  899. return nil
  900. }
  901. }
  902. // DisconnectErrHandler is an Option to set the disconnected error handler.
  903. func DisconnectErrHandler(cb ConnErrHandler) Option {
  904. return func(o *Options) error {
  905. o.DisconnectedErrCB = cb
  906. return nil
  907. }
  908. }
  909. // DisconnectHandler is an Option to set the disconnected handler.
  910. // DEPRECATED: Use DisconnectErrHandler.
  911. func DisconnectHandler(cb ConnHandler) Option {
  912. return func(o *Options) error {
  913. o.DisconnectedCB = cb
  914. return nil
  915. }
  916. }
  917. // ConnectHandler is an Option to set the connected handler.
  918. func ConnectHandler(cb ConnHandler) Option {
  919. return func(o *Options) error {
  920. o.ConnectedCB = cb
  921. return nil
  922. }
  923. }
  924. // ReconnectHandler is an Option to set the reconnected handler.
  925. func ReconnectHandler(cb ConnHandler) Option {
  926. return func(o *Options) error {
  927. o.ReconnectedCB = cb
  928. return nil
  929. }
  930. }
  931. // ClosedHandler is an Option to set the closed handler.
  932. func ClosedHandler(cb ConnHandler) Option {
  933. return func(o *Options) error {
  934. o.ClosedCB = cb
  935. return nil
  936. }
  937. }
  938. // DiscoveredServersHandler is an Option to set the new servers handler.
  939. func DiscoveredServersHandler(cb ConnHandler) Option {
  940. return func(o *Options) error {
  941. o.DiscoveredServersCB = cb
  942. return nil
  943. }
  944. }
  945. // ErrorHandler is an Option to set the async error handler.
  946. func ErrorHandler(cb ErrHandler) Option {
  947. return func(o *Options) error {
  948. o.AsyncErrorCB = cb
  949. return nil
  950. }
  951. }
  952. // UserInfo is an Option to set the username and password to
  953. // use when not included directly in the URLs.
  954. func UserInfo(user, password string) Option {
  955. return func(o *Options) error {
  956. o.User = user
  957. o.Password = password
  958. return nil
  959. }
  960. }
  961. // Token is an Option to set the token to use
  962. // when a token is not included directly in the URLs
  963. // and when a token handler is not provided.
  964. func Token(token string) Option {
  965. return func(o *Options) error {
  966. if o.TokenHandler != nil {
  967. return ErrTokenAlreadySet
  968. }
  969. o.Token = token
  970. return nil
  971. }
  972. }
  973. // TokenHandler is an Option to set the token handler to use
  974. // when a token is not included directly in the URLs
  975. // and when a token is not set.
  976. func TokenHandler(cb AuthTokenHandler) Option {
  977. return func(o *Options) error {
  978. if o.Token != "" {
  979. return ErrTokenAlreadySet
  980. }
  981. o.TokenHandler = cb
  982. return nil
  983. }
  984. }
  985. // UserCredentials is a convenience function that takes a filename
  986. // for a user's JWT and a filename for the user's private Nkey seed.
  987. func UserCredentials(userOrChainedFile string, seedFiles ...string) Option {
  988. userCB := func() (string, error) {
  989. return userFromFile(userOrChainedFile)
  990. }
  991. var keyFile string
  992. if len(seedFiles) > 0 {
  993. keyFile = seedFiles[0]
  994. } else {
  995. keyFile = userOrChainedFile
  996. }
  997. sigCB := func(nonce []byte) ([]byte, error) {
  998. return sigHandler(nonce, keyFile)
  999. }
  1000. return UserJWT(userCB, sigCB)
  1001. }
  1002. // UserJWTAndSeed is a convenience function that takes the JWT and seed
  1003. // values as strings.
  1004. func UserJWTAndSeed(jwt string, seed string) Option {
  1005. userCB := func() (string, error) {
  1006. return jwt, nil
  1007. }
  1008. sigCB := func(nonce []byte) ([]byte, error) {
  1009. kp, err := nkeys.FromSeed([]byte(seed))
  1010. if err != nil {
  1011. return nil, fmt.Errorf("unable to extract key pair from seed: %w", err)
  1012. }
  1013. // Wipe our key on exit.
  1014. defer kp.Wipe()
  1015. sig, _ := kp.Sign(nonce)
  1016. return sig, nil
  1017. }
  1018. return UserJWT(userCB, sigCB)
  1019. }
  1020. // UserJWT will set the callbacks to retrieve the user's JWT and
  1021. // the signature callback to sign the server nonce. This an the Nkey
  1022. // option are mutually exclusive.
  1023. func UserJWT(userCB UserJWTHandler, sigCB SignatureHandler) Option {
  1024. return func(o *Options) error {
  1025. if userCB == nil {
  1026. return ErrNoUserCB
  1027. }
  1028. if sigCB == nil {
  1029. return ErrUserButNoSigCB
  1030. }
  1031. // Smoke test the user callback to ensure it is setup properly
  1032. // when processing options.
  1033. if _, err := userCB(); err != nil {
  1034. return err
  1035. }
  1036. o.UserJWT = userCB
  1037. o.SignatureCB = sigCB
  1038. return nil
  1039. }
  1040. }
  1041. // Nkey will set the public Nkey and the signature callback to
  1042. // sign the server nonce.
  1043. func Nkey(pubKey string, sigCB SignatureHandler) Option {
  1044. return func(o *Options) error {
  1045. o.Nkey = pubKey
  1046. o.SignatureCB = sigCB
  1047. if pubKey != "" && sigCB == nil {
  1048. return ErrNkeyButNoSigCB
  1049. }
  1050. return nil
  1051. }
  1052. }
  1053. // SyncQueueLen will set the maximum queue len for the internal
  1054. // channel used for SubscribeSync().
  1055. // Defaults to 65536.
  1056. func SyncQueueLen(max int) Option {
  1057. return func(o *Options) error {
  1058. o.SubChanLen = max
  1059. return nil
  1060. }
  1061. }
  1062. // Dialer is an Option to set the dialer which will be used when
  1063. // attempting to establish a connection.
  1064. // DEPRECATED: Should use CustomDialer instead.
  1065. func Dialer(dialer *net.Dialer) Option {
  1066. return func(o *Options) error {
  1067. o.Dialer = dialer
  1068. return nil
  1069. }
  1070. }
  1071. // SetCustomDialer is an Option to set a custom dialer which will be
  1072. // used when attempting to establish a connection. If both Dialer
  1073. // and CustomDialer are specified, CustomDialer takes precedence.
  1074. func SetCustomDialer(dialer CustomDialer) Option {
  1075. return func(o *Options) error {
  1076. o.CustomDialer = dialer
  1077. return nil
  1078. }
  1079. }
  1080. // UseOldRequestStyle is an Option to force usage of the old Request style.
  1081. func UseOldRequestStyle() Option {
  1082. return func(o *Options) error {
  1083. o.UseOldRequestStyle = true
  1084. return nil
  1085. }
  1086. }
  1087. // NoCallbacksAfterClientClose is an Option to disable callbacks when user code
  1088. // calls Close(). If close is initiated by any other condition, callbacks
  1089. // if any will be invoked.
  1090. func NoCallbacksAfterClientClose() Option {
  1091. return func(o *Options) error {
  1092. o.NoCallbacksAfterClientClose = true
  1093. return nil
  1094. }
  1095. }
  1096. // LameDuckModeHandler sets the callback to invoke when the server notifies
  1097. // the connection that it entered lame duck mode, that is, going to
  1098. // gradually disconnect all its connections before shutting down. This is
  1099. // often used in deployments when upgrading NATS Servers.
  1100. func LameDuckModeHandler(cb ConnHandler) Option {
  1101. return func(o *Options) error {
  1102. o.LameDuckModeHandler = cb
  1103. return nil
  1104. }
  1105. }
  1106. // RetryOnFailedConnect sets the connection in reconnecting state right away
  1107. // if it can't connect to a server in the initial set.
  1108. // See RetryOnFailedConnect option for more details.
  1109. func RetryOnFailedConnect(retry bool) Option {
  1110. return func(o *Options) error {
  1111. o.RetryOnFailedConnect = retry
  1112. return nil
  1113. }
  1114. }
  1115. // Compression is an Option to indicate if this connection supports
  1116. // compression. Currently only supported for Websocket connections.
  1117. func Compression(enabled bool) Option {
  1118. return func(o *Options) error {
  1119. o.Compression = enabled
  1120. return nil
  1121. }
  1122. }
  1123. // ProxyPath is an option for websocket connections that adds a path to connections url.
  1124. // This is useful when connecting to NATS behind a proxy.
  1125. func ProxyPath(path string) Option {
  1126. return func(o *Options) error {
  1127. o.ProxyPath = path
  1128. return nil
  1129. }
  1130. }
  1131. // CustomInboxPrefix configures the request + reply inbox prefix
  1132. func CustomInboxPrefix(p string) Option {
  1133. return func(o *Options) error {
  1134. if p == "" || strings.Contains(p, ">") || strings.Contains(p, "*") || strings.HasSuffix(p, ".") {
  1135. return fmt.Errorf("nats: invalid custom prefix")
  1136. }
  1137. o.InboxPrefix = p
  1138. return nil
  1139. }
  1140. }
  1141. // IgnoreAuthErrorAbort opts out of the default connect behavior of aborting
  1142. // subsequent reconnect attempts if server returns the same auth error twice.
  1143. func IgnoreAuthErrorAbort() Option {
  1144. return func(o *Options) error {
  1145. o.IgnoreAuthErrorAbort = true
  1146. return nil
  1147. }
  1148. }
  1149. // SkipHostLookup is an Option to skip the host lookup when connecting to a server.
  1150. func SkipHostLookup() Option {
  1151. return func(o *Options) error {
  1152. o.SkipHostLookup = true
  1153. return nil
  1154. }
  1155. }
  1156. // TLSHandshakeFirst is an Option to perform the TLS handshake first, that is
  1157. // before receiving the INFO protocol. This requires the server to also be
  1158. // configured with such option, otherwise the connection will fail.
  1159. func TLSHandshakeFirst() Option {
  1160. return func(o *Options) error {
  1161. o.TLSHandshakeFirst = true
  1162. o.Secure = true
  1163. return nil
  1164. }
  1165. }
  1166. // Handler processing
  1167. // SetDisconnectHandler will set the disconnect event handler.
  1168. // DEPRECATED: Use SetDisconnectErrHandler
  1169. func (nc *Conn) SetDisconnectHandler(dcb ConnHandler) {
  1170. if nc == nil {
  1171. return
  1172. }
  1173. nc.mu.Lock()
  1174. defer nc.mu.Unlock()
  1175. nc.Opts.DisconnectedCB = dcb
  1176. }
  1177. // SetDisconnectErrHandler will set the disconnect event handler.
  1178. func (nc *Conn) SetDisconnectErrHandler(dcb ConnErrHandler) {
  1179. if nc == nil {
  1180. return
  1181. }
  1182. nc.mu.Lock()
  1183. defer nc.mu.Unlock()
  1184. nc.Opts.DisconnectedErrCB = dcb
  1185. }
  1186. // DisconnectErrHandler will return the disconnect event handler.
  1187. func (nc *Conn) DisconnectErrHandler() ConnErrHandler {
  1188. if nc == nil {
  1189. return nil
  1190. }
  1191. nc.mu.Lock()
  1192. defer nc.mu.Unlock()
  1193. return nc.Opts.DisconnectedErrCB
  1194. }
  1195. // SetReconnectHandler will set the reconnect event handler.
  1196. func (nc *Conn) SetReconnectHandler(rcb ConnHandler) {
  1197. if nc == nil {
  1198. return
  1199. }
  1200. nc.mu.Lock()
  1201. defer nc.mu.Unlock()
  1202. nc.Opts.ReconnectedCB = rcb
  1203. }
  1204. // ReconnectHandler will return the reconnect event handler.
  1205. func (nc *Conn) ReconnectHandler() ConnHandler {
  1206. if nc == nil {
  1207. return nil
  1208. }
  1209. nc.mu.Lock()
  1210. defer nc.mu.Unlock()
  1211. return nc.Opts.ReconnectedCB
  1212. }
  1213. // SetDiscoveredServersHandler will set the discovered servers handler.
  1214. func (nc *Conn) SetDiscoveredServersHandler(dscb ConnHandler) {
  1215. if nc == nil {
  1216. return
  1217. }
  1218. nc.mu.Lock()
  1219. defer nc.mu.Unlock()
  1220. nc.Opts.DiscoveredServersCB = dscb
  1221. }
  1222. // DiscoveredServersHandler will return the discovered servers handler.
  1223. func (nc *Conn) DiscoveredServersHandler() ConnHandler {
  1224. if nc == nil {
  1225. return nil
  1226. }
  1227. nc.mu.Lock()
  1228. defer nc.mu.Unlock()
  1229. return nc.Opts.DiscoveredServersCB
  1230. }
  1231. // SetClosedHandler will set the closed event handler.
  1232. func (nc *Conn) SetClosedHandler(cb ConnHandler) {
  1233. if nc == nil {
  1234. return
  1235. }
  1236. nc.mu.Lock()
  1237. defer nc.mu.Unlock()
  1238. nc.Opts.ClosedCB = cb
  1239. }
  1240. // ClosedHandler will return the closed event handler.
  1241. func (nc *Conn) ClosedHandler() ConnHandler {
  1242. if nc == nil {
  1243. return nil
  1244. }
  1245. nc.mu.Lock()
  1246. defer nc.mu.Unlock()
  1247. return nc.Opts.ClosedCB
  1248. }
  1249. // SetErrorHandler will set the async error handler.
  1250. func (nc *Conn) SetErrorHandler(cb ErrHandler) {
  1251. if nc == nil {
  1252. return
  1253. }
  1254. nc.mu.Lock()
  1255. defer nc.mu.Unlock()
  1256. nc.Opts.AsyncErrorCB = cb
  1257. }
  1258. // ErrorHandler will return the async error handler.
  1259. func (nc *Conn) ErrorHandler() ErrHandler {
  1260. if nc == nil {
  1261. return nil
  1262. }
  1263. nc.mu.Lock()
  1264. defer nc.mu.Unlock()
  1265. return nc.Opts.AsyncErrorCB
  1266. }
  1267. // Process the url string argument to Connect.
  1268. // Return an array of urls, even if only one.
  1269. func processUrlString(url string) []string {
  1270. urls := strings.Split(url, ",")
  1271. var j int
  1272. for _, s := range urls {
  1273. u := strings.TrimSpace(s)
  1274. if len(u) > 0 {
  1275. urls[j] = u
  1276. j++
  1277. }
  1278. }
  1279. return urls[:j]
  1280. }
  1281. // Connect will attempt to connect to a NATS server with multiple options.
  1282. func (o Options) Connect() (*Conn, error) {
  1283. nc := &Conn{Opts: o}
  1284. // Some default options processing.
  1285. if nc.Opts.MaxPingsOut == 0 {
  1286. nc.Opts.MaxPingsOut = DefaultMaxPingOut
  1287. }
  1288. // Allow old default for channel length to work correctly.
  1289. if nc.Opts.SubChanLen == 0 {
  1290. nc.Opts.SubChanLen = DefaultMaxChanLen
  1291. }
  1292. // Default ReconnectBufSize
  1293. if nc.Opts.ReconnectBufSize == 0 {
  1294. nc.Opts.ReconnectBufSize = DefaultReconnectBufSize
  1295. }
  1296. // Ensure that Timeout is not 0
  1297. if nc.Opts.Timeout == 0 {
  1298. nc.Opts.Timeout = DefaultTimeout
  1299. }
  1300. // Check first for user jwt callback being defined and nkey.
  1301. if nc.Opts.UserJWT != nil && nc.Opts.Nkey != "" {
  1302. return nil, ErrNkeyAndUser
  1303. }
  1304. // Check if we have an nkey but no signature callback defined.
  1305. if nc.Opts.Nkey != "" && nc.Opts.SignatureCB == nil {
  1306. return nil, ErrNkeyButNoSigCB
  1307. }
  1308. // Allow custom Dialer for connecting using a timeout by default
  1309. if nc.Opts.Dialer == nil {
  1310. nc.Opts.Dialer = &net.Dialer{
  1311. Timeout: nc.Opts.Timeout,
  1312. }
  1313. }
  1314. // If the TLSHandshakeFirst option is specified, make sure that
  1315. // the Secure boolean is true.
  1316. if nc.Opts.TLSHandshakeFirst {
  1317. nc.Opts.Secure = true
  1318. }
  1319. if err := nc.setupServerPool(); err != nil {
  1320. return nil, err
  1321. }
  1322. // Create the async callback handler.
  1323. nc.ach = &asyncCallbacksHandler{}
  1324. nc.ach.cond = sync.NewCond(&nc.ach.mu)
  1325. // Set a default error handler that will print to stderr.
  1326. if nc.Opts.AsyncErrorCB == nil {
  1327. nc.Opts.AsyncErrorCB = defaultErrHandler
  1328. }
  1329. // Create reader/writer
  1330. nc.newReaderWriter()
  1331. connectionEstablished, err := nc.connect()
  1332. if err != nil {
  1333. return nil, err
  1334. }
  1335. // Spin up the async cb dispatcher on success
  1336. go nc.ach.asyncCBDispatcher()
  1337. if connectionEstablished && nc.Opts.ConnectedCB != nil {
  1338. nc.ach.push(func() { nc.Opts.ConnectedCB(nc) })
  1339. }
  1340. return nc, nil
  1341. }
  1342. func defaultErrHandler(nc *Conn, sub *Subscription, err error) {
  1343. var cid uint64
  1344. if nc != nil {
  1345. nc.mu.RLock()
  1346. cid = nc.info.CID
  1347. nc.mu.RUnlock()
  1348. }
  1349. var errStr string
  1350. if sub != nil {
  1351. var subject string
  1352. sub.mu.Lock()
  1353. if sub.jsi != nil {
  1354. subject = sub.jsi.psubj
  1355. } else {
  1356. subject = sub.Subject
  1357. }
  1358. sub.mu.Unlock()
  1359. errStr = fmt.Sprintf("%s on connection [%d] for subscription on %q\n", err.Error(), cid, subject)
  1360. } else {
  1361. errStr = fmt.Sprintf("%s on connection [%d]\n", err.Error(), cid)
  1362. }
  1363. os.Stderr.WriteString(errStr)
  1364. }
  1365. const (
  1366. _CRLF_ = "\r\n"
  1367. _EMPTY_ = ""
  1368. _SPC_ = " "
  1369. _PUB_P_ = "PUB "
  1370. _HPUB_P_ = "HPUB "
  1371. )
  1372. var _CRLF_BYTES_ = []byte(_CRLF_)
  1373. const (
  1374. _OK_OP_ = "+OK"
  1375. _ERR_OP_ = "-ERR"
  1376. _PONG_OP_ = "PONG"
  1377. _INFO_OP_ = "INFO"
  1378. )
  1379. const (
  1380. connectProto = "CONNECT %s" + _CRLF_
  1381. pingProto = "PING" + _CRLF_
  1382. pongProto = "PONG" + _CRLF_
  1383. subProto = "SUB %s %s %d" + _CRLF_
  1384. unsubProto = "UNSUB %d %s" + _CRLF_
  1385. okProto = _OK_OP_ + _CRLF_
  1386. )
  1387. // Return the currently selected server
  1388. func (nc *Conn) currentServer() (int, *srv) {
  1389. for i, s := range nc.srvPool {
  1390. if s == nil {
  1391. continue
  1392. }
  1393. if s == nc.current {
  1394. return i, s
  1395. }
  1396. }
  1397. return -1, nil
  1398. }
  1399. // Pop the current server and put onto the end of the list. Select head of list as long
  1400. // as number of reconnect attempts under MaxReconnect.
  1401. func (nc *Conn) selectNextServer() (*srv, error) {
  1402. i, s := nc.currentServer()
  1403. if i < 0 {
  1404. return nil, ErrNoServers
  1405. }
  1406. sp := nc.srvPool
  1407. num := len(sp)
  1408. copy(sp[i:num-1], sp[i+1:num])
  1409. maxReconnect := nc.Opts.MaxReconnect
  1410. if maxReconnect < 0 || s.reconnects < maxReconnect {
  1411. nc.srvPool[num-1] = s
  1412. } else {
  1413. nc.srvPool = sp[0 : num-1]
  1414. }
  1415. if len(nc.srvPool) <= 0 {
  1416. nc.current = nil
  1417. return nil, ErrNoServers
  1418. }
  1419. nc.current = nc.srvPool[0]
  1420. return nc.srvPool[0], nil
  1421. }
  1422. // Will assign the correct server to nc.current
  1423. func (nc *Conn) pickServer() error {
  1424. nc.current = nil
  1425. if len(nc.srvPool) <= 0 {
  1426. return ErrNoServers
  1427. }
  1428. for _, s := range nc.srvPool {
  1429. if s != nil {
  1430. nc.current = s
  1431. return nil
  1432. }
  1433. }
  1434. return ErrNoServers
  1435. }
  1436. const tlsScheme = "tls"
  1437. // Create the server pool using the options given.
  1438. // We will place a Url option first, followed by any
  1439. // Server Options. We will randomize the server pool unless
  1440. // the NoRandomize flag is set.
  1441. func (nc *Conn) setupServerPool() error {
  1442. nc.srvPool = make([]*srv, 0, srvPoolSize)
  1443. nc.urls = make(map[string]struct{}, srvPoolSize)
  1444. // Create srv objects from each url string in nc.Opts.Servers
  1445. // and add them to the pool.
  1446. for _, urlString := range nc.Opts.Servers {
  1447. if err := nc.addURLToPool(urlString, false, false); err != nil {
  1448. return err
  1449. }
  1450. }
  1451. // Randomize if allowed to
  1452. if !nc.Opts.NoRandomize {
  1453. nc.shufflePool(0)
  1454. }
  1455. // Normally, if this one is set, Options.Servers should not be,
  1456. // but we always allowed that, so continue to do so.
  1457. if nc.Opts.Url != _EMPTY_ {
  1458. // Add to the end of the array
  1459. if err := nc.addURLToPool(nc.Opts.Url, false, false); err != nil {
  1460. return err
  1461. }
  1462. // Then swap it with first to guarantee that Options.Url is tried first.
  1463. last := len(nc.srvPool) - 1
  1464. if last > 0 {
  1465. nc.srvPool[0], nc.srvPool[last] = nc.srvPool[last], nc.srvPool[0]
  1466. }
  1467. } else if len(nc.srvPool) <= 0 {
  1468. // Place default URL if pool is empty.
  1469. if err := nc.addURLToPool(DefaultURL, false, false); err != nil {
  1470. return err
  1471. }
  1472. }
  1473. // Check for Scheme hint to move to TLS mode.
  1474. for _, srv := range nc.srvPool {
  1475. if srv.url.Scheme == tlsScheme || srv.url.Scheme == wsSchemeTLS {
  1476. // FIXME(dlc), this is for all in the pool, should be case by case.
  1477. nc.Opts.Secure = true
  1478. if nc.Opts.TLSConfig == nil {
  1479. nc.Opts.TLSConfig = &tls.Config{MinVersion: tls.VersionTLS12}
  1480. }
  1481. }
  1482. }
  1483. return nc.pickServer()
  1484. }
  1485. // Helper function to return scheme
  1486. func (nc *Conn) connScheme() string {
  1487. if nc.ws {
  1488. if nc.Opts.Secure {
  1489. return wsSchemeTLS
  1490. }
  1491. return wsScheme
  1492. }
  1493. if nc.Opts.Secure {
  1494. return tlsScheme
  1495. }
  1496. return "nats"
  1497. }
  1498. // Return true iff u.Hostname() is an IP address.
  1499. func hostIsIP(u *url.URL) bool {
  1500. return net.ParseIP(u.Hostname()) != nil
  1501. }
  1502. // addURLToPool adds an entry to the server pool
  1503. func (nc *Conn) addURLToPool(sURL string, implicit, saveTLSName bool) error {
  1504. if !strings.Contains(sURL, "://") {
  1505. sURL = fmt.Sprintf("%s://%s", nc.connScheme(), sURL)
  1506. }
  1507. var (
  1508. u *url.URL
  1509. err error
  1510. )
  1511. for i := 0; i < 2; i++ {
  1512. u, err = url.Parse(sURL)
  1513. if err != nil {
  1514. return err
  1515. }
  1516. if u.Port() != "" {
  1517. break
  1518. }
  1519. // In case given URL is of the form "localhost:", just add
  1520. // the port number at the end, otherwise, add ":4222".
  1521. if sURL[len(sURL)-1] != ':' {
  1522. sURL += ":"
  1523. }
  1524. switch u.Scheme {
  1525. case wsScheme:
  1526. sURL += defaultWSPortString
  1527. case wsSchemeTLS:
  1528. sURL += defaultWSSPortString
  1529. default:
  1530. sURL += defaultPortString
  1531. }
  1532. }
  1533. isWS := isWebsocketScheme(u)
  1534. // We don't support mix and match of websocket and non websocket URLs.
  1535. // If this is the first URL, then we accept and switch the global state
  1536. // to websocket. After that, we will know how to reject mixed URLs.
  1537. if len(nc.srvPool) == 0 {
  1538. nc.ws = isWS
  1539. } else if isWS && !nc.ws || !isWS && nc.ws {
  1540. return fmt.Errorf("mixing of websocket and non websocket URLs is not allowed")
  1541. }
  1542. var tlsName string
  1543. if implicit {
  1544. curl := nc.current.url
  1545. // Check to see if we do not have a url.User but current connected
  1546. // url does. If so copy over.
  1547. if u.User == nil && curl.User != nil {
  1548. u.User = curl.User
  1549. }
  1550. // We are checking to see if we have a secure connection and are
  1551. // adding an implicit server that just has an IP. If so we will remember
  1552. // the current hostname we are connected to.
  1553. if saveTLSName && hostIsIP(u) {
  1554. tlsName = curl.Hostname()
  1555. }
  1556. }
  1557. s := &srv{url: u, isImplicit: implicit, tlsName: tlsName}
  1558. nc.srvPool = append(nc.srvPool, s)
  1559. nc.urls[u.Host] = struct{}{}
  1560. return nil
  1561. }
  1562. // shufflePool swaps randomly elements in the server pool
  1563. // The `offset` value indicates that the shuffling should start at
  1564. // this offset and leave the elements from [0..offset) intact.
  1565. func (nc *Conn) shufflePool(offset int) {
  1566. if len(nc.srvPool) <= offset+1 {
  1567. return
  1568. }
  1569. source := rand.NewSource(time.Now().UnixNano())
  1570. r := rand.New(source)
  1571. for i := offset; i < len(nc.srvPool); i++ {
  1572. j := offset + r.Intn(i+1-offset)
  1573. nc.srvPool[i], nc.srvPool[j] = nc.srvPool[j], nc.srvPool[i]
  1574. }
  1575. }
  1576. func (nc *Conn) newReaderWriter() {
  1577. nc.br = &natsReader{
  1578. buf: make([]byte, defaultBufSize),
  1579. off: -1,
  1580. }
  1581. nc.bw = &natsWriter{
  1582. limit: defaultBufSize,
  1583. plimit: nc.Opts.ReconnectBufSize,
  1584. }
  1585. }
  1586. func (nc *Conn) bindToNewConn() {
  1587. bw := nc.bw
  1588. bw.w, bw.bufs = nc.newWriter(), nil
  1589. br := nc.br
  1590. br.r, br.n, br.off = nc.conn, 0, -1
  1591. }
  1592. func (nc *Conn) newWriter() io.Writer {
  1593. var w io.Writer = nc.conn
  1594. if nc.Opts.FlusherTimeout > 0 {
  1595. w = &timeoutWriter{conn: nc.conn, timeout: nc.Opts.FlusherTimeout}
  1596. }
  1597. return w
  1598. }
  1599. func (w *natsWriter) appendString(str string) error {
  1600. return w.appendBufs([]byte(str))
  1601. }
  1602. func (w *natsWriter) appendBufs(bufs ...[]byte) error {
  1603. for _, buf := range bufs {
  1604. if len(buf) == 0 {
  1605. continue
  1606. }
  1607. if w.pending != nil {
  1608. w.pending.Write(buf)
  1609. } else {
  1610. w.bufs = append(w.bufs, buf...)
  1611. }
  1612. }
  1613. if w.pending == nil && len(w.bufs) >= w.limit {
  1614. return w.flush()
  1615. }
  1616. return nil
  1617. }
  1618. func (w *natsWriter) writeDirect(strs ...string) error {
  1619. for _, str := range strs {
  1620. if _, err := w.w.Write([]byte(str)); err != nil {
  1621. return err
  1622. }
  1623. }
  1624. return nil
  1625. }
  1626. func (w *natsWriter) flush() error {
  1627. // If a pending buffer is set, we don't flush. Code that needs to
  1628. // write directly to the socket, by-passing buffers during (re)connect,
  1629. // will use the writeDirect() API.
  1630. if w.pending != nil {
  1631. return nil
  1632. }
  1633. // Do not skip calling w.w.Write() here if len(w.bufs) is 0 because
  1634. // the actual writer (if websocket for instance) may have things
  1635. // to do such as sending control frames, etc..
  1636. _, err := w.w.Write(w.bufs)
  1637. w.bufs = w.bufs[:0]
  1638. return err
  1639. }
  1640. func (w *natsWriter) buffered() int {
  1641. if w.pending != nil {
  1642. return w.pending.Len()
  1643. }
  1644. return len(w.bufs)
  1645. }
  1646. func (w *natsWriter) switchToPending() {
  1647. w.pending = new(bytes.Buffer)
  1648. }
  1649. func (w *natsWriter) flushPendingBuffer() error {
  1650. if w.pending == nil || w.pending.Len() == 0 {
  1651. return nil
  1652. }
  1653. _, err := w.w.Write(w.pending.Bytes())
  1654. // Reset the pending buffer at this point because we don't want
  1655. // to take the risk of sending duplicates or partials.
  1656. w.pending.Reset()
  1657. return err
  1658. }
  1659. func (w *natsWriter) atLimitIfUsingPending() bool {
  1660. if w.pending == nil {
  1661. return false
  1662. }
  1663. return w.pending.Len() >= w.plimit
  1664. }
  1665. func (w *natsWriter) doneWithPending() {
  1666. w.pending = nil
  1667. }
  1668. // Notify the reader that we are done with the connect, where "read" operations
  1669. // happen synchronously and under the connection lock. After this point, "read"
  1670. // will be happening from the read loop, without the connection lock.
  1671. //
  1672. // Note: this runs under the connection lock.
  1673. func (r *natsReader) doneWithConnect() {
  1674. if wsr, ok := r.r.(*websocketReader); ok {
  1675. wsr.doneWithConnect()
  1676. }
  1677. }
  1678. func (r *natsReader) Read() ([]byte, error) {
  1679. if r.off >= 0 {
  1680. off := r.off
  1681. r.off = -1
  1682. return r.buf[off:r.n], nil
  1683. }
  1684. var err error
  1685. r.n, err = r.r.Read(r.buf)
  1686. return r.buf[:r.n], err
  1687. }
  1688. func (r *natsReader) ReadString(delim byte) (string, error) {
  1689. var s string
  1690. build_string:
  1691. // First look if we have something in the buffer
  1692. if r.off >= 0 {
  1693. i := bytes.IndexByte(r.buf[r.off:r.n], delim)
  1694. if i >= 0 {
  1695. end := r.off + i + 1
  1696. s += string(r.buf[r.off:end])
  1697. r.off = end
  1698. if r.off >= r.n {
  1699. r.off = -1
  1700. }
  1701. return s, nil
  1702. }
  1703. // We did not find the delim, so will have to read more.
  1704. s += string(r.buf[r.off:r.n])
  1705. r.off = -1
  1706. }
  1707. if _, err := r.Read(); err != nil {
  1708. return s, err
  1709. }
  1710. r.off = 0
  1711. goto build_string
  1712. }
  1713. // createConn will connect to the server and wrap the appropriate
  1714. // bufio structures. It will do the right thing when an existing
  1715. // connection is in place.
  1716. func (nc *Conn) createConn() (err error) {
  1717. if nc.Opts.Timeout < 0 {
  1718. return ErrBadTimeout
  1719. }
  1720. if _, cur := nc.currentServer(); cur == nil {
  1721. return ErrNoServers
  1722. }
  1723. // If we have a reference to an in-process server then establish a
  1724. // connection using that.
  1725. if nc.Opts.InProcessServer != nil {
  1726. conn, err := nc.Opts.InProcessServer.InProcessConn()
  1727. if err != nil {
  1728. return fmt.Errorf("failed to get in-process connection: %w", err)
  1729. }
  1730. nc.conn = conn
  1731. nc.bindToNewConn()
  1732. return nil
  1733. }
  1734. // We will auto-expand host names if they resolve to multiple IPs
  1735. hosts := []string{}
  1736. u := nc.current.url
  1737. if !nc.Opts.SkipHostLookup && net.ParseIP(u.Hostname()) == nil {
  1738. addrs, _ := net.LookupHost(u.Hostname())
  1739. for _, addr := range addrs {
  1740. hosts = append(hosts, net.JoinHostPort(addr, u.Port()))
  1741. }
  1742. }
  1743. // Fall back to what we were given.
  1744. if len(hosts) == 0 {
  1745. hosts = append(hosts, u.Host)
  1746. }
  1747. // CustomDialer takes precedence. If not set, use Opts.Dialer which
  1748. // is set to a default *net.Dialer (in Connect()) if not explicitly
  1749. // set by the user.
  1750. dialer := nc.Opts.CustomDialer
  1751. if dialer == nil {
  1752. // We will copy and shorten the timeout if we have multiple hosts to try.
  1753. copyDialer := *nc.Opts.Dialer
  1754. copyDialer.Timeout = copyDialer.Timeout / time.Duration(len(hosts))
  1755. dialer = &copyDialer
  1756. }
  1757. if len(hosts) > 1 && !nc.Opts.NoRandomize {
  1758. rand.Shuffle(len(hosts), func(i, j int) {
  1759. hosts[i], hosts[j] = hosts[j], hosts[i]
  1760. })
  1761. }
  1762. for _, host := range hosts {
  1763. nc.conn, err = dialer.Dial("tcp", host)
  1764. if err == nil {
  1765. break
  1766. }
  1767. }
  1768. if err != nil {
  1769. return err
  1770. }
  1771. // If scheme starts with "ws" then branch out to websocket code.
  1772. if isWebsocketScheme(u) {
  1773. return nc.wsInitHandshake(u)
  1774. }
  1775. // Reset reader/writer to this new TCP connection
  1776. nc.bindToNewConn()
  1777. return nil
  1778. }
  1779. type skipTLSDialer interface {
  1780. SkipTLSHandshake() bool
  1781. }
  1782. // makeTLSConn will wrap an existing Conn using TLS
  1783. func (nc *Conn) makeTLSConn() error {
  1784. if nc.Opts.CustomDialer != nil {
  1785. // we do nothing when asked to skip the TLS wrapper
  1786. sd, ok := nc.Opts.CustomDialer.(skipTLSDialer)
  1787. if ok && sd.SkipTLSHandshake() {
  1788. return nil
  1789. }
  1790. }
  1791. // Allow the user to configure their own tls.Config structure.
  1792. tlsCopy := &tls.Config{}
  1793. if nc.Opts.TLSConfig != nil {
  1794. tlsCopy = util.CloneTLSConfig(nc.Opts.TLSConfig)
  1795. }
  1796. if nc.Opts.TLSCertCB != nil {
  1797. cert, err := nc.Opts.TLSCertCB()
  1798. if err != nil {
  1799. return err
  1800. }
  1801. tlsCopy.Certificates = []tls.Certificate{cert}
  1802. }
  1803. if nc.Opts.RootCAsCB != nil {
  1804. rootCAs, err := nc.Opts.RootCAsCB()
  1805. if err != nil {
  1806. return err
  1807. }
  1808. tlsCopy.RootCAs = rootCAs
  1809. }
  1810. // If its blank we will override it with the current host
  1811. if tlsCopy.ServerName == _EMPTY_ {
  1812. if nc.current.tlsName != _EMPTY_ {
  1813. tlsCopy.ServerName = nc.current.tlsName
  1814. } else {
  1815. h, _, _ := net.SplitHostPort(nc.current.url.Host)
  1816. tlsCopy.ServerName = h
  1817. }
  1818. }
  1819. nc.conn = tls.Client(nc.conn, tlsCopy)
  1820. conn := nc.conn.(*tls.Conn)
  1821. if err := conn.Handshake(); err != nil {
  1822. return err
  1823. }
  1824. nc.bindToNewConn()
  1825. return nil
  1826. }
  1827. // TLSConnectionState retrieves the state of the TLS connection to the server
  1828. func (nc *Conn) TLSConnectionState() (tls.ConnectionState, error) {
  1829. if !nc.isConnected() {
  1830. return tls.ConnectionState{}, ErrDisconnected
  1831. }
  1832. nc.mu.RLock()
  1833. conn := nc.conn
  1834. nc.mu.RUnlock()
  1835. tc, ok := conn.(*tls.Conn)
  1836. if !ok {
  1837. return tls.ConnectionState{}, ErrConnectionNotTLS
  1838. }
  1839. return tc.ConnectionState(), nil
  1840. }
  1841. // waitForExits will wait for all socket watcher Go routines to
  1842. // be shutdown before proceeding.
  1843. func (nc *Conn) waitForExits() {
  1844. // Kick old flusher forcefully.
  1845. select {
  1846. case nc.fch <- struct{}{}:
  1847. default:
  1848. }
  1849. // Wait for any previous go routines.
  1850. nc.wg.Wait()
  1851. }
  1852. // ConnectedUrl reports the connected server's URL
  1853. func (nc *Conn) ConnectedUrl() string {
  1854. if nc == nil {
  1855. return _EMPTY_
  1856. }
  1857. nc.mu.RLock()
  1858. defer nc.mu.RUnlock()
  1859. if nc.status != CONNECTED {
  1860. return _EMPTY_
  1861. }
  1862. return nc.current.url.String()
  1863. }
  1864. // ConnectedUrlRedacted reports the connected server's URL with passwords redacted
  1865. func (nc *Conn) ConnectedUrlRedacted() string {
  1866. if nc == nil {
  1867. return _EMPTY_
  1868. }
  1869. nc.mu.RLock()
  1870. defer nc.mu.RUnlock()
  1871. if nc.status != CONNECTED {
  1872. return _EMPTY_
  1873. }
  1874. return nc.current.url.Redacted()
  1875. }
  1876. // ConnectedAddr returns the connected server's IP
  1877. func (nc *Conn) ConnectedAddr() string {
  1878. if nc == nil {
  1879. return _EMPTY_
  1880. }
  1881. nc.mu.RLock()
  1882. defer nc.mu.RUnlock()
  1883. if nc.status != CONNECTED {
  1884. return _EMPTY_
  1885. }
  1886. return nc.conn.RemoteAddr().String()
  1887. }
  1888. // ConnectedServerId reports the connected server's Id
  1889. func (nc *Conn) ConnectedServerId() string {
  1890. if nc == nil {
  1891. return _EMPTY_
  1892. }
  1893. nc.mu.RLock()
  1894. defer nc.mu.RUnlock()
  1895. if nc.status != CONNECTED {
  1896. return _EMPTY_
  1897. }
  1898. return nc.info.ID
  1899. }
  1900. // ConnectedServerName reports the connected server's name
  1901. func (nc *Conn) ConnectedServerName() string {
  1902. if nc == nil {
  1903. return _EMPTY_
  1904. }
  1905. nc.mu.RLock()
  1906. defer nc.mu.RUnlock()
  1907. if nc.status != CONNECTED {
  1908. return _EMPTY_
  1909. }
  1910. return nc.info.Name
  1911. }
  1912. var semVerRe = regexp.MustCompile(`\Av?([0-9]+)\.?([0-9]+)?\.?([0-9]+)?`)
  1913. func versionComponents(version string) (major, minor, patch int, err error) {
  1914. m := semVerRe.FindStringSubmatch(version)
  1915. if m == nil {
  1916. return 0, 0, 0, errors.New("invalid semver")
  1917. }
  1918. major, err = strconv.Atoi(m[1])
  1919. if err != nil {
  1920. return -1, -1, -1, err
  1921. }
  1922. minor, err = strconv.Atoi(m[2])
  1923. if err != nil {
  1924. return -1, -1, -1, err
  1925. }
  1926. patch, err = strconv.Atoi(m[3])
  1927. if err != nil {
  1928. return -1, -1, -1, err
  1929. }
  1930. return major, minor, patch, err
  1931. }
  1932. // Check for minimum server requirement.
  1933. func (nc *Conn) serverMinVersion(major, minor, patch int) bool {
  1934. smajor, sminor, spatch, _ := versionComponents(nc.ConnectedServerVersion())
  1935. if smajor < major || (smajor == major && sminor < minor) || (smajor == major && sminor == minor && spatch < patch) {
  1936. return false
  1937. }
  1938. return true
  1939. }
  1940. // ConnectedServerVersion reports the connected server's version as a string
  1941. func (nc *Conn) ConnectedServerVersion() string {
  1942. if nc == nil {
  1943. return _EMPTY_
  1944. }
  1945. nc.mu.RLock()
  1946. defer nc.mu.RUnlock()
  1947. if nc.status != CONNECTED {
  1948. return _EMPTY_
  1949. }
  1950. return nc.info.Version
  1951. }
  1952. // ConnectedClusterName reports the connected server's cluster name if any
  1953. func (nc *Conn) ConnectedClusterName() string {
  1954. if nc == nil {
  1955. return _EMPTY_
  1956. }
  1957. nc.mu.RLock()
  1958. defer nc.mu.RUnlock()
  1959. if nc.status != CONNECTED {
  1960. return _EMPTY_
  1961. }
  1962. return nc.info.Cluster
  1963. }
  1964. // Low level setup for structs, etc
  1965. func (nc *Conn) setup() {
  1966. nc.subs = make(map[int64]*Subscription)
  1967. nc.pongs = make([]chan struct{}, 0, 8)
  1968. nc.fch = make(chan struct{}, flushChanSize)
  1969. nc.rqch = make(chan struct{})
  1970. // Setup scratch outbound buffer for PUB/HPUB
  1971. pub := nc.scratch[:len(_HPUB_P_)]
  1972. copy(pub, _HPUB_P_)
  1973. }
  1974. // Process a connected connection and initialize properly.
  1975. func (nc *Conn) processConnectInit() error {
  1976. // Set our deadline for the whole connect process
  1977. nc.conn.SetDeadline(time.Now().Add(nc.Opts.Timeout))
  1978. defer nc.conn.SetDeadline(time.Time{})
  1979. // Set our status to connecting.
  1980. nc.changeConnStatus(CONNECTING)
  1981. // If we need to have a TLS connection and want the TLS handshake to occur
  1982. // first, do it now.
  1983. if nc.Opts.Secure && nc.Opts.TLSHandshakeFirst {
  1984. if err := nc.makeTLSConn(); err != nil {
  1985. return err
  1986. }
  1987. }
  1988. // Process the INFO protocol received from the server
  1989. err := nc.processExpectedInfo()
  1990. if err != nil {
  1991. return err
  1992. }
  1993. // Send the CONNECT protocol along with the initial PING protocol.
  1994. // Wait for the PONG response (or any error that we get from the server).
  1995. err = nc.sendConnect()
  1996. if err != nil {
  1997. return err
  1998. }
  1999. // Reset the number of PING sent out
  2000. nc.pout = 0
  2001. // Start or reset Timer
  2002. if nc.Opts.PingInterval > 0 {
  2003. if nc.ptmr == nil {
  2004. nc.ptmr = time.AfterFunc(nc.Opts.PingInterval, nc.processPingTimer)
  2005. } else {
  2006. nc.ptmr.Reset(nc.Opts.PingInterval)
  2007. }
  2008. }
  2009. // Start the readLoop and flusher go routines, we will wait on both on a reconnect event.
  2010. nc.wg.Add(2)
  2011. go nc.readLoop()
  2012. go nc.flusher()
  2013. // Notify the reader that we are done with the connect handshake, where
  2014. // reads were done synchronously and under the connection lock.
  2015. nc.br.doneWithConnect()
  2016. return nil
  2017. }
  2018. // Main connect function. Will connect to the nats-server.
  2019. func (nc *Conn) connect() (bool, error) {
  2020. var err error
  2021. var connectionEstablished bool
  2022. // Create actual socket connection
  2023. // For first connect we walk all servers in the pool and try
  2024. // to connect immediately.
  2025. nc.mu.Lock()
  2026. defer nc.mu.Unlock()
  2027. nc.initc = true
  2028. // The pool may change inside the loop iteration due to INFO protocol.
  2029. for i := 0; i < len(nc.srvPool); i++ {
  2030. nc.current = nc.srvPool[i]
  2031. if err = nc.createConn(); err == nil {
  2032. // This was moved out of processConnectInit() because
  2033. // that function is now invoked from doReconnect() too.
  2034. nc.setup()
  2035. err = nc.processConnectInit()
  2036. if err == nil {
  2037. nc.current.didConnect = true
  2038. nc.current.reconnects = 0
  2039. nc.current.lastErr = nil
  2040. break
  2041. } else {
  2042. nc.mu.Unlock()
  2043. nc.close(DISCONNECTED, false, err)
  2044. nc.mu.Lock()
  2045. // Do not reset nc.current here since it would prevent
  2046. // RetryOnFailedConnect to work should this be the last server
  2047. // to try before starting doReconnect().
  2048. }
  2049. } else {
  2050. // Cancel out default connection refused, will trigger the
  2051. // No servers error conditional
  2052. if strings.Contains(err.Error(), "connection refused") {
  2053. err = nil
  2054. }
  2055. }
  2056. }
  2057. if err == nil && nc.status != CONNECTED {
  2058. err = ErrNoServers
  2059. }
  2060. if err == nil {
  2061. connectionEstablished = true
  2062. nc.initc = false
  2063. } else if nc.Opts.RetryOnFailedConnect {
  2064. nc.setup()
  2065. nc.changeConnStatus(RECONNECTING)
  2066. nc.bw.switchToPending()
  2067. go nc.doReconnect(ErrNoServers)
  2068. err = nil
  2069. } else {
  2070. nc.current = nil
  2071. }
  2072. return connectionEstablished, err
  2073. }
  2074. // This will check to see if the connection should be
  2075. // secure. This can be dictated from either end and should
  2076. // only be called after the INIT protocol has been received.
  2077. func (nc *Conn) checkForSecure() error {
  2078. // Check to see if we need to engage TLS
  2079. o := nc.Opts
  2080. // Check for mismatch in setups
  2081. if o.Secure && !nc.info.TLSRequired && !nc.info.TLSAvailable {
  2082. return ErrSecureConnWanted
  2083. } else if nc.info.TLSRequired && !o.Secure {
  2084. // Switch to Secure since server needs TLS.
  2085. o.Secure = true
  2086. }
  2087. if o.Secure {
  2088. // If TLS handshake first is true, we have already done
  2089. // the handshake, so we are done here.
  2090. if o.TLSHandshakeFirst {
  2091. return nil
  2092. }
  2093. // Need to rewrap with bufio
  2094. if err := nc.makeTLSConn(); err != nil {
  2095. return err
  2096. }
  2097. }
  2098. return nil
  2099. }
  2100. // processExpectedInfo will look for the expected first INFO message
  2101. // sent when a connection is established. The lock should be held entering.
  2102. func (nc *Conn) processExpectedInfo() error {
  2103. c := &control{}
  2104. // Read the protocol
  2105. err := nc.readOp(c)
  2106. if err != nil {
  2107. return err
  2108. }
  2109. // The nats protocol should send INFO first always.
  2110. if c.op != _INFO_OP_ {
  2111. return ErrNoInfoReceived
  2112. }
  2113. // Parse the protocol
  2114. if err := nc.processInfo(c.args); err != nil {
  2115. return err
  2116. }
  2117. if nc.Opts.Nkey != "" && nc.info.Nonce == "" {
  2118. return ErrNkeysNotSupported
  2119. }
  2120. // For websocket connections, we already switched to TLS if need be,
  2121. // so we are done here.
  2122. if nc.ws {
  2123. return nil
  2124. }
  2125. return nc.checkForSecure()
  2126. }
  2127. // Sends a protocol control message by queuing into the bufio writer
  2128. // and kicking the flush Go routine. These writes are protected.
  2129. func (nc *Conn) sendProto(proto string) {
  2130. nc.mu.Lock()
  2131. nc.bw.appendString(proto)
  2132. nc.kickFlusher()
  2133. nc.mu.Unlock()
  2134. }
  2135. // Generate a connect protocol message, issuing user/password if
  2136. // applicable. The lock is assumed to be held upon entering.
  2137. func (nc *Conn) connectProto() (string, error) {
  2138. o := nc.Opts
  2139. var nkey, sig, user, pass, token, ujwt string
  2140. u := nc.current.url.User
  2141. if u != nil {
  2142. // if no password, assume username is authToken
  2143. if _, ok := u.Password(); !ok {
  2144. token = u.Username()
  2145. } else {
  2146. user = u.Username()
  2147. pass, _ = u.Password()
  2148. }
  2149. } else {
  2150. // Take from options (possibly all empty strings)
  2151. user = o.User
  2152. pass = o.Password
  2153. token = o.Token
  2154. nkey = o.Nkey
  2155. }
  2156. // Look for user jwt.
  2157. if o.UserJWT != nil {
  2158. if jwt, err := o.UserJWT(); err != nil {
  2159. return _EMPTY_, err
  2160. } else {
  2161. ujwt = jwt
  2162. }
  2163. if nkey != _EMPTY_ {
  2164. return _EMPTY_, ErrNkeyAndUser
  2165. }
  2166. }
  2167. if ujwt != _EMPTY_ || nkey != _EMPTY_ {
  2168. if o.SignatureCB == nil {
  2169. if ujwt == _EMPTY_ {
  2170. return _EMPTY_, ErrNkeyButNoSigCB
  2171. }
  2172. return _EMPTY_, ErrUserButNoSigCB
  2173. }
  2174. sigraw, err := o.SignatureCB([]byte(nc.info.Nonce))
  2175. if err != nil {
  2176. return _EMPTY_, fmt.Errorf("error signing nonce: %w", err)
  2177. }
  2178. sig = base64.RawURLEncoding.EncodeToString(sigraw)
  2179. }
  2180. if nc.Opts.TokenHandler != nil {
  2181. if token != _EMPTY_ {
  2182. return _EMPTY_, ErrTokenAlreadySet
  2183. }
  2184. token = nc.Opts.TokenHandler()
  2185. }
  2186. // If our server does not support headers then we can't do them or no responders.
  2187. hdrs := nc.info.Headers
  2188. cinfo := connectInfo{o.Verbose, o.Pedantic, ujwt, nkey, sig, user, pass, token,
  2189. o.Secure, o.Name, LangString, Version, clientProtoInfo, !o.NoEcho, hdrs, hdrs}
  2190. b, err := json.Marshal(cinfo)
  2191. if err != nil {
  2192. return _EMPTY_, ErrJsonParse
  2193. }
  2194. // Check if NoEcho is set and we have a server that supports it.
  2195. if o.NoEcho && nc.info.Proto < 1 {
  2196. return _EMPTY_, ErrNoEchoNotSupported
  2197. }
  2198. return fmt.Sprintf(connectProto, b), nil
  2199. }
  2200. // normalizeErr removes the prefix -ERR, trim spaces and remove the quotes.
  2201. func normalizeErr(line string) string {
  2202. s := strings.TrimSpace(strings.TrimPrefix(line, _ERR_OP_))
  2203. s = strings.TrimLeft(strings.TrimRight(s, "'"), "'")
  2204. return s
  2205. }
  2206. // natsProtoErr represents an -ERR protocol message sent by the server.
  2207. type natsProtoErr struct {
  2208. description string
  2209. }
  2210. func (nerr *natsProtoErr) Error() string {
  2211. return fmt.Sprintf("nats: %s", nerr.description)
  2212. }
  2213. func (nerr *natsProtoErr) Is(err error) bool {
  2214. return strings.ToLower(nerr.Error()) == err.Error()
  2215. }
  2216. // Send a connect protocol message to the server, issue user/password if
  2217. // applicable. Will wait for a flush to return from the server for error
  2218. // processing.
  2219. func (nc *Conn) sendConnect() error {
  2220. // Construct the CONNECT protocol string
  2221. cProto, err := nc.connectProto()
  2222. if err != nil {
  2223. if !nc.initc && nc.Opts.AsyncErrorCB != nil {
  2224. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
  2225. }
  2226. return err
  2227. }
  2228. // Write the protocol and PING directly to the underlying writer.
  2229. if err := nc.bw.writeDirect(cProto, pingProto); err != nil {
  2230. return err
  2231. }
  2232. // We don't want to read more than we need here, otherwise
  2233. // we would need to transfer the excess read data to the readLoop.
  2234. // Since in normal situations we just are looking for a PONG\r\n,
  2235. // reading byte-by-byte here is ok.
  2236. proto, err := nc.readProto()
  2237. if err != nil {
  2238. if !nc.initc && nc.Opts.AsyncErrorCB != nil {
  2239. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
  2240. }
  2241. return err
  2242. }
  2243. // If opts.Verbose is set, handle +OK
  2244. if nc.Opts.Verbose && proto == okProto {
  2245. // Read the rest now...
  2246. proto, err = nc.readProto()
  2247. if err != nil {
  2248. if !nc.initc && nc.Opts.AsyncErrorCB != nil {
  2249. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
  2250. }
  2251. return err
  2252. }
  2253. }
  2254. // We expect a PONG
  2255. if proto != pongProto {
  2256. // But it could be something else, like -ERR
  2257. // Since we no longer use ReadLine(), trim the trailing "\r\n"
  2258. proto = strings.TrimRight(proto, "\r\n")
  2259. // If it's a server error...
  2260. if strings.HasPrefix(proto, _ERR_OP_) {
  2261. // Remove -ERR, trim spaces and quotes, and convert to lower case.
  2262. proto = normalizeErr(proto)
  2263. // Check if this is an auth error
  2264. if authErr := checkAuthError(strings.ToLower(proto)); authErr != nil {
  2265. // This will schedule an async error if we are in reconnect,
  2266. // and keep track of the auth error for the current server.
  2267. // If we have got the same error twice, this sets nc.ar to true to
  2268. // indicate that the reconnect should be aborted (will be checked
  2269. // in doReconnect()).
  2270. nc.processAuthError(authErr)
  2271. }
  2272. return &natsProtoErr{proto}
  2273. }
  2274. // Notify that we got an unexpected protocol.
  2275. return fmt.Errorf("nats: expected '%s', got '%s'", _PONG_OP_, proto)
  2276. }
  2277. // This is where we are truly connected.
  2278. nc.changeConnStatus(CONNECTED)
  2279. return nil
  2280. }
  2281. // reads a protocol line.
  2282. func (nc *Conn) readProto() (string, error) {
  2283. return nc.br.ReadString('\n')
  2284. }
  2285. // A control protocol line.
  2286. type control struct {
  2287. op, args string
  2288. }
  2289. // Read a control line and process the intended op.
  2290. func (nc *Conn) readOp(c *control) error {
  2291. line, err := nc.readProto()
  2292. if err != nil {
  2293. return err
  2294. }
  2295. parseControl(line, c)
  2296. return nil
  2297. }
  2298. // Parse a control line from the server.
  2299. func parseControl(line string, c *control) {
  2300. toks := strings.SplitN(line, _SPC_, 2)
  2301. if len(toks) == 1 {
  2302. c.op = strings.TrimSpace(toks[0])
  2303. c.args = _EMPTY_
  2304. } else if len(toks) == 2 {
  2305. c.op, c.args = strings.TrimSpace(toks[0]), strings.TrimSpace(toks[1])
  2306. } else {
  2307. c.op = _EMPTY_
  2308. }
  2309. }
  2310. // flushReconnectPendingItems will push the pending items that were
  2311. // gathered while we were in a RECONNECTING state to the socket.
  2312. func (nc *Conn) flushReconnectPendingItems() error {
  2313. return nc.bw.flushPendingBuffer()
  2314. }
  2315. // Stops the ping timer if set.
  2316. // Connection lock is held on entry.
  2317. func (nc *Conn) stopPingTimer() {
  2318. if nc.ptmr != nil {
  2319. nc.ptmr.Stop()
  2320. }
  2321. }
  2322. // Try to reconnect using the option parameters.
  2323. // This function assumes we are allowed to reconnect.
  2324. func (nc *Conn) doReconnect(err error) {
  2325. // We want to make sure we have the other watchers shutdown properly
  2326. // here before we proceed past this point.
  2327. nc.waitForExits()
  2328. // FIXME(dlc) - We have an issue here if we have
  2329. // outstanding flush points (pongs) and they were not
  2330. // sent out, but are still in the pipe.
  2331. // Hold the lock manually and release where needed below,
  2332. // can't do defer here.
  2333. nc.mu.Lock()
  2334. // Clear any errors.
  2335. nc.err = nil
  2336. // Perform appropriate callback if needed for a disconnect.
  2337. // DisconnectedErrCB has priority over deprecated DisconnectedCB
  2338. if !nc.initc {
  2339. if nc.Opts.DisconnectedErrCB != nil {
  2340. nc.ach.push(func() { nc.Opts.DisconnectedErrCB(nc, err) })
  2341. } else if nc.Opts.DisconnectedCB != nil {
  2342. nc.ach.push(func() { nc.Opts.DisconnectedCB(nc) })
  2343. }
  2344. }
  2345. // This is used to wait on go routines exit if we start them in the loop
  2346. // but an error occurs after that.
  2347. waitForGoRoutines := false
  2348. var rt *time.Timer
  2349. // Channel used to kick routine out of sleep when conn is closed.
  2350. rqch := nc.rqch
  2351. // Counter that is increased when the whole list of servers has been tried.
  2352. var wlf int
  2353. var jitter time.Duration
  2354. var rw time.Duration
  2355. // If a custom reconnect delay handler is set, this takes precedence.
  2356. crd := nc.Opts.CustomReconnectDelayCB
  2357. if crd == nil {
  2358. rw = nc.Opts.ReconnectWait
  2359. // TODO: since we sleep only after the whole list has been tried, we can't
  2360. // rely on individual *srv to know if it is a TLS or non-TLS url.
  2361. // We have to pick which type of jitter to use, for now, we use these hints:
  2362. jitter = nc.Opts.ReconnectJitter
  2363. if nc.Opts.Secure || nc.Opts.TLSConfig != nil {
  2364. jitter = nc.Opts.ReconnectJitterTLS
  2365. }
  2366. }
  2367. for i := 0; len(nc.srvPool) > 0; {
  2368. cur, err := nc.selectNextServer()
  2369. if err != nil {
  2370. nc.err = err
  2371. break
  2372. }
  2373. doSleep := i+1 >= len(nc.srvPool)
  2374. nc.mu.Unlock()
  2375. if !doSleep {
  2376. i++
  2377. // Release the lock to give a chance to a concurrent nc.Close() to break the loop.
  2378. runtime.Gosched()
  2379. } else {
  2380. i = 0
  2381. var st time.Duration
  2382. if crd != nil {
  2383. wlf++
  2384. st = crd(wlf)
  2385. } else {
  2386. st = rw
  2387. if jitter > 0 {
  2388. st += time.Duration(rand.Int63n(int64(jitter)))
  2389. }
  2390. }
  2391. if rt == nil {
  2392. rt = time.NewTimer(st)
  2393. } else {
  2394. rt.Reset(st)
  2395. }
  2396. select {
  2397. case <-rqch:
  2398. rt.Stop()
  2399. case <-rt.C:
  2400. }
  2401. }
  2402. // If the readLoop, etc.. go routines were started, wait for them to complete.
  2403. if waitForGoRoutines {
  2404. nc.waitForExits()
  2405. waitForGoRoutines = false
  2406. }
  2407. nc.mu.Lock()
  2408. // Check if we have been closed first.
  2409. if nc.isClosed() {
  2410. break
  2411. }
  2412. // Mark that we tried a reconnect
  2413. cur.reconnects++
  2414. // Try to create a new connection
  2415. err = nc.createConn()
  2416. // Not yet connected, retry...
  2417. // Continue to hold the lock
  2418. if err != nil {
  2419. nc.err = nil
  2420. continue
  2421. }
  2422. // We are reconnected
  2423. nc.Reconnects++
  2424. // Process connect logic
  2425. if nc.err = nc.processConnectInit(); nc.err != nil {
  2426. // Check if we should abort reconnect. If so, break out
  2427. // of the loop and connection will be closed.
  2428. if nc.ar {
  2429. break
  2430. }
  2431. nc.changeConnStatus(RECONNECTING)
  2432. continue
  2433. }
  2434. // Clear possible lastErr under the connection lock after
  2435. // a successful processConnectInit().
  2436. nc.current.lastErr = nil
  2437. // Clear out server stats for the server we connected to..
  2438. cur.didConnect = true
  2439. cur.reconnects = 0
  2440. // Send existing subscription state
  2441. nc.resendSubscriptions()
  2442. // Now send off and clear pending buffer
  2443. nc.err = nc.flushReconnectPendingItems()
  2444. if nc.err != nil {
  2445. nc.changeConnStatus(RECONNECTING)
  2446. // Stop the ping timer (if set)
  2447. nc.stopPingTimer()
  2448. // Since processConnectInit() returned without error, the
  2449. // go routines were started, so wait for them to return
  2450. // on the next iteration (after releasing the lock).
  2451. waitForGoRoutines = true
  2452. continue
  2453. }
  2454. // Done with the pending buffer
  2455. nc.bw.doneWithPending()
  2456. // This is where we are truly connected.
  2457. nc.status = CONNECTED
  2458. // If we are here with a retry on failed connect, indicate that the
  2459. // initial connect is now complete.
  2460. nc.initc = false
  2461. // Queue up the reconnect callback.
  2462. if nc.Opts.ReconnectedCB != nil {
  2463. nc.ach.push(func() { nc.Opts.ReconnectedCB(nc) })
  2464. }
  2465. // Release lock here, we will return below.
  2466. nc.mu.Unlock()
  2467. // Make sure to flush everything
  2468. nc.Flush()
  2469. return
  2470. }
  2471. // Call into close.. We have no servers left..
  2472. if nc.err == nil {
  2473. nc.err = ErrNoServers
  2474. }
  2475. nc.mu.Unlock()
  2476. nc.close(CLOSED, true, nil)
  2477. }
  2478. // processOpErr handles errors from reading or parsing the protocol.
  2479. // The lock should not be held entering this function.
  2480. func (nc *Conn) processOpErr(err error) {
  2481. nc.mu.Lock()
  2482. if nc.isConnecting() || nc.isClosed() || nc.isReconnecting() {
  2483. nc.mu.Unlock()
  2484. return
  2485. }
  2486. if nc.Opts.AllowReconnect && nc.status == CONNECTED {
  2487. // Set our new status
  2488. nc.changeConnStatus(RECONNECTING)
  2489. // Stop ping timer if set
  2490. nc.stopPingTimer()
  2491. if nc.conn != nil {
  2492. nc.conn.Close()
  2493. nc.conn = nil
  2494. }
  2495. // Create pending buffer before reconnecting.
  2496. nc.bw.switchToPending()
  2497. // Clear any queued pongs, e.g. pending flush calls.
  2498. nc.clearPendingFlushCalls()
  2499. go nc.doReconnect(err)
  2500. nc.mu.Unlock()
  2501. return
  2502. }
  2503. nc.changeConnStatus(DISCONNECTED)
  2504. nc.err = err
  2505. nc.mu.Unlock()
  2506. nc.close(CLOSED, true, nil)
  2507. }
  2508. // dispatch is responsible for calling any async callbacks
  2509. func (ac *asyncCallbacksHandler) asyncCBDispatcher() {
  2510. for {
  2511. ac.mu.Lock()
  2512. // Protect for spurious wakeups. We should get out of the
  2513. // wait only if there is an element to pop from the list.
  2514. for ac.head == nil {
  2515. ac.cond.Wait()
  2516. }
  2517. cur := ac.head
  2518. ac.head = cur.next
  2519. if cur == ac.tail {
  2520. ac.tail = nil
  2521. }
  2522. ac.mu.Unlock()
  2523. // This signals that the dispatcher has been closed and all
  2524. // previous callbacks have been dispatched.
  2525. if cur.f == nil {
  2526. return
  2527. }
  2528. // Invoke callback outside of handler's lock
  2529. cur.f()
  2530. }
  2531. }
  2532. // Add the given function to the tail of the list and
  2533. // signals the dispatcher.
  2534. func (ac *asyncCallbacksHandler) push(f func()) {
  2535. ac.pushOrClose(f, false)
  2536. }
  2537. // Signals that we are closing...
  2538. func (ac *asyncCallbacksHandler) close() {
  2539. ac.pushOrClose(nil, true)
  2540. }
  2541. // Add the given function to the tail of the list and
  2542. // signals the dispatcher.
  2543. func (ac *asyncCallbacksHandler) pushOrClose(f func(), close bool) {
  2544. ac.mu.Lock()
  2545. defer ac.mu.Unlock()
  2546. // Make sure that library is not calling push with nil function,
  2547. // since this is used to notify the dispatcher that it should stop.
  2548. if !close && f == nil {
  2549. panic("pushing a nil callback")
  2550. }
  2551. cb := &asyncCB{f: f}
  2552. if ac.tail != nil {
  2553. ac.tail.next = cb
  2554. } else {
  2555. ac.head = cb
  2556. }
  2557. ac.tail = cb
  2558. if close {
  2559. ac.cond.Broadcast()
  2560. } else {
  2561. ac.cond.Signal()
  2562. }
  2563. }
  2564. // readLoop() will sit on the socket reading and processing the
  2565. // protocol from the server. It will dispatch appropriately based
  2566. // on the op type.
  2567. func (nc *Conn) readLoop() {
  2568. // Release the wait group on exit
  2569. defer nc.wg.Done()
  2570. // Create a parseState if needed.
  2571. nc.mu.Lock()
  2572. if nc.ps == nil {
  2573. nc.ps = &parseState{}
  2574. }
  2575. conn := nc.conn
  2576. br := nc.br
  2577. nc.mu.Unlock()
  2578. if conn == nil {
  2579. return
  2580. }
  2581. for {
  2582. buf, err := br.Read()
  2583. if err == nil {
  2584. // With websocket, it is possible that there is no error but
  2585. // also no buffer returned (either WS control message or read of a
  2586. // partial compressed message). We could call parse(buf) which
  2587. // would ignore an empty buffer, but simply go back to top of the loop.
  2588. if len(buf) == 0 {
  2589. continue
  2590. }
  2591. err = nc.parse(buf)
  2592. }
  2593. if err != nil {
  2594. nc.processOpErr(err)
  2595. break
  2596. }
  2597. }
  2598. // Clear the parseState here..
  2599. nc.mu.Lock()
  2600. nc.ps = nil
  2601. nc.mu.Unlock()
  2602. }
  2603. // waitForMsgs waits on the conditional shared with readLoop and processMsg.
  2604. // It is used to deliver messages to asynchronous subscribers.
  2605. func (nc *Conn) waitForMsgs(s *Subscription) {
  2606. var closed bool
  2607. var delivered, max uint64
  2608. // Used to account for adjustments to sub.pBytes when we wrap back around.
  2609. msgLen := -1
  2610. for {
  2611. s.mu.Lock()
  2612. // Do accounting for last msg delivered here so we only lock once
  2613. // and drain state trips after callback has returned.
  2614. if msgLen >= 0 {
  2615. s.pMsgs--
  2616. s.pBytes -= msgLen
  2617. msgLen = -1
  2618. }
  2619. if s.pHead == nil && !s.closed {
  2620. s.pCond.Wait()
  2621. }
  2622. // Pop the msg off the list
  2623. m := s.pHead
  2624. if m != nil {
  2625. s.pHead = m.next
  2626. if s.pHead == nil {
  2627. s.pTail = nil
  2628. }
  2629. if m.barrier != nil {
  2630. s.mu.Unlock()
  2631. if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
  2632. m.barrier.f()
  2633. }
  2634. continue
  2635. }
  2636. msgLen = len(m.Data)
  2637. }
  2638. mcb := s.mcb
  2639. max = s.max
  2640. closed = s.closed
  2641. var fcReply string
  2642. if !s.closed {
  2643. s.delivered++
  2644. delivered = s.delivered
  2645. if s.jsi != nil {
  2646. fcReply = s.checkForFlowControlResponse()
  2647. }
  2648. }
  2649. s.mu.Unlock()
  2650. // Respond to flow control if applicable
  2651. if fcReply != _EMPTY_ {
  2652. nc.Publish(fcReply, nil)
  2653. }
  2654. if closed {
  2655. break
  2656. }
  2657. // Deliver the message.
  2658. if m != nil && (max == 0 || delivered <= max) {
  2659. mcb(m)
  2660. }
  2661. // If we have hit the max for delivered msgs, remove sub.
  2662. if max > 0 && delivered >= max {
  2663. nc.mu.Lock()
  2664. nc.removeSub(s)
  2665. nc.mu.Unlock()
  2666. break
  2667. }
  2668. }
  2669. // Check for barrier messages
  2670. s.mu.Lock()
  2671. for m := s.pHead; m != nil; m = s.pHead {
  2672. if m.barrier != nil {
  2673. s.mu.Unlock()
  2674. if atomic.AddInt64(&m.barrier.refs, -1) == 0 {
  2675. m.barrier.f()
  2676. }
  2677. s.mu.Lock()
  2678. }
  2679. s.pHead = m.next
  2680. }
  2681. // Now check for pDone
  2682. done := s.pDone
  2683. s.mu.Unlock()
  2684. if done != nil {
  2685. done(s.Subject)
  2686. }
  2687. }
  2688. // Used for debugging and simulating loss for certain tests.
  2689. // Return what is to be used. If we return nil the message will be dropped.
  2690. type msgFilter func(m *Msg) *Msg
  2691. // processMsg is called by parse and will place the msg on the
  2692. // appropriate channel/pending queue for processing. If the channel is full,
  2693. // or the pending queue is over the pending limits, the connection is
  2694. // considered a slow consumer.
  2695. func (nc *Conn) processMsg(data []byte) {
  2696. // Stats
  2697. atomic.AddUint64(&nc.InMsgs, 1)
  2698. atomic.AddUint64(&nc.InBytes, uint64(len(data)))
  2699. // Don't lock the connection to avoid server cutting us off if the
  2700. // flusher is holding the connection lock, trying to send to the server
  2701. // that is itself trying to send data to us.
  2702. nc.subsMu.RLock()
  2703. sub := nc.subs[nc.ps.ma.sid]
  2704. var mf msgFilter
  2705. if nc.filters != nil {
  2706. mf = nc.filters[string(nc.ps.ma.subject)]
  2707. }
  2708. nc.subsMu.RUnlock()
  2709. if sub == nil {
  2710. return
  2711. }
  2712. // Copy them into string
  2713. subj := string(nc.ps.ma.subject)
  2714. reply := string(nc.ps.ma.reply)
  2715. // Doing message create outside of the sub's lock to reduce contention.
  2716. // It's possible that we end-up not using the message, but that's ok.
  2717. // FIXME(dlc): Need to copy, should/can do COW?
  2718. var msgPayload = data
  2719. if !nc.ps.msgCopied {
  2720. msgPayload = make([]byte, len(data))
  2721. copy(msgPayload, data)
  2722. }
  2723. // Check if we have headers encoded here.
  2724. var h Header
  2725. var err error
  2726. var ctrlMsg bool
  2727. var ctrlType int
  2728. var fcReply string
  2729. if nc.ps.ma.hdr > 0 {
  2730. hbuf := msgPayload[:nc.ps.ma.hdr]
  2731. msgPayload = msgPayload[nc.ps.ma.hdr:]
  2732. h, err = DecodeHeadersMsg(hbuf)
  2733. if err != nil {
  2734. // We will pass the message through but send async error.
  2735. nc.mu.Lock()
  2736. nc.err = ErrBadHeaderMsg
  2737. if nc.Opts.AsyncErrorCB != nil {
  2738. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrBadHeaderMsg) })
  2739. }
  2740. nc.mu.Unlock()
  2741. }
  2742. }
  2743. // FIXME(dlc): Should we recycle these containers?
  2744. m := &Msg{
  2745. Subject: subj,
  2746. Reply: reply,
  2747. Header: h,
  2748. Data: msgPayload,
  2749. Sub: sub,
  2750. wsz: len(data) + len(subj) + len(reply),
  2751. }
  2752. // Check for message filters.
  2753. if mf != nil {
  2754. if m = mf(m); m == nil {
  2755. // Drop message.
  2756. return
  2757. }
  2758. }
  2759. sub.mu.Lock()
  2760. // Check if closed.
  2761. if sub.closed {
  2762. sub.mu.Unlock()
  2763. return
  2764. }
  2765. // Skip flow control messages in case of using a JetStream context.
  2766. jsi := sub.jsi
  2767. if jsi != nil {
  2768. // There has to be a header for it to be a control message.
  2769. if h != nil {
  2770. ctrlMsg, ctrlType = isJSControlMessage(m)
  2771. if ctrlMsg && ctrlType == jsCtrlHB {
  2772. // Check if the heartbeat has a "Consumer Stalled" header, if
  2773. // so, the value is the FC reply to send a nil message to.
  2774. // We will send it at the end of this function.
  2775. fcReply = m.Header.Get(consumerStalledHdr)
  2776. }
  2777. }
  2778. // Check for ordered consumer here. If checkOrderedMsgs returns true that means it detected a gap.
  2779. if !ctrlMsg && jsi.ordered && sub.checkOrderedMsgs(m) {
  2780. sub.mu.Unlock()
  2781. return
  2782. }
  2783. }
  2784. // Skip processing if this is a control message and
  2785. // if not a pull consumer heartbeat. For pull consumers,
  2786. // heartbeats have to be handled on per request basis.
  2787. if !ctrlMsg || (jsi != nil && jsi.pull) {
  2788. var chanSubCheckFC bool
  2789. // Subscription internal stats (applicable only for non ChanSubscription's)
  2790. if sub.typ != ChanSubscription {
  2791. sub.pMsgs++
  2792. if sub.pMsgs > sub.pMsgsMax {
  2793. sub.pMsgsMax = sub.pMsgs
  2794. }
  2795. sub.pBytes += len(m.Data)
  2796. if sub.pBytes > sub.pBytesMax {
  2797. sub.pBytesMax = sub.pBytes
  2798. }
  2799. // Check for a Slow Consumer
  2800. if (sub.pMsgsLimit > 0 && sub.pMsgs > sub.pMsgsLimit) ||
  2801. (sub.pBytesLimit > 0 && sub.pBytes > sub.pBytesLimit) {
  2802. goto slowConsumer
  2803. }
  2804. } else if jsi != nil {
  2805. chanSubCheckFC = true
  2806. }
  2807. // We have two modes of delivery. One is the channel, used by channel
  2808. // subscribers and syncSubscribers, the other is a linked list for async.
  2809. if sub.mch != nil {
  2810. select {
  2811. case sub.mch <- m:
  2812. default:
  2813. goto slowConsumer
  2814. }
  2815. } else {
  2816. // Push onto the async pList
  2817. if sub.pHead == nil {
  2818. sub.pHead = m
  2819. sub.pTail = m
  2820. if sub.pCond != nil {
  2821. sub.pCond.Signal()
  2822. }
  2823. } else {
  2824. sub.pTail.next = m
  2825. sub.pTail = m
  2826. }
  2827. }
  2828. if jsi != nil {
  2829. // Store the ACK metadata from the message to
  2830. // compare later on with the received heartbeat.
  2831. sub.trackSequences(m.Reply)
  2832. if chanSubCheckFC {
  2833. // For ChanSubscription, since we can't call this when a message
  2834. // is "delivered" (since user is pull from their own channel),
  2835. // we have a go routine that does this check, however, we do it
  2836. // also here to make it much more responsive. The go routine is
  2837. // really to avoid stalling when there is no new messages coming.
  2838. fcReply = sub.checkForFlowControlResponse()
  2839. }
  2840. }
  2841. } else if ctrlType == jsCtrlFC && m.Reply != _EMPTY_ {
  2842. // This is a flow control message.
  2843. // We will schedule the send of the FC reply once we have delivered the
  2844. // DATA message that was received before this flow control message, which
  2845. // has sequence `jsi.fciseq`. However, it is possible that this message
  2846. // has already been delivered, in that case, we need to send the FC reply now.
  2847. if sub.getJSDelivered() >= jsi.fciseq {
  2848. fcReply = m.Reply
  2849. } else {
  2850. // Schedule a reply after the previous message is delivered.
  2851. sub.scheduleFlowControlResponse(m.Reply)
  2852. }
  2853. }
  2854. // Clear any SlowConsumer status.
  2855. sub.sc = false
  2856. sub.mu.Unlock()
  2857. if fcReply != _EMPTY_ {
  2858. nc.Publish(fcReply, nil)
  2859. }
  2860. // Handle control heartbeat messages.
  2861. if ctrlMsg && ctrlType == jsCtrlHB && m.Reply == _EMPTY_ {
  2862. nc.checkForSequenceMismatch(m, sub, jsi)
  2863. }
  2864. return
  2865. slowConsumer:
  2866. sub.dropped++
  2867. sc := !sub.sc
  2868. sub.sc = true
  2869. // Undo stats from above
  2870. if sub.typ != ChanSubscription {
  2871. sub.pMsgs--
  2872. sub.pBytes -= len(m.Data)
  2873. }
  2874. sub.mu.Unlock()
  2875. if sc {
  2876. // Now we need connection's lock and we may end-up in the situation
  2877. // that we were trying to avoid, except that in this case, the client
  2878. // is already experiencing client-side slow consumer situation.
  2879. nc.mu.Lock()
  2880. nc.err = ErrSlowConsumer
  2881. if nc.Opts.AsyncErrorCB != nil {
  2882. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, sub, ErrSlowConsumer) })
  2883. }
  2884. nc.mu.Unlock()
  2885. }
  2886. }
  2887. // processPermissionsViolation is called when the server signals a subject
  2888. // permissions violation on either publish or subscribe.
  2889. func (nc *Conn) processPermissionsViolation(err string) {
  2890. nc.mu.Lock()
  2891. // create error here so we can pass it as a closure to the async cb dispatcher.
  2892. e := errors.New("nats: " + err)
  2893. nc.err = e
  2894. if nc.Opts.AsyncErrorCB != nil {
  2895. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, e) })
  2896. }
  2897. nc.mu.Unlock()
  2898. }
  2899. // processAuthError generally processing for auth errors. We want to do retries
  2900. // unless we get the same error again. This allows us for instance to swap credentials
  2901. // and have the app reconnect, but if nothing is changing we should bail.
  2902. // This function will return true if the connection should be closed, false otherwise.
  2903. // Connection lock is held on entry
  2904. func (nc *Conn) processAuthError(err error) bool {
  2905. nc.err = err
  2906. if !nc.initc && nc.Opts.AsyncErrorCB != nil {
  2907. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
  2908. }
  2909. // We should give up if we tried twice on this server and got the
  2910. // same error. This behavior can be modified using IgnoreAuthErrorAbort.
  2911. if nc.current.lastErr == err && !nc.Opts.IgnoreAuthErrorAbort {
  2912. nc.ar = true
  2913. } else {
  2914. nc.current.lastErr = err
  2915. }
  2916. return nc.ar
  2917. }
  2918. // flusher is a separate Go routine that will process flush requests for the write
  2919. // bufio. This allows coalescing of writes to the underlying socket.
  2920. func (nc *Conn) flusher() {
  2921. // Release the wait group
  2922. defer nc.wg.Done()
  2923. // snapshot the bw and conn since they can change from underneath of us.
  2924. nc.mu.Lock()
  2925. bw := nc.bw
  2926. conn := nc.conn
  2927. fch := nc.fch
  2928. nc.mu.Unlock()
  2929. if conn == nil || bw == nil {
  2930. return
  2931. }
  2932. for {
  2933. if _, ok := <-fch; !ok {
  2934. return
  2935. }
  2936. nc.mu.Lock()
  2937. // Check to see if we should bail out.
  2938. if !nc.isConnected() || nc.isConnecting() || conn != nc.conn {
  2939. nc.mu.Unlock()
  2940. return
  2941. }
  2942. if bw.buffered() > 0 {
  2943. if err := bw.flush(); err != nil {
  2944. if nc.err == nil {
  2945. nc.err = err
  2946. }
  2947. if nc.Opts.AsyncErrorCB != nil {
  2948. nc.ach.push(func() { nc.Opts.AsyncErrorCB(nc, nil, err) })
  2949. }
  2950. }
  2951. }
  2952. nc.mu.Unlock()
  2953. }
  2954. }
  2955. // processPing will send an immediate pong protocol response to the
  2956. // server. The server uses this mechanism to detect dead clients.
  2957. func (nc *Conn) processPing() {
  2958. nc.sendProto(pongProto)
  2959. }
  2960. // processPong is used to process responses to the client's ping
  2961. // messages. We use pings for the flush mechanism as well.
  2962. func (nc *Conn) processPong() {
  2963. var ch chan struct{}
  2964. nc.mu.Lock()
  2965. if len(nc.pongs) > 0 {
  2966. ch = nc.pongs[0]
  2967. nc.pongs = append(nc.pongs[:0], nc.pongs[1:]...)
  2968. }
  2969. nc.pout = 0
  2970. nc.mu.Unlock()
  2971. if ch != nil {
  2972. ch <- struct{}{}
  2973. }
  2974. }
  2975. // processOK is a placeholder for processing OK messages.
  2976. func (nc *Conn) processOK() {
  2977. // do nothing
  2978. }
  2979. // processInfo is used to parse the info messages sent
  2980. // from the server.
  2981. // This function may update the server pool.
  2982. func (nc *Conn) processInfo(info string) error {
  2983. if info == _EMPTY_ {
  2984. return nil
  2985. }
  2986. var ncInfo serverInfo
  2987. if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
  2988. return err
  2989. }
  2990. // Copy content into connection's info structure.
  2991. nc.info = ncInfo
  2992. // The array could be empty/not present on initial connect,
  2993. // if advertise is disabled on that server, or servers that
  2994. // did not include themselves in the async INFO protocol.
  2995. // If empty, do not remove the implicit servers from the pool.
  2996. if len(nc.info.ConnectURLs) == 0 {
  2997. if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil {
  2998. nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) })
  2999. }
  3000. return nil
  3001. }
  3002. // Note about pool randomization: when the pool was first created,
  3003. // it was randomized (if allowed). We keep the order the same (removing
  3004. // implicit servers that are no longer sent to us). New URLs are sent
  3005. // to us in no specific order so don't need extra randomization.
  3006. hasNew := false
  3007. // This is what we got from the server we are connected to.
  3008. urls := nc.info.ConnectURLs
  3009. // Transform that to a map for easy lookups
  3010. tmp := make(map[string]struct{}, len(urls))
  3011. for _, curl := range urls {
  3012. tmp[curl] = struct{}{}
  3013. }
  3014. // Walk the pool and removed the implicit servers that are no longer in the
  3015. // given array/map
  3016. sp := nc.srvPool
  3017. for i := 0; i < len(sp); i++ {
  3018. srv := sp[i]
  3019. curl := srv.url.Host
  3020. // Check if this URL is in the INFO protocol
  3021. _, inInfo := tmp[curl]
  3022. // Remove from the temp map so that at the end we are left with only
  3023. // new (or restarted) servers that need to be added to the pool.
  3024. delete(tmp, curl)
  3025. // Keep servers that were set through Options, but also the one that
  3026. // we are currently connected to (even if it is a discovered server).
  3027. if !srv.isImplicit || srv.url == nc.current.url {
  3028. continue
  3029. }
  3030. if !inInfo {
  3031. // Remove from server pool. Keep current order.
  3032. copy(sp[i:], sp[i+1:])
  3033. nc.srvPool = sp[:len(sp)-1]
  3034. sp = nc.srvPool
  3035. i--
  3036. }
  3037. }
  3038. // Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
  3039. saveTLS := nc.current != nil && !hostIsIP(nc.current.url)
  3040. // If there are any left in the tmp map, these are new (or restarted) servers
  3041. // and need to be added to the pool.
  3042. for curl := range tmp {
  3043. // Before adding, check if this is a new (as in never seen) URL.
  3044. // This is used to figure out if we invoke the DiscoveredServersCB
  3045. if _, present := nc.urls[curl]; !present {
  3046. hasNew = true
  3047. }
  3048. nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
  3049. }
  3050. if hasNew {
  3051. // Randomize the pool if allowed but leave the first URL in place.
  3052. if !nc.Opts.NoRandomize {
  3053. nc.shufflePool(1)
  3054. }
  3055. if !nc.initc && nc.Opts.DiscoveredServersCB != nil {
  3056. nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) })
  3057. }
  3058. }
  3059. if !nc.initc && ncInfo.LameDuckMode && nc.Opts.LameDuckModeHandler != nil {
  3060. nc.ach.push(func() { nc.Opts.LameDuckModeHandler(nc) })
  3061. }
  3062. return nil
  3063. }
  3064. // processAsyncInfo does the same than processInfo, but is called
  3065. // from the parser. Calls processInfo under connection's lock
  3066. // protection.
  3067. func (nc *Conn) processAsyncInfo(info []byte) {
  3068. nc.mu.Lock()
  3069. // Ignore errors, we will simply not update the server pool...
  3070. nc.processInfo(string(info))
  3071. nc.mu.Unlock()
  3072. }
  3073. // LastError reports the last error encountered via the connection.
  3074. // It can be used reliably within ClosedCB in order to find out reason
  3075. // why connection was closed for example.
  3076. func (nc *Conn) LastError() error {
  3077. if nc == nil {
  3078. return ErrInvalidConnection
  3079. }
  3080. nc.mu.RLock()
  3081. err := nc.err
  3082. nc.mu.RUnlock()
  3083. return err
  3084. }
  3085. // Check if the given error string is an auth error, and if so returns
  3086. // the corresponding ErrXXX error, nil otherwise
  3087. func checkAuthError(e string) error {
  3088. if strings.HasPrefix(e, AUTHORIZATION_ERR) {
  3089. return ErrAuthorization
  3090. }
  3091. if strings.HasPrefix(e, AUTHENTICATION_EXPIRED_ERR) {
  3092. return ErrAuthExpired
  3093. }
  3094. if strings.HasPrefix(e, AUTHENTICATION_REVOKED_ERR) {
  3095. return ErrAuthRevoked
  3096. }
  3097. if strings.HasPrefix(e, ACCOUNT_AUTHENTICATION_EXPIRED_ERR) {
  3098. return ErrAccountAuthExpired
  3099. }
  3100. return nil
  3101. }
  3102. // processErr processes any error messages from the server and
  3103. // sets the connection's LastError.
  3104. func (nc *Conn) processErr(ie string) {
  3105. // Trim, remove quotes
  3106. ne := normalizeErr(ie)
  3107. // convert to lower case.
  3108. e := strings.ToLower(ne)
  3109. close := false
  3110. // FIXME(dlc) - process Slow Consumer signals special.
  3111. if e == STALE_CONNECTION {
  3112. nc.processOpErr(ErrStaleConnection)
  3113. } else if e == MAX_CONNECTIONS_ERR {
  3114. nc.processOpErr(ErrMaxConnectionsExceeded)
  3115. } else if strings.HasPrefix(e, PERMISSIONS_ERR) {
  3116. nc.processPermissionsViolation(ne)
  3117. } else if authErr := checkAuthError(e); authErr != nil {
  3118. nc.mu.Lock()
  3119. close = nc.processAuthError(authErr)
  3120. nc.mu.Unlock()
  3121. } else {
  3122. close = true
  3123. nc.mu.Lock()
  3124. nc.err = errors.New("nats: " + ne)
  3125. nc.mu.Unlock()
  3126. }
  3127. if close {
  3128. nc.close(CLOSED, true, nil)
  3129. }
  3130. }
  3131. // kickFlusher will send a bool on a channel to kick the
  3132. // flush Go routine to flush data to the server.
  3133. func (nc *Conn) kickFlusher() {
  3134. if nc.bw != nil {
  3135. select {
  3136. case nc.fch <- struct{}{}:
  3137. default:
  3138. }
  3139. }
  3140. }
  3141. // Publish publishes the data argument to the given subject. The data
  3142. // argument is left untouched and needs to be correctly interpreted on
  3143. // the receiver.
  3144. func (nc *Conn) Publish(subj string, data []byte) error {
  3145. return nc.publish(subj, _EMPTY_, nil, data)
  3146. }
  3147. // Header represents the optional Header for a NATS message,
  3148. // based on the implementation of http.Header.
  3149. type Header map[string][]string
  3150. // Add adds the key, value pair to the header. It is case-sensitive
  3151. // and appends to any existing values associated with key.
  3152. func (h Header) Add(key, value string) {
  3153. h[key] = append(h[key], value)
  3154. }
  3155. // Set sets the header entries associated with key to the single
  3156. // element value. It is case-sensitive and replaces any existing
  3157. // values associated with key.
  3158. func (h Header) Set(key, value string) {
  3159. h[key] = []string{value}
  3160. }
  3161. // Get gets the first value associated with the given key.
  3162. // It is case-sensitive.
  3163. func (h Header) Get(key string) string {
  3164. if h == nil {
  3165. return _EMPTY_
  3166. }
  3167. if v := h[key]; v != nil {
  3168. return v[0]
  3169. }
  3170. return _EMPTY_
  3171. }
  3172. // Values returns all values associated with the given key.
  3173. // It is case-sensitive.
  3174. func (h Header) Values(key string) []string {
  3175. return h[key]
  3176. }
  3177. // Del deletes the values associated with a key.
  3178. // It is case-sensitive.
  3179. func (h Header) Del(key string) {
  3180. delete(h, key)
  3181. }
  3182. // NewMsg creates a message for publishing that will use headers.
  3183. func NewMsg(subject string) *Msg {
  3184. return &Msg{
  3185. Subject: subject,
  3186. Header: make(Header),
  3187. }
  3188. }
  3189. const (
  3190. hdrLine = "NATS/1.0\r\n"
  3191. crlf = "\r\n"
  3192. hdrPreEnd = len(hdrLine) - len(crlf)
  3193. statusHdr = "Status"
  3194. descrHdr = "Description"
  3195. lastConsumerSeqHdr = "Nats-Last-Consumer"
  3196. lastStreamSeqHdr = "Nats-Last-Stream"
  3197. consumerStalledHdr = "Nats-Consumer-Stalled"
  3198. noResponders = "503"
  3199. noMessagesSts = "404"
  3200. reqTimeoutSts = "408"
  3201. jetStream409Sts = "409"
  3202. controlMsg = "100"
  3203. statusLen = 3 // e.g. 20x, 40x, 50x
  3204. )
  3205. // DecodeHeadersMsg will decode and headers.
  3206. func DecodeHeadersMsg(data []byte) (Header, error) {
  3207. br := bufio.NewReaderSize(bytes.NewReader(data), 128)
  3208. tp := textproto.NewReader(br)
  3209. l, err := tp.ReadLine()
  3210. if err != nil || len(l) < hdrPreEnd || l[:hdrPreEnd] != hdrLine[:hdrPreEnd] {
  3211. return nil, ErrBadHeaderMsg
  3212. }
  3213. mh, err := readMIMEHeader(tp)
  3214. if err != nil {
  3215. return nil, err
  3216. }
  3217. // Check if we have an inlined status.
  3218. if len(l) > hdrPreEnd {
  3219. var description string
  3220. status := strings.TrimSpace(l[hdrPreEnd:])
  3221. if len(status) != statusLen {
  3222. description = strings.TrimSpace(status[statusLen:])
  3223. status = status[:statusLen]
  3224. }
  3225. mh.Add(statusHdr, status)
  3226. if len(description) > 0 {
  3227. mh.Add(descrHdr, description)
  3228. }
  3229. }
  3230. return Header(mh), nil
  3231. }
  3232. // readMIMEHeader returns a MIMEHeader that preserves the
  3233. // original case of the MIME header, based on the implementation
  3234. // of textproto.ReadMIMEHeader.
  3235. //
  3236. // https://golang.org/pkg/net/textproto/#Reader.ReadMIMEHeader
  3237. func readMIMEHeader(tp *textproto.Reader) (textproto.MIMEHeader, error) {
  3238. m := make(textproto.MIMEHeader)
  3239. for {
  3240. kv, err := tp.ReadLine()
  3241. if len(kv) == 0 {
  3242. return m, err
  3243. }
  3244. // Process key fetching original case.
  3245. i := bytes.IndexByte([]byte(kv), ':')
  3246. if i < 0 {
  3247. return nil, ErrBadHeaderMsg
  3248. }
  3249. key := kv[:i]
  3250. if key == "" {
  3251. // Skip empty keys.
  3252. continue
  3253. }
  3254. i++
  3255. for i < len(kv) && (kv[i] == ' ' || kv[i] == '\t') {
  3256. i++
  3257. }
  3258. value := string(kv[i:])
  3259. m[key] = append(m[key], value)
  3260. if err != nil {
  3261. return m, err
  3262. }
  3263. }
  3264. }
  3265. // PublishMsg publishes the Msg structure, which includes the
  3266. // Subject, an optional Reply and an optional Data field.
  3267. func (nc *Conn) PublishMsg(m *Msg) error {
  3268. if m == nil {
  3269. return ErrInvalidMsg
  3270. }
  3271. hdr, err := m.headerBytes()
  3272. if err != nil {
  3273. return err
  3274. }
  3275. return nc.publish(m.Subject, m.Reply, hdr, m.Data)
  3276. }
  3277. // PublishRequest will perform a Publish() expecting a response on the
  3278. // reply subject. Use Request() for automatically waiting for a response
  3279. // inline.
  3280. func (nc *Conn) PublishRequest(subj, reply string, data []byte) error {
  3281. return nc.publish(subj, reply, nil, data)
  3282. }
  3283. // Used for handrolled Itoa
  3284. const digits = "0123456789"
  3285. // publish is the internal function to publish messages to a nats-server.
  3286. // Sends a protocol data message by queuing into the bufio writer
  3287. // and kicking the flush go routine. These writes should be protected.
  3288. func (nc *Conn) publish(subj, reply string, hdr, data []byte) error {
  3289. if nc == nil {
  3290. return ErrInvalidConnection
  3291. }
  3292. if subj == "" {
  3293. return ErrBadSubject
  3294. }
  3295. nc.mu.Lock()
  3296. // Check if headers attempted to be sent to server that does not support them.
  3297. if len(hdr) > 0 && !nc.info.Headers {
  3298. nc.mu.Unlock()
  3299. return ErrHeadersNotSupported
  3300. }
  3301. if nc.isClosed() {
  3302. nc.mu.Unlock()
  3303. return ErrConnectionClosed
  3304. }
  3305. if nc.isDrainingPubs() {
  3306. nc.mu.Unlock()
  3307. return ErrConnectionDraining
  3308. }
  3309. // Proactively reject payloads over the threshold set by server.
  3310. msgSize := int64(len(data) + len(hdr))
  3311. // Skip this check if we are not yet connected (RetryOnFailedConnect)
  3312. if !nc.initc && msgSize > nc.info.MaxPayload {
  3313. nc.mu.Unlock()
  3314. return ErrMaxPayload
  3315. }
  3316. // Check if we are reconnecting, and if so check if
  3317. // we have exceeded our reconnect outbound buffer limits.
  3318. if nc.bw.atLimitIfUsingPending() {
  3319. nc.mu.Unlock()
  3320. return ErrReconnectBufExceeded
  3321. }
  3322. var mh []byte
  3323. if hdr != nil {
  3324. mh = nc.scratch[:len(_HPUB_P_)]
  3325. } else {
  3326. mh = nc.scratch[1:len(_HPUB_P_)]
  3327. }
  3328. mh = append(mh, subj...)
  3329. mh = append(mh, ' ')
  3330. if reply != "" {
  3331. mh = append(mh, reply...)
  3332. mh = append(mh, ' ')
  3333. }
  3334. // We could be smarter here, but simple loop is ok,
  3335. // just avoid strconv in fast path.
  3336. // FIXME(dlc) - Find a better way here.
  3337. // msgh = strconv.AppendInt(msgh, int64(len(data)), 10)
  3338. // go 1.14 some values strconv faster, may be able to switch over.
  3339. var b [12]byte
  3340. var i = len(b)
  3341. if hdr != nil {
  3342. if len(hdr) > 0 {
  3343. for l := len(hdr); l > 0; l /= 10 {
  3344. i--
  3345. b[i] = digits[l%10]
  3346. }
  3347. } else {
  3348. i--
  3349. b[i] = digits[0]
  3350. }
  3351. mh = append(mh, b[i:]...)
  3352. mh = append(mh, ' ')
  3353. // reset for below.
  3354. i = len(b)
  3355. }
  3356. if msgSize > 0 {
  3357. for l := msgSize; l > 0; l /= 10 {
  3358. i--
  3359. b[i] = digits[l%10]
  3360. }
  3361. } else {
  3362. i--
  3363. b[i] = digits[0]
  3364. }
  3365. mh = append(mh, b[i:]...)
  3366. mh = append(mh, _CRLF_...)
  3367. if err := nc.bw.appendBufs(mh, hdr, data, _CRLF_BYTES_); err != nil {
  3368. nc.mu.Unlock()
  3369. return err
  3370. }
  3371. nc.OutMsgs++
  3372. nc.OutBytes += uint64(len(data) + len(hdr))
  3373. if len(nc.fch) == 0 {
  3374. nc.kickFlusher()
  3375. }
  3376. nc.mu.Unlock()
  3377. return nil
  3378. }
  3379. // respHandler is the global response handler. It will look up
  3380. // the appropriate channel based on the last token and place
  3381. // the message on the channel if possible.
  3382. func (nc *Conn) respHandler(m *Msg) {
  3383. nc.mu.Lock()
  3384. // Just return if closed.
  3385. if nc.isClosed() {
  3386. nc.mu.Unlock()
  3387. return
  3388. }
  3389. var mch chan *Msg
  3390. // Grab mch
  3391. rt := nc.respToken(m.Subject)
  3392. if rt != _EMPTY_ {
  3393. mch = nc.respMap[rt]
  3394. // Delete the key regardless, one response only.
  3395. delete(nc.respMap, rt)
  3396. } else if len(nc.respMap) == 1 {
  3397. // If the server has rewritten the subject, the response token (rt)
  3398. // will not match (could be the case with JetStream). If that is the
  3399. // case and there is a single entry, use that.
  3400. for k, v := range nc.respMap {
  3401. mch = v
  3402. delete(nc.respMap, k)
  3403. break
  3404. }
  3405. }
  3406. nc.mu.Unlock()
  3407. // Don't block, let Request timeout instead, mch is
  3408. // buffered and we should delete the key before a
  3409. // second response is processed.
  3410. select {
  3411. case mch <- m:
  3412. default:
  3413. return
  3414. }
  3415. }
  3416. // Helper to setup and send new request style requests. Return the chan to receive the response.
  3417. func (nc *Conn) createNewRequestAndSend(subj string, hdr, data []byte) (chan *Msg, string, error) {
  3418. nc.mu.Lock()
  3419. // Do setup for the new style if needed.
  3420. if nc.respMap == nil {
  3421. nc.initNewResp()
  3422. }
  3423. // Create new literal Inbox and map to a chan msg.
  3424. mch := make(chan *Msg, RequestChanLen)
  3425. respInbox := nc.newRespInbox()
  3426. token := respInbox[nc.respSubLen:]
  3427. nc.respMap[token] = mch
  3428. if nc.respMux == nil {
  3429. // Create the response subscription we will use for all new style responses.
  3430. // This will be on an _INBOX with an additional terminal token. The subscription
  3431. // will be on a wildcard.
  3432. s, err := nc.subscribeLocked(nc.respSub, _EMPTY_, nc.respHandler, nil, false, nil)
  3433. if err != nil {
  3434. nc.mu.Unlock()
  3435. return nil, token, err
  3436. }
  3437. nc.respScanf = strings.Replace(nc.respSub, "*", "%s", -1)
  3438. nc.respMux = s
  3439. }
  3440. nc.mu.Unlock()
  3441. if err := nc.publish(subj, respInbox, hdr, data); err != nil {
  3442. return nil, token, err
  3443. }
  3444. return mch, token, nil
  3445. }
  3446. // RequestMsg will send a request payload including optional headers and deliver
  3447. // the response message, or an error, including a timeout if no message was received properly.
  3448. func (nc *Conn) RequestMsg(msg *Msg, timeout time.Duration) (*Msg, error) {
  3449. if msg == nil {
  3450. return nil, ErrInvalidMsg
  3451. }
  3452. hdr, err := msg.headerBytes()
  3453. if err != nil {
  3454. return nil, err
  3455. }
  3456. return nc.request(msg.Subject, hdr, msg.Data, timeout)
  3457. }
  3458. // Request will send a request payload and deliver the response message,
  3459. // or an error, including a timeout if no message was received properly.
  3460. func (nc *Conn) Request(subj string, data []byte, timeout time.Duration) (*Msg, error) {
  3461. return nc.request(subj, nil, data, timeout)
  3462. }
  3463. func (nc *Conn) useOldRequestStyle() bool {
  3464. nc.mu.RLock()
  3465. r := nc.Opts.UseOldRequestStyle
  3466. nc.mu.RUnlock()
  3467. return r
  3468. }
  3469. func (nc *Conn) request(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
  3470. if nc == nil {
  3471. return nil, ErrInvalidConnection
  3472. }
  3473. var m *Msg
  3474. var err error
  3475. if nc.useOldRequestStyle() {
  3476. m, err = nc.oldRequest(subj, hdr, data, timeout)
  3477. } else {
  3478. m, err = nc.newRequest(subj, hdr, data, timeout)
  3479. }
  3480. // Check for no responder status.
  3481. if err == nil && len(m.Data) == 0 && m.Header.Get(statusHdr) == noResponders {
  3482. m, err = nil, ErrNoResponders
  3483. }
  3484. return m, err
  3485. }
  3486. func (nc *Conn) newRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
  3487. mch, token, err := nc.createNewRequestAndSend(subj, hdr, data)
  3488. if err != nil {
  3489. return nil, err
  3490. }
  3491. t := globalTimerPool.Get(timeout)
  3492. defer globalTimerPool.Put(t)
  3493. var ok bool
  3494. var msg *Msg
  3495. select {
  3496. case msg, ok = <-mch:
  3497. if !ok {
  3498. return nil, ErrConnectionClosed
  3499. }
  3500. case <-t.C:
  3501. nc.mu.Lock()
  3502. delete(nc.respMap, token)
  3503. nc.mu.Unlock()
  3504. return nil, ErrTimeout
  3505. }
  3506. return msg, nil
  3507. }
  3508. // oldRequest will create an Inbox and perform a Request() call
  3509. // with the Inbox reply and return the first reply received.
  3510. // This is optimized for the case of multiple responses.
  3511. func (nc *Conn) oldRequest(subj string, hdr, data []byte, timeout time.Duration) (*Msg, error) {
  3512. inbox := nc.NewInbox()
  3513. ch := make(chan *Msg, RequestChanLen)
  3514. s, err := nc.subscribe(inbox, _EMPTY_, nil, ch, true, nil)
  3515. if err != nil {
  3516. return nil, err
  3517. }
  3518. s.AutoUnsubscribe(1)
  3519. defer s.Unsubscribe()
  3520. err = nc.publish(subj, inbox, hdr, data)
  3521. if err != nil {
  3522. return nil, err
  3523. }
  3524. return s.NextMsg(timeout)
  3525. }
  3526. // InboxPrefix is the prefix for all inbox subjects.
  3527. const (
  3528. InboxPrefix = "_INBOX."
  3529. inboxPrefixLen = len(InboxPrefix)
  3530. replySuffixLen = 8 // Gives us 62^8
  3531. rdigits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  3532. base = 62
  3533. )
  3534. // NewInbox will return an inbox string which can be used for directed replies from
  3535. // subscribers. These are guaranteed to be unique, but can be shared and subscribed
  3536. // to by others.
  3537. func NewInbox() string {
  3538. var b [inboxPrefixLen + nuidSize]byte
  3539. pres := b[:inboxPrefixLen]
  3540. copy(pres, InboxPrefix)
  3541. ns := b[inboxPrefixLen:]
  3542. copy(ns, nuid.Next())
  3543. return string(b[:])
  3544. }
  3545. // Create a new inbox that is prefix aware.
  3546. func (nc *Conn) NewInbox() string {
  3547. if nc.Opts.InboxPrefix == _EMPTY_ {
  3548. return NewInbox()
  3549. }
  3550. var sb strings.Builder
  3551. sb.WriteString(nc.Opts.InboxPrefix)
  3552. sb.WriteByte('.')
  3553. sb.WriteString(nuid.Next())
  3554. return sb.String()
  3555. }
  3556. // Function to init new response structures.
  3557. func (nc *Conn) initNewResp() {
  3558. nc.respSubPrefix = fmt.Sprintf("%s.", nc.NewInbox())
  3559. nc.respSubLen = len(nc.respSubPrefix)
  3560. nc.respSub = fmt.Sprintf("%s*", nc.respSubPrefix)
  3561. nc.respMap = make(map[string]chan *Msg)
  3562. nc.respRand = rand.New(rand.NewSource(time.Now().UnixNano()))
  3563. }
  3564. // newRespInbox creates a new literal response subject
  3565. // that will trigger the mux subscription handler.
  3566. // Lock should be held.
  3567. func (nc *Conn) newRespInbox() string {
  3568. if nc.respMap == nil {
  3569. nc.initNewResp()
  3570. }
  3571. var sb strings.Builder
  3572. sb.WriteString(nc.respSubPrefix)
  3573. rn := nc.respRand.Int63()
  3574. for i := 0; i < replySuffixLen; i++ {
  3575. sb.WriteByte(rdigits[rn%base])
  3576. rn /= base
  3577. }
  3578. return sb.String()
  3579. }
  3580. // NewRespInbox is the new format used for _INBOX.
  3581. func (nc *Conn) NewRespInbox() string {
  3582. nc.mu.Lock()
  3583. s := nc.newRespInbox()
  3584. nc.mu.Unlock()
  3585. return s
  3586. }
  3587. // respToken will return the last token of a literal response inbox
  3588. // which we use for the message channel lookup. This needs to do a
  3589. // scan to protect itself against the server changing the subject.
  3590. // Lock should be held.
  3591. func (nc *Conn) respToken(respInbox string) string {
  3592. var token string
  3593. n, err := fmt.Sscanf(respInbox, nc.respScanf, &token)
  3594. if err != nil || n != 1 {
  3595. return ""
  3596. }
  3597. return token
  3598. }
  3599. // Subscribe will express interest in the given subject. The subject
  3600. // can have wildcards.
  3601. // There are two type of wildcards: * for partial, and > for full.
  3602. // A subscription on subject time.*.east would receive messages sent to time.us.east and time.eu.east.
  3603. // A subscription on subject time.us.> would receive messages sent to
  3604. // time.us.east and time.us.east.atlanta, while time.us.* would only match time.us.east
  3605. // since it can't match more than one token.
  3606. // Messages will be delivered to the associated MsgHandler.
  3607. func (nc *Conn) Subscribe(subj string, cb MsgHandler) (*Subscription, error) {
  3608. return nc.subscribe(subj, _EMPTY_, cb, nil, false, nil)
  3609. }
  3610. // ChanSubscribe will express interest in the given subject and place
  3611. // all messages received on the channel.
  3612. // You should not close the channel until sub.Unsubscribe() has been called.
  3613. func (nc *Conn) ChanSubscribe(subj string, ch chan *Msg) (*Subscription, error) {
  3614. return nc.subscribe(subj, _EMPTY_, nil, ch, false, nil)
  3615. }
  3616. // ChanQueueSubscribe will express interest in the given subject.
  3617. // All subscribers with the same queue name will form the queue group
  3618. // and only one member of the group will be selected to receive any given message,
  3619. // which will be placed on the channel.
  3620. // You should not close the channel until sub.Unsubscribe() has been called.
  3621. // Note: This is the same than QueueSubscribeSyncWithChan.
  3622. func (nc *Conn) ChanQueueSubscribe(subj, group string, ch chan *Msg) (*Subscription, error) {
  3623. return nc.subscribe(subj, group, nil, ch, false, nil)
  3624. }
  3625. // SubscribeSync will express interest on the given subject. Messages will
  3626. // be received synchronously using Subscription.NextMsg().
  3627. func (nc *Conn) SubscribeSync(subj string) (*Subscription, error) {
  3628. if nc == nil {
  3629. return nil, ErrInvalidConnection
  3630. }
  3631. mch := make(chan *Msg, nc.Opts.SubChanLen)
  3632. return nc.subscribe(subj, _EMPTY_, nil, mch, true, nil)
  3633. }
  3634. // QueueSubscribe creates an asynchronous queue subscriber on the given subject.
  3635. // All subscribers with the same queue name will form the queue group and
  3636. // only one member of the group will be selected to receive any given
  3637. // message asynchronously.
  3638. func (nc *Conn) QueueSubscribe(subj, queue string, cb MsgHandler) (*Subscription, error) {
  3639. return nc.subscribe(subj, queue, cb, nil, false, nil)
  3640. }
  3641. // QueueSubscribeSync creates a synchronous queue subscriber on the given
  3642. // subject. All subscribers with the same queue name will form the queue
  3643. // group and only one member of the group will be selected to receive any
  3644. // given message synchronously using Subscription.NextMsg().
  3645. func (nc *Conn) QueueSubscribeSync(subj, queue string) (*Subscription, error) {
  3646. mch := make(chan *Msg, nc.Opts.SubChanLen)
  3647. return nc.subscribe(subj, queue, nil, mch, true, nil)
  3648. }
  3649. // QueueSubscribeSyncWithChan will express interest in the given subject.
  3650. // All subscribers with the same queue name will form the queue group
  3651. // and only one member of the group will be selected to receive any given message,
  3652. // which will be placed on the channel.
  3653. // You should not close the channel until sub.Unsubscribe() has been called.
  3654. // Note: This is the same than ChanQueueSubscribe.
  3655. func (nc *Conn) QueueSubscribeSyncWithChan(subj, queue string, ch chan *Msg) (*Subscription, error) {
  3656. return nc.subscribe(subj, queue, nil, ch, false, nil)
  3657. }
  3658. // badSubject will do quick test on whether a subject is acceptable.
  3659. // Spaces are not allowed and all tokens should be > 0 in len.
  3660. func badSubject(subj string) bool {
  3661. if strings.ContainsAny(subj, " \t\r\n") {
  3662. return true
  3663. }
  3664. tokens := strings.Split(subj, ".")
  3665. for _, t := range tokens {
  3666. if len(t) == 0 {
  3667. return true
  3668. }
  3669. }
  3670. return false
  3671. }
  3672. // badQueue will check a queue name for whitespace.
  3673. func badQueue(qname string) bool {
  3674. return strings.ContainsAny(qname, " \t\r\n")
  3675. }
  3676. // subscribe is the internal subscribe function that indicates interest in a subject.
  3677. func (nc *Conn) subscribe(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, js *jsSub) (*Subscription, error) {
  3678. if nc == nil {
  3679. return nil, ErrInvalidConnection
  3680. }
  3681. nc.mu.Lock()
  3682. defer nc.mu.Unlock()
  3683. return nc.subscribeLocked(subj, queue, cb, ch, isSync, js)
  3684. }
  3685. func (nc *Conn) subscribeLocked(subj, queue string, cb MsgHandler, ch chan *Msg, isSync bool, js *jsSub) (*Subscription, error) {
  3686. if nc == nil {
  3687. return nil, ErrInvalidConnection
  3688. }
  3689. if badSubject(subj) {
  3690. return nil, ErrBadSubject
  3691. }
  3692. if queue != _EMPTY_ && badQueue(queue) {
  3693. return nil, ErrBadQueueName
  3694. }
  3695. // Check for some error conditions.
  3696. if nc.isClosed() {
  3697. return nil, ErrConnectionClosed
  3698. }
  3699. if nc.isDraining() {
  3700. return nil, ErrConnectionDraining
  3701. }
  3702. if cb == nil && ch == nil {
  3703. return nil, ErrBadSubscription
  3704. }
  3705. sub := &Subscription{
  3706. Subject: subj,
  3707. Queue: queue,
  3708. mcb: cb,
  3709. conn: nc,
  3710. jsi: js,
  3711. }
  3712. // Set pending limits.
  3713. if ch != nil {
  3714. sub.pMsgsLimit = cap(ch)
  3715. } else {
  3716. sub.pMsgsLimit = DefaultSubPendingMsgsLimit
  3717. }
  3718. sub.pBytesLimit = DefaultSubPendingBytesLimit
  3719. // If we have an async callback, start up a sub specific
  3720. // Go routine to deliver the messages.
  3721. var sr bool
  3722. if cb != nil {
  3723. sub.typ = AsyncSubscription
  3724. sub.pCond = sync.NewCond(&sub.mu)
  3725. sr = true
  3726. } else if !isSync {
  3727. sub.typ = ChanSubscription
  3728. sub.mch = ch
  3729. } else { // Sync Subscription
  3730. sub.typ = SyncSubscription
  3731. sub.mch = ch
  3732. }
  3733. nc.subsMu.Lock()
  3734. nc.ssid++
  3735. sub.sid = nc.ssid
  3736. nc.subs[sub.sid] = sub
  3737. nc.subsMu.Unlock()
  3738. // Let's start the go routine now that it is fully setup and registered.
  3739. if sr {
  3740. go nc.waitForMsgs(sub)
  3741. }
  3742. // We will send these for all subs when we reconnect
  3743. // so that we can suppress here if reconnecting.
  3744. if !nc.isReconnecting() {
  3745. nc.bw.appendString(fmt.Sprintf(subProto, subj, queue, sub.sid))
  3746. nc.kickFlusher()
  3747. }
  3748. return sub, nil
  3749. }
  3750. // NumSubscriptions returns active number of subscriptions.
  3751. func (nc *Conn) NumSubscriptions() int {
  3752. nc.mu.RLock()
  3753. defer nc.mu.RUnlock()
  3754. return len(nc.subs)
  3755. }
  3756. // Lock for nc should be held here upon entry
  3757. func (nc *Conn) removeSub(s *Subscription) {
  3758. nc.subsMu.Lock()
  3759. delete(nc.subs, s.sid)
  3760. nc.subsMu.Unlock()
  3761. s.mu.Lock()
  3762. defer s.mu.Unlock()
  3763. // Release callers on NextMsg for SyncSubscription only
  3764. if s.mch != nil && s.typ == SyncSubscription {
  3765. close(s.mch)
  3766. }
  3767. s.mch = nil
  3768. // If JS subscription then stop HB timer.
  3769. if jsi := s.jsi; jsi != nil {
  3770. if jsi.hbc != nil {
  3771. jsi.hbc.Stop()
  3772. jsi.hbc = nil
  3773. }
  3774. if jsi.csfct != nil {
  3775. jsi.csfct.Stop()
  3776. jsi.csfct = nil
  3777. }
  3778. }
  3779. // Mark as invalid
  3780. s.closed = true
  3781. if s.pCond != nil {
  3782. s.pCond.Broadcast()
  3783. }
  3784. }
  3785. // SubscriptionType is the type of the Subscription.
  3786. type SubscriptionType int
  3787. // The different types of subscription types.
  3788. const (
  3789. AsyncSubscription = SubscriptionType(iota)
  3790. SyncSubscription
  3791. ChanSubscription
  3792. NilSubscription
  3793. PullSubscription
  3794. )
  3795. // Type returns the type of Subscription.
  3796. func (s *Subscription) Type() SubscriptionType {
  3797. if s == nil {
  3798. return NilSubscription
  3799. }
  3800. s.mu.Lock()
  3801. defer s.mu.Unlock()
  3802. // Pull subscriptions are really a SyncSubscription and we want this
  3803. // type to be set internally for all delivered messages management, etc..
  3804. // So check when to return PullSubscription to the user.
  3805. if s.jsi != nil && s.jsi.pull {
  3806. return PullSubscription
  3807. }
  3808. return s.typ
  3809. }
  3810. // IsValid returns a boolean indicating whether the subscription
  3811. // is still active. This will return false if the subscription has
  3812. // already been closed.
  3813. func (s *Subscription) IsValid() bool {
  3814. if s == nil {
  3815. return false
  3816. }
  3817. s.mu.Lock()
  3818. defer s.mu.Unlock()
  3819. return s.conn != nil && !s.closed
  3820. }
  3821. // Drain will remove interest but continue callbacks until all messages
  3822. // have been processed.
  3823. //
  3824. // For a JetStream subscription, if the library has created the JetStream
  3825. // consumer, the library will send a DeleteConsumer request to the server
  3826. // when the Drain operation completes. If a failure occurs when deleting
  3827. // the JetStream consumer, an error will be reported to the asynchronous
  3828. // error callback.
  3829. // If you do not wish the JetStream consumer to be automatically deleted,
  3830. // ensure that the consumer is not created by the library, which means
  3831. // create the consumer with AddConsumer and bind to this consumer.
  3832. func (s *Subscription) Drain() error {
  3833. if s == nil {
  3834. return ErrBadSubscription
  3835. }
  3836. s.mu.Lock()
  3837. conn := s.conn
  3838. s.mu.Unlock()
  3839. if conn == nil {
  3840. return ErrBadSubscription
  3841. }
  3842. return conn.unsubscribe(s, 0, true)
  3843. }
  3844. // Unsubscribe will remove interest in the given subject.
  3845. //
  3846. // For a JetStream subscription, if the library has created the JetStream
  3847. // consumer, it will send a DeleteConsumer request to the server (if the
  3848. // unsubscribe itself was successful). If the delete operation fails, the
  3849. // error will be returned.
  3850. // If you do not wish the JetStream consumer to be automatically deleted,
  3851. // ensure that the consumer is not created by the library, which means
  3852. // create the consumer with AddConsumer and bind to this consumer (using
  3853. // the nats.Bind() option).
  3854. func (s *Subscription) Unsubscribe() error {
  3855. if s == nil {
  3856. return ErrBadSubscription
  3857. }
  3858. s.mu.Lock()
  3859. conn := s.conn
  3860. closed := s.closed
  3861. dc := s.jsi != nil && s.jsi.dc
  3862. s.mu.Unlock()
  3863. if conn == nil || conn.IsClosed() {
  3864. return ErrConnectionClosed
  3865. }
  3866. if closed {
  3867. return ErrBadSubscription
  3868. }
  3869. if conn.IsDraining() {
  3870. return ErrConnectionDraining
  3871. }
  3872. err := conn.unsubscribe(s, 0, false)
  3873. if err == nil && dc {
  3874. err = s.deleteConsumer()
  3875. }
  3876. return err
  3877. }
  3878. // checkDrained will watch for a subscription to be fully drained
  3879. // and then remove it.
  3880. func (nc *Conn) checkDrained(sub *Subscription) {
  3881. if nc == nil || sub == nil {
  3882. return
  3883. }
  3884. // This allows us to know that whatever we have in the client pending
  3885. // is correct and the server will not send additional information.
  3886. nc.Flush()
  3887. sub.mu.Lock()
  3888. // For JS subscriptions, check if we are going to delete the
  3889. // JS consumer when drain completes.
  3890. dc := sub.jsi != nil && sub.jsi.dc
  3891. sub.mu.Unlock()
  3892. // Once we are here we just wait for Pending to reach 0 or
  3893. // any other state to exit this go routine.
  3894. for {
  3895. // check connection is still valid.
  3896. if nc.IsClosed() {
  3897. return
  3898. }
  3899. // Check subscription state
  3900. sub.mu.Lock()
  3901. conn := sub.conn
  3902. closed := sub.closed
  3903. pMsgs := sub.pMsgs
  3904. sub.mu.Unlock()
  3905. if conn == nil || closed || pMsgs == 0 {
  3906. nc.mu.Lock()
  3907. nc.removeSub(sub)
  3908. nc.mu.Unlock()
  3909. if dc {
  3910. if err := sub.deleteConsumer(); err != nil {
  3911. nc.mu.Lock()
  3912. if errCB := nc.Opts.AsyncErrorCB; errCB != nil {
  3913. nc.ach.push(func() { errCB(nc, sub, err) })
  3914. }
  3915. nc.mu.Unlock()
  3916. }
  3917. }
  3918. return
  3919. }
  3920. time.Sleep(100 * time.Millisecond)
  3921. }
  3922. }
  3923. // AutoUnsubscribe will issue an automatic Unsubscribe that is
  3924. // processed by the server when max messages have been received.
  3925. // This can be useful when sending a request to an unknown number
  3926. // of subscribers.
  3927. func (s *Subscription) AutoUnsubscribe(max int) error {
  3928. if s == nil {
  3929. return ErrBadSubscription
  3930. }
  3931. s.mu.Lock()
  3932. conn := s.conn
  3933. closed := s.closed
  3934. s.mu.Unlock()
  3935. if conn == nil || closed {
  3936. return ErrBadSubscription
  3937. }
  3938. return conn.unsubscribe(s, max, false)
  3939. }
  3940. // SetClosedHandler will set the closed handler for when a subscription
  3941. // is closed (either unsubscribed or drained).
  3942. func (s *Subscription) SetClosedHandler(handler func(subject string)) {
  3943. s.mu.Lock()
  3944. s.pDone = handler
  3945. s.mu.Unlock()
  3946. }
  3947. // unsubscribe performs the low level unsubscribe to the server.
  3948. // Use Subscription.Unsubscribe()
  3949. func (nc *Conn) unsubscribe(sub *Subscription, max int, drainMode bool) error {
  3950. var maxStr string
  3951. if max > 0 {
  3952. sub.mu.Lock()
  3953. sub.max = uint64(max)
  3954. if sub.delivered < sub.max {
  3955. maxStr = strconv.Itoa(max)
  3956. }
  3957. sub.mu.Unlock()
  3958. }
  3959. nc.mu.Lock()
  3960. // ok here, but defer is expensive
  3961. defer nc.mu.Unlock()
  3962. if nc.isClosed() {
  3963. return ErrConnectionClosed
  3964. }
  3965. nc.subsMu.RLock()
  3966. s := nc.subs[sub.sid]
  3967. nc.subsMu.RUnlock()
  3968. // Already unsubscribed
  3969. if s == nil {
  3970. return nil
  3971. }
  3972. if maxStr == _EMPTY_ && !drainMode {
  3973. nc.removeSub(s)
  3974. }
  3975. if drainMode {
  3976. go nc.checkDrained(sub)
  3977. }
  3978. // We will send these for all subs when we reconnect
  3979. // so that we can suppress here.
  3980. if !nc.isReconnecting() {
  3981. nc.bw.appendString(fmt.Sprintf(unsubProto, s.sid, maxStr))
  3982. nc.kickFlusher()
  3983. }
  3984. // For JetStream subscriptions cancel the attached context if there is any.
  3985. var cancel func()
  3986. sub.mu.Lock()
  3987. jsi := sub.jsi
  3988. if jsi != nil {
  3989. cancel = jsi.cancel
  3990. jsi.cancel = nil
  3991. }
  3992. sub.mu.Unlock()
  3993. if cancel != nil {
  3994. cancel()
  3995. }
  3996. return nil
  3997. }
  3998. // NextMsg will return the next message available to a synchronous subscriber
  3999. // or block until one is available. An error is returned if the subscription is invalid (ErrBadSubscription),
  4000. // the connection is closed (ErrConnectionClosed), the timeout is reached (ErrTimeout),
  4001. // or if there were no responders (ErrNoResponders) when used in the context of a request/reply.
  4002. func (s *Subscription) NextMsg(timeout time.Duration) (*Msg, error) {
  4003. if s == nil {
  4004. return nil, ErrBadSubscription
  4005. }
  4006. s.mu.Lock()
  4007. err := s.validateNextMsgState(false)
  4008. if err != nil {
  4009. s.mu.Unlock()
  4010. return nil, err
  4011. }
  4012. // snapshot
  4013. mch := s.mch
  4014. s.mu.Unlock()
  4015. var ok bool
  4016. var msg *Msg
  4017. // If something is available right away, let's optimize that case.
  4018. select {
  4019. case msg, ok = <-mch:
  4020. if !ok {
  4021. return nil, s.getNextMsgErr()
  4022. }
  4023. if err := s.processNextMsgDelivered(msg); err != nil {
  4024. return nil, err
  4025. } else {
  4026. return msg, nil
  4027. }
  4028. default:
  4029. }
  4030. // If we are here a message was not immediately available, so lets loop
  4031. // with a timeout.
  4032. t := globalTimerPool.Get(timeout)
  4033. defer globalTimerPool.Put(t)
  4034. select {
  4035. case msg, ok = <-mch:
  4036. if !ok {
  4037. return nil, s.getNextMsgErr()
  4038. }
  4039. if err := s.processNextMsgDelivered(msg); err != nil {
  4040. return nil, err
  4041. }
  4042. case <-t.C:
  4043. return nil, ErrTimeout
  4044. }
  4045. return msg, nil
  4046. }
  4047. // validateNextMsgState checks whether the subscription is in a valid
  4048. // state to call NextMsg and be delivered another message synchronously.
  4049. // This should be called while holding the lock.
  4050. func (s *Subscription) validateNextMsgState(pullSubInternal bool) error {
  4051. if s.connClosed {
  4052. return ErrConnectionClosed
  4053. }
  4054. if s.mch == nil {
  4055. if s.max > 0 && s.delivered >= s.max {
  4056. return ErrMaxMessages
  4057. } else if s.closed {
  4058. return ErrBadSubscription
  4059. }
  4060. }
  4061. if s.mcb != nil {
  4062. return ErrSyncSubRequired
  4063. }
  4064. if s.sc {
  4065. s.sc = false
  4066. return ErrSlowConsumer
  4067. }
  4068. // Unless this is from an internal call, reject use of this API.
  4069. // Users should use Fetch() instead.
  4070. if !pullSubInternal && s.jsi != nil && s.jsi.pull {
  4071. return ErrTypeSubscription
  4072. }
  4073. return nil
  4074. }
  4075. // This is called when the sync channel has been closed.
  4076. // The error returned will be either connection or subscription
  4077. // closed depending on what caused NextMsg() to fail.
  4078. func (s *Subscription) getNextMsgErr() error {
  4079. s.mu.Lock()
  4080. defer s.mu.Unlock()
  4081. if s.connClosed {
  4082. return ErrConnectionClosed
  4083. }
  4084. return ErrBadSubscription
  4085. }
  4086. // processNextMsgDelivered takes a message and applies the needed
  4087. // accounting to the stats from the subscription, returning an
  4088. // error in case we have the maximum number of messages have been
  4089. // delivered already. It should not be called while holding the lock.
  4090. func (s *Subscription) processNextMsgDelivered(msg *Msg) error {
  4091. s.mu.Lock()
  4092. nc := s.conn
  4093. max := s.max
  4094. var fcReply string
  4095. // Update some stats.
  4096. s.delivered++
  4097. delivered := s.delivered
  4098. if s.jsi != nil {
  4099. fcReply = s.checkForFlowControlResponse()
  4100. }
  4101. if s.typ == SyncSubscription {
  4102. s.pMsgs--
  4103. s.pBytes -= len(msg.Data)
  4104. }
  4105. s.mu.Unlock()
  4106. if fcReply != _EMPTY_ {
  4107. nc.Publish(fcReply, nil)
  4108. }
  4109. if max > 0 {
  4110. if delivered > max {
  4111. return ErrMaxMessages
  4112. }
  4113. // Remove subscription if we have reached max.
  4114. if delivered == max {
  4115. nc.mu.Lock()
  4116. nc.removeSub(s)
  4117. nc.mu.Unlock()
  4118. }
  4119. }
  4120. if len(msg.Data) == 0 && msg.Header.Get(statusHdr) == noResponders {
  4121. return ErrNoResponders
  4122. }
  4123. return nil
  4124. }
  4125. // Queued returns the number of queued messages in the client for this subscription.
  4126. // DEPRECATED: Use Pending()
  4127. func (s *Subscription) QueuedMsgs() (int, error) {
  4128. m, _, err := s.Pending()
  4129. return int(m), err
  4130. }
  4131. // Pending returns the number of queued messages and queued bytes in the client for this subscription.
  4132. func (s *Subscription) Pending() (int, int, error) {
  4133. if s == nil {
  4134. return -1, -1, ErrBadSubscription
  4135. }
  4136. s.mu.Lock()
  4137. defer s.mu.Unlock()
  4138. if s.conn == nil || s.closed {
  4139. return -1, -1, ErrBadSubscription
  4140. }
  4141. if s.typ == ChanSubscription {
  4142. return -1, -1, ErrTypeSubscription
  4143. }
  4144. return s.pMsgs, s.pBytes, nil
  4145. }
  4146. // MaxPending returns the maximum number of queued messages and queued bytes seen so far.
  4147. func (s *Subscription) MaxPending() (int, int, error) {
  4148. if s == nil {
  4149. return -1, -1, ErrBadSubscription
  4150. }
  4151. s.mu.Lock()
  4152. defer s.mu.Unlock()
  4153. if s.conn == nil || s.closed {
  4154. return -1, -1, ErrBadSubscription
  4155. }
  4156. if s.typ == ChanSubscription {
  4157. return -1, -1, ErrTypeSubscription
  4158. }
  4159. return s.pMsgsMax, s.pBytesMax, nil
  4160. }
  4161. // ClearMaxPending resets the maximums seen so far.
  4162. func (s *Subscription) ClearMaxPending() error {
  4163. if s == nil {
  4164. return ErrBadSubscription
  4165. }
  4166. s.mu.Lock()
  4167. defer s.mu.Unlock()
  4168. if s.conn == nil || s.closed {
  4169. return ErrBadSubscription
  4170. }
  4171. if s.typ == ChanSubscription {
  4172. return ErrTypeSubscription
  4173. }
  4174. s.pMsgsMax, s.pBytesMax = 0, 0
  4175. return nil
  4176. }
  4177. // Pending Limits
  4178. const (
  4179. // DefaultSubPendingMsgsLimit will be 512k msgs.
  4180. DefaultSubPendingMsgsLimit = 512 * 1024
  4181. // DefaultSubPendingBytesLimit is 64MB
  4182. DefaultSubPendingBytesLimit = 64 * 1024 * 1024
  4183. )
  4184. // PendingLimits returns the current limits for this subscription.
  4185. // If no error is returned, a negative value indicates that the
  4186. // given metric is not limited.
  4187. func (s *Subscription) PendingLimits() (int, int, error) {
  4188. if s == nil {
  4189. return -1, -1, ErrBadSubscription
  4190. }
  4191. s.mu.Lock()
  4192. defer s.mu.Unlock()
  4193. if s.conn == nil || s.closed {
  4194. return -1, -1, ErrBadSubscription
  4195. }
  4196. if s.typ == ChanSubscription {
  4197. return -1, -1, ErrTypeSubscription
  4198. }
  4199. return s.pMsgsLimit, s.pBytesLimit, nil
  4200. }
  4201. // SetPendingLimits sets the limits for pending msgs and bytes for this subscription.
  4202. // Zero is not allowed. Any negative value means that the given metric is not limited.
  4203. func (s *Subscription) SetPendingLimits(msgLimit, bytesLimit int) error {
  4204. if s == nil {
  4205. return ErrBadSubscription
  4206. }
  4207. s.mu.Lock()
  4208. defer s.mu.Unlock()
  4209. if s.conn == nil || s.closed {
  4210. return ErrBadSubscription
  4211. }
  4212. if s.typ == ChanSubscription {
  4213. return ErrTypeSubscription
  4214. }
  4215. if msgLimit == 0 || bytesLimit == 0 {
  4216. return ErrInvalidArg
  4217. }
  4218. s.pMsgsLimit, s.pBytesLimit = msgLimit, bytesLimit
  4219. return nil
  4220. }
  4221. // Delivered returns the number of delivered messages for this subscription.
  4222. func (s *Subscription) Delivered() (int64, error) {
  4223. if s == nil {
  4224. return -1, ErrBadSubscription
  4225. }
  4226. s.mu.Lock()
  4227. defer s.mu.Unlock()
  4228. if s.conn == nil || s.closed {
  4229. return -1, ErrBadSubscription
  4230. }
  4231. return int64(s.delivered), nil
  4232. }
  4233. // Dropped returns the number of known dropped messages for this subscription.
  4234. // This will correspond to messages dropped by violations of PendingLimits. If
  4235. // the server declares the connection a SlowConsumer, this number may not be
  4236. // valid.
  4237. func (s *Subscription) Dropped() (int, error) {
  4238. if s == nil {
  4239. return -1, ErrBadSubscription
  4240. }
  4241. s.mu.Lock()
  4242. defer s.mu.Unlock()
  4243. if s.conn == nil || s.closed {
  4244. return -1, ErrBadSubscription
  4245. }
  4246. return s.dropped, nil
  4247. }
  4248. // Respond allows a convenient way to respond to requests in service based subscriptions.
  4249. func (m *Msg) Respond(data []byte) error {
  4250. if m == nil || m.Sub == nil {
  4251. return ErrMsgNotBound
  4252. }
  4253. if m.Reply == "" {
  4254. return ErrMsgNoReply
  4255. }
  4256. m.Sub.mu.Lock()
  4257. nc := m.Sub.conn
  4258. m.Sub.mu.Unlock()
  4259. // No need to check the connection here since the call to publish will do all the checking.
  4260. return nc.Publish(m.Reply, data)
  4261. }
  4262. // RespondMsg allows a convenient way to respond to requests in service based subscriptions that might include headers
  4263. func (m *Msg) RespondMsg(msg *Msg) error {
  4264. if m == nil || m.Sub == nil {
  4265. return ErrMsgNotBound
  4266. }
  4267. if m.Reply == "" {
  4268. return ErrMsgNoReply
  4269. }
  4270. msg.Subject = m.Reply
  4271. m.Sub.mu.Lock()
  4272. nc := m.Sub.conn
  4273. m.Sub.mu.Unlock()
  4274. // No need to check the connection here since the call to publish will do all the checking.
  4275. return nc.PublishMsg(msg)
  4276. }
  4277. // FIXME: This is a hack
  4278. // removeFlushEntry is needed when we need to discard queued up responses
  4279. // for our pings as part of a flush call. This happens when we have a flush
  4280. // call outstanding and we call close.
  4281. func (nc *Conn) removeFlushEntry(ch chan struct{}) bool {
  4282. nc.mu.Lock()
  4283. defer nc.mu.Unlock()
  4284. if nc.pongs == nil {
  4285. return false
  4286. }
  4287. for i, c := range nc.pongs {
  4288. if c == ch {
  4289. nc.pongs[i] = nil
  4290. return true
  4291. }
  4292. }
  4293. return false
  4294. }
  4295. // The lock must be held entering this function.
  4296. func (nc *Conn) sendPing(ch chan struct{}) {
  4297. nc.pongs = append(nc.pongs, ch)
  4298. nc.bw.appendString(pingProto)
  4299. // Flush in place.
  4300. nc.bw.flush()
  4301. }
  4302. // This will fire periodically and send a client origin
  4303. // ping to the server. Will also check that we have received
  4304. // responses from the server.
  4305. func (nc *Conn) processPingTimer() {
  4306. nc.mu.Lock()
  4307. if nc.status != CONNECTED {
  4308. nc.mu.Unlock()
  4309. return
  4310. }
  4311. // Check for violation
  4312. nc.pout++
  4313. if nc.pout > nc.Opts.MaxPingsOut {
  4314. nc.mu.Unlock()
  4315. nc.processOpErr(ErrStaleConnection)
  4316. return
  4317. }
  4318. nc.sendPing(nil)
  4319. nc.ptmr.Reset(nc.Opts.PingInterval)
  4320. nc.mu.Unlock()
  4321. }
  4322. // FlushTimeout allows a Flush operation to have an associated timeout.
  4323. func (nc *Conn) FlushTimeout(timeout time.Duration) (err error) {
  4324. if nc == nil {
  4325. return ErrInvalidConnection
  4326. }
  4327. if timeout <= 0 {
  4328. return ErrBadTimeout
  4329. }
  4330. nc.mu.Lock()
  4331. if nc.isClosed() {
  4332. nc.mu.Unlock()
  4333. return ErrConnectionClosed
  4334. }
  4335. t := globalTimerPool.Get(timeout)
  4336. defer globalTimerPool.Put(t)
  4337. // Create a buffered channel to prevent chan send to block
  4338. // in processPong() if this code here times out just when
  4339. // PONG was received.
  4340. ch := make(chan struct{}, 1)
  4341. nc.sendPing(ch)
  4342. nc.mu.Unlock()
  4343. select {
  4344. case _, ok := <-ch:
  4345. if !ok {
  4346. err = ErrConnectionClosed
  4347. } else {
  4348. close(ch)
  4349. }
  4350. case <-t.C:
  4351. err = ErrTimeout
  4352. }
  4353. if err != nil {
  4354. nc.removeFlushEntry(ch)
  4355. }
  4356. return
  4357. }
  4358. // RTT calculates the round trip time between this client and the server.
  4359. func (nc *Conn) RTT() (time.Duration, error) {
  4360. if nc.IsClosed() {
  4361. return 0, ErrConnectionClosed
  4362. }
  4363. if nc.IsReconnecting() {
  4364. return 0, ErrDisconnected
  4365. }
  4366. start := time.Now()
  4367. if err := nc.FlushTimeout(10 * time.Second); err != nil {
  4368. return 0, err
  4369. }
  4370. return time.Since(start), nil
  4371. }
  4372. // Flush will perform a round trip to the server and return when it
  4373. // receives the internal reply.
  4374. func (nc *Conn) Flush() error {
  4375. return nc.FlushTimeout(10 * time.Second)
  4376. }
  4377. // Buffered will return the number of bytes buffered to be sent to the server.
  4378. // FIXME(dlc) take into account disconnected state.
  4379. func (nc *Conn) Buffered() (int, error) {
  4380. nc.mu.RLock()
  4381. defer nc.mu.RUnlock()
  4382. if nc.isClosed() || nc.bw == nil {
  4383. return -1, ErrConnectionClosed
  4384. }
  4385. return nc.bw.buffered(), nil
  4386. }
  4387. // resendSubscriptions will send our subscription state back to the
  4388. // server. Used in reconnects
  4389. func (nc *Conn) resendSubscriptions() {
  4390. // Since we are going to send protocols to the server, we don't want to
  4391. // be holding the subsMu lock (which is used in processMsg). So copy
  4392. // the subscriptions in a temporary array.
  4393. nc.subsMu.RLock()
  4394. subs := make([]*Subscription, 0, len(nc.subs))
  4395. for _, s := range nc.subs {
  4396. subs = append(subs, s)
  4397. }
  4398. nc.subsMu.RUnlock()
  4399. for _, s := range subs {
  4400. adjustedMax := uint64(0)
  4401. s.mu.Lock()
  4402. if s.max > 0 {
  4403. if s.delivered < s.max {
  4404. adjustedMax = s.max - s.delivered
  4405. }
  4406. // adjustedMax could be 0 here if the number of delivered msgs
  4407. // reached the max, if so unsubscribe.
  4408. if adjustedMax == 0 {
  4409. s.mu.Unlock()
  4410. nc.bw.writeDirect(fmt.Sprintf(unsubProto, s.sid, _EMPTY_))
  4411. continue
  4412. }
  4413. }
  4414. subj, queue, sid := s.Subject, s.Queue, s.sid
  4415. s.mu.Unlock()
  4416. nc.bw.writeDirect(fmt.Sprintf(subProto, subj, queue, sid))
  4417. if adjustedMax > 0 {
  4418. maxStr := strconv.Itoa(int(adjustedMax))
  4419. nc.bw.writeDirect(fmt.Sprintf(unsubProto, sid, maxStr))
  4420. }
  4421. }
  4422. }
  4423. // This will clear any pending flush calls and release pending calls.
  4424. // Lock is assumed to be held by the caller.
  4425. func (nc *Conn) clearPendingFlushCalls() {
  4426. // Clear any queued pongs, e.g. pending flush calls.
  4427. for _, ch := range nc.pongs {
  4428. if ch != nil {
  4429. close(ch)
  4430. }
  4431. }
  4432. nc.pongs = nil
  4433. }
  4434. // This will clear any pending Request calls.
  4435. // Lock is assumed to be held by the caller.
  4436. func (nc *Conn) clearPendingRequestCalls() {
  4437. if nc.respMap == nil {
  4438. return
  4439. }
  4440. for key, ch := range nc.respMap {
  4441. if ch != nil {
  4442. close(ch)
  4443. delete(nc.respMap, key)
  4444. }
  4445. }
  4446. }
  4447. // Low level close call that will do correct cleanup and set
  4448. // desired status. Also controls whether user defined callbacks
  4449. // will be triggered. The lock should not be held entering this
  4450. // function. This function will handle the locking manually.
  4451. func (nc *Conn) close(status Status, doCBs bool, err error) {
  4452. nc.mu.Lock()
  4453. if nc.isClosed() {
  4454. nc.status = status
  4455. nc.mu.Unlock()
  4456. return
  4457. }
  4458. nc.status = CLOSED
  4459. // Kick the Go routines so they fall out.
  4460. nc.kickFlusher()
  4461. // If the reconnect timer is waiting between a reconnect attempt,
  4462. // this will kick it out.
  4463. if nc.rqch != nil {
  4464. close(nc.rqch)
  4465. nc.rqch = nil
  4466. }
  4467. // Clear any queued pongs, e.g. pending flush calls.
  4468. nc.clearPendingFlushCalls()
  4469. // Clear any queued and blocking Requests.
  4470. nc.clearPendingRequestCalls()
  4471. // Stop ping timer if set.
  4472. nc.stopPingTimer()
  4473. nc.ptmr = nil
  4474. // Need to close and set TCP conn to nil if reconnect loop has stopped,
  4475. // otherwise we would incorrectly invoke Disconnect handler (if set)
  4476. // down below.
  4477. if nc.ar && nc.conn != nil {
  4478. nc.conn.Close()
  4479. nc.conn = nil
  4480. } else if nc.conn != nil {
  4481. // Go ahead and make sure we have flushed the outbound
  4482. nc.bw.flush()
  4483. defer nc.conn.Close()
  4484. }
  4485. // Close sync subscriber channels and release any
  4486. // pending NextMsg() calls.
  4487. nc.subsMu.Lock()
  4488. for _, s := range nc.subs {
  4489. s.mu.Lock()
  4490. // Release callers on NextMsg for SyncSubscription only
  4491. if s.mch != nil && s.typ == SyncSubscription {
  4492. close(s.mch)
  4493. }
  4494. s.mch = nil
  4495. // Mark as invalid, for signaling to waitForMsgs
  4496. s.closed = true
  4497. // Mark connection closed in subscription
  4498. s.connClosed = true
  4499. // If we have an async subscription, signals it to exit
  4500. if s.typ == AsyncSubscription && s.pCond != nil {
  4501. s.pCond.Signal()
  4502. }
  4503. s.mu.Unlock()
  4504. }
  4505. nc.subs = nil
  4506. nc.subsMu.Unlock()
  4507. nc.changeConnStatus(status)
  4508. // Perform appropriate callback if needed for a disconnect.
  4509. if doCBs {
  4510. if nc.conn != nil {
  4511. if disconnectedErrCB := nc.Opts.DisconnectedErrCB; disconnectedErrCB != nil {
  4512. nc.ach.push(func() { disconnectedErrCB(nc, err) })
  4513. } else if disconnectedCB := nc.Opts.DisconnectedCB; disconnectedCB != nil {
  4514. nc.ach.push(func() { disconnectedCB(nc) })
  4515. }
  4516. }
  4517. if nc.Opts.ClosedCB != nil {
  4518. nc.ach.push(func() { nc.Opts.ClosedCB(nc) })
  4519. }
  4520. }
  4521. // If this is terminal, then we have to notify the asyncCB handler that
  4522. // it can exit once all async callbacks have been dispatched.
  4523. if status == CLOSED {
  4524. nc.ach.close()
  4525. }
  4526. nc.mu.Unlock()
  4527. }
  4528. // Close will close the connection to the server. This call will release
  4529. // all blocking calls, such as Flush() and NextMsg()
  4530. func (nc *Conn) Close() {
  4531. if nc != nil {
  4532. // This will be a no-op if the connection was not websocket.
  4533. // We do this here as opposed to inside close() because we want
  4534. // to do this only for the final user-driven close of the client.
  4535. // Otherwise, we would need to change close() to pass a boolean
  4536. // indicating that this is the case.
  4537. nc.wsClose()
  4538. nc.close(CLOSED, !nc.Opts.NoCallbacksAfterClientClose, nil)
  4539. }
  4540. }
  4541. // IsClosed tests if a Conn has been closed.
  4542. func (nc *Conn) IsClosed() bool {
  4543. nc.mu.RLock()
  4544. defer nc.mu.RUnlock()
  4545. return nc.isClosed()
  4546. }
  4547. // IsReconnecting tests if a Conn is reconnecting.
  4548. func (nc *Conn) IsReconnecting() bool {
  4549. nc.mu.RLock()
  4550. defer nc.mu.RUnlock()
  4551. return nc.isReconnecting()
  4552. }
  4553. // IsConnected tests if a Conn is connected.
  4554. func (nc *Conn) IsConnected() bool {
  4555. nc.mu.RLock()
  4556. defer nc.mu.RUnlock()
  4557. return nc.isConnected()
  4558. }
  4559. // drainConnection will run in a separate Go routine and will
  4560. // flush all publishes and drain all active subscriptions.
  4561. func (nc *Conn) drainConnection() {
  4562. // Snapshot subs list.
  4563. nc.mu.Lock()
  4564. // Check again here if we are in a state to not process.
  4565. if nc.isClosed() {
  4566. nc.mu.Unlock()
  4567. return
  4568. }
  4569. if nc.isConnecting() || nc.isReconnecting() {
  4570. nc.mu.Unlock()
  4571. // Move to closed state.
  4572. nc.Close()
  4573. return
  4574. }
  4575. subs := make([]*Subscription, 0, len(nc.subs))
  4576. for _, s := range nc.subs {
  4577. if s == nc.respMux {
  4578. // Skip since might be in use while messages
  4579. // are being processed (can miss responses).
  4580. continue
  4581. }
  4582. subs = append(subs, s)
  4583. }
  4584. errCB := nc.Opts.AsyncErrorCB
  4585. drainWait := nc.Opts.DrainTimeout
  4586. respMux := nc.respMux
  4587. nc.mu.Unlock()
  4588. // for pushing errors with context.
  4589. pushErr := func(err error) {
  4590. nc.mu.Lock()
  4591. nc.err = err
  4592. if errCB != nil {
  4593. nc.ach.push(func() { errCB(nc, nil, err) })
  4594. }
  4595. nc.mu.Unlock()
  4596. }
  4597. // Do subs first, skip request handler if present.
  4598. for _, s := range subs {
  4599. if err := s.Drain(); err != nil {
  4600. // We will notify about these but continue.
  4601. pushErr(err)
  4602. }
  4603. }
  4604. // Wait for the subscriptions to drop to zero.
  4605. timeout := time.Now().Add(drainWait)
  4606. var min int
  4607. if respMux != nil {
  4608. min = 1
  4609. } else {
  4610. min = 0
  4611. }
  4612. for time.Now().Before(timeout) {
  4613. if nc.NumSubscriptions() == min {
  4614. break
  4615. }
  4616. time.Sleep(10 * time.Millisecond)
  4617. }
  4618. // In case there was a request/response handler
  4619. // then need to call drain at the end.
  4620. if respMux != nil {
  4621. if err := respMux.Drain(); err != nil {
  4622. // We will notify about these but continue.
  4623. pushErr(err)
  4624. }
  4625. for time.Now().Before(timeout) {
  4626. if nc.NumSubscriptions() == 0 {
  4627. break
  4628. }
  4629. time.Sleep(10 * time.Millisecond)
  4630. }
  4631. }
  4632. // Check if we timed out.
  4633. if nc.NumSubscriptions() != 0 {
  4634. pushErr(ErrDrainTimeout)
  4635. }
  4636. // Flip State
  4637. nc.mu.Lock()
  4638. nc.changeConnStatus(DRAINING_PUBS)
  4639. nc.mu.Unlock()
  4640. // Do publish drain via Flush() call.
  4641. err := nc.FlushTimeout(5 * time.Second)
  4642. if err != nil {
  4643. pushErr(err)
  4644. }
  4645. // Move to closed state.
  4646. nc.Close()
  4647. }
  4648. // Drain will put a connection into a drain state. All subscriptions will
  4649. // immediately be put into a drain state. Upon completion, the publishers
  4650. // will be drained and can not publish any additional messages. Upon draining
  4651. // of the publishers, the connection will be closed. Use the ClosedCB()
  4652. // option to know when the connection has moved from draining to closed.
  4653. //
  4654. // See note in Subscription.Drain for JetStream subscriptions.
  4655. func (nc *Conn) Drain() error {
  4656. nc.mu.Lock()
  4657. if nc.isClosed() {
  4658. nc.mu.Unlock()
  4659. return ErrConnectionClosed
  4660. }
  4661. if nc.isConnecting() || nc.isReconnecting() {
  4662. nc.mu.Unlock()
  4663. nc.Close()
  4664. return ErrConnectionReconnecting
  4665. }
  4666. if nc.isDraining() {
  4667. nc.mu.Unlock()
  4668. return nil
  4669. }
  4670. nc.changeConnStatus(DRAINING_SUBS)
  4671. go nc.drainConnection()
  4672. nc.mu.Unlock()
  4673. return nil
  4674. }
  4675. // IsDraining tests if a Conn is in the draining state.
  4676. func (nc *Conn) IsDraining() bool {
  4677. nc.mu.RLock()
  4678. defer nc.mu.RUnlock()
  4679. return nc.isDraining()
  4680. }
  4681. // caller must lock
  4682. func (nc *Conn) getServers(implicitOnly bool) []string {
  4683. poolSize := len(nc.srvPool)
  4684. var servers = make([]string, 0)
  4685. for i := 0; i < poolSize; i++ {
  4686. if implicitOnly && !nc.srvPool[i].isImplicit {
  4687. continue
  4688. }
  4689. url := nc.srvPool[i].url
  4690. servers = append(servers, fmt.Sprintf("%s://%s", url.Scheme, url.Host))
  4691. }
  4692. return servers
  4693. }
  4694. // Servers returns the list of known server urls, including additional
  4695. // servers discovered after a connection has been established. If
  4696. // authentication is enabled, use UserInfo or Token when connecting with
  4697. // these urls.
  4698. func (nc *Conn) Servers() []string {
  4699. nc.mu.RLock()
  4700. defer nc.mu.RUnlock()
  4701. return nc.getServers(false)
  4702. }
  4703. // DiscoveredServers returns only the server urls that have been discovered
  4704. // after a connection has been established. If authentication is enabled,
  4705. // use UserInfo or Token when connecting with these urls.
  4706. func (nc *Conn) DiscoveredServers() []string {
  4707. nc.mu.RLock()
  4708. defer nc.mu.RUnlock()
  4709. return nc.getServers(true)
  4710. }
  4711. // Status returns the current state of the connection.
  4712. func (nc *Conn) Status() Status {
  4713. nc.mu.RLock()
  4714. defer nc.mu.RUnlock()
  4715. return nc.status
  4716. }
  4717. // Test if Conn has been closed Lock is assumed held.
  4718. func (nc *Conn) isClosed() bool {
  4719. return nc.status == CLOSED
  4720. }
  4721. // Test if Conn is in the process of connecting
  4722. func (nc *Conn) isConnecting() bool {
  4723. return nc.status == CONNECTING
  4724. }
  4725. // Test if Conn is being reconnected.
  4726. func (nc *Conn) isReconnecting() bool {
  4727. return nc.status == RECONNECTING
  4728. }
  4729. // Test if Conn is connected or connecting.
  4730. func (nc *Conn) isConnected() bool {
  4731. return nc.status == CONNECTED || nc.isDraining()
  4732. }
  4733. // Test if Conn is in the draining state.
  4734. func (nc *Conn) isDraining() bool {
  4735. return nc.status == DRAINING_SUBS || nc.status == DRAINING_PUBS
  4736. }
  4737. // Test if Conn is in the draining state for pubs.
  4738. func (nc *Conn) isDrainingPubs() bool {
  4739. return nc.status == DRAINING_PUBS
  4740. }
  4741. // Stats will return a race safe copy of the Statistics section for the connection.
  4742. func (nc *Conn) Stats() Statistics {
  4743. // Stats are updated either under connection's mu or with atomic operations
  4744. // for inbound stats in processMsg().
  4745. nc.mu.Lock()
  4746. stats := Statistics{
  4747. InMsgs: atomic.LoadUint64(&nc.InMsgs),
  4748. InBytes: atomic.LoadUint64(&nc.InBytes),
  4749. OutMsgs: nc.OutMsgs,
  4750. OutBytes: nc.OutBytes,
  4751. Reconnects: nc.Reconnects,
  4752. }
  4753. nc.mu.Unlock()
  4754. return stats
  4755. }
  4756. // MaxPayload returns the size limit that a message payload can have.
  4757. // This is set by the server configuration and delivered to the client
  4758. // upon connect.
  4759. func (nc *Conn) MaxPayload() int64 {
  4760. nc.mu.RLock()
  4761. defer nc.mu.RUnlock()
  4762. return nc.info.MaxPayload
  4763. }
  4764. // HeadersSupported will return if the server supports headers
  4765. func (nc *Conn) HeadersSupported() bool {
  4766. nc.mu.RLock()
  4767. defer nc.mu.RUnlock()
  4768. return nc.info.Headers
  4769. }
  4770. // AuthRequired will return if the connected server requires authorization.
  4771. func (nc *Conn) AuthRequired() bool {
  4772. nc.mu.RLock()
  4773. defer nc.mu.RUnlock()
  4774. return nc.info.AuthRequired
  4775. }
  4776. // TLSRequired will return if the connected server requires TLS connections.
  4777. func (nc *Conn) TLSRequired() bool {
  4778. nc.mu.RLock()
  4779. defer nc.mu.RUnlock()
  4780. return nc.info.TLSRequired
  4781. }
  4782. // Barrier schedules the given function `f` to all registered asynchronous
  4783. // subscriptions.
  4784. // Only the last subscription to see this barrier will invoke the function.
  4785. // If no subscription is registered at the time of this call, `f()` is invoked
  4786. // right away.
  4787. // ErrConnectionClosed is returned if the connection is closed prior to
  4788. // the call.
  4789. func (nc *Conn) Barrier(f func()) error {
  4790. nc.mu.Lock()
  4791. if nc.isClosed() {
  4792. nc.mu.Unlock()
  4793. return ErrConnectionClosed
  4794. }
  4795. nc.subsMu.Lock()
  4796. // Need to figure out how many non chan subscriptions there are
  4797. numSubs := 0
  4798. for _, sub := range nc.subs {
  4799. if sub.typ == AsyncSubscription {
  4800. numSubs++
  4801. }
  4802. }
  4803. if numSubs == 0 {
  4804. nc.subsMu.Unlock()
  4805. nc.mu.Unlock()
  4806. f()
  4807. return nil
  4808. }
  4809. barrier := &barrierInfo{refs: int64(numSubs), f: f}
  4810. for _, sub := range nc.subs {
  4811. sub.mu.Lock()
  4812. if sub.mch == nil {
  4813. msg := &Msg{barrier: barrier}
  4814. // Push onto the async pList
  4815. if sub.pTail != nil {
  4816. sub.pTail.next = msg
  4817. } else {
  4818. sub.pHead = msg
  4819. sub.pCond.Signal()
  4820. }
  4821. sub.pTail = msg
  4822. }
  4823. sub.mu.Unlock()
  4824. }
  4825. nc.subsMu.Unlock()
  4826. nc.mu.Unlock()
  4827. return nil
  4828. }
  4829. // GetClientIP returns the client IP as known by the server.
  4830. // Supported as of server version 2.1.6.
  4831. func (nc *Conn) GetClientIP() (net.IP, error) {
  4832. nc.mu.RLock()
  4833. defer nc.mu.RUnlock()
  4834. if nc.isClosed() {
  4835. return nil, ErrConnectionClosed
  4836. }
  4837. if nc.info.ClientIP == "" {
  4838. return nil, ErrClientIPNotSupported
  4839. }
  4840. ip := net.ParseIP(nc.info.ClientIP)
  4841. return ip, nil
  4842. }
  4843. // GetClientID returns the client ID assigned by the server to which
  4844. // the client is currently connected to. Note that the value may change if
  4845. // the client reconnects.
  4846. // This function returns ErrClientIDNotSupported if the server is of a
  4847. // version prior to 1.2.0.
  4848. func (nc *Conn) GetClientID() (uint64, error) {
  4849. nc.mu.RLock()
  4850. defer nc.mu.RUnlock()
  4851. if nc.isClosed() {
  4852. return 0, ErrConnectionClosed
  4853. }
  4854. if nc.info.CID == 0 {
  4855. return 0, ErrClientIDNotSupported
  4856. }
  4857. return nc.info.CID, nil
  4858. }
  4859. // StatusChanged returns a channel on which given list of connection status changes will be reported.
  4860. // If no statuses are provided, defaults will be used: CONNECTED, RECONNECTING, DISCONNECTED, CLOSED.
  4861. func (nc *Conn) StatusChanged(statuses ...Status) chan Status {
  4862. if len(statuses) == 0 {
  4863. statuses = []Status{CONNECTED, RECONNECTING, DISCONNECTED, CLOSED}
  4864. }
  4865. ch := make(chan Status, 10)
  4866. for _, s := range statuses {
  4867. nc.registerStatusChangeListener(s, ch)
  4868. }
  4869. return ch
  4870. }
  4871. // registerStatusChangeListener registers a channel waiting for a specific status change event.
  4872. // Status change events are non-blocking - if no receiver is waiting for the status change,
  4873. // it will not be sent on the channel. Closed channels are ignored.
  4874. func (nc *Conn) registerStatusChangeListener(status Status, ch chan Status) {
  4875. nc.mu.Lock()
  4876. defer nc.mu.Unlock()
  4877. if nc.statListeners == nil {
  4878. nc.statListeners = make(map[Status][]chan Status)
  4879. }
  4880. if _, ok := nc.statListeners[status]; !ok {
  4881. nc.statListeners[status] = make([]chan Status, 0)
  4882. }
  4883. nc.statListeners[status] = append(nc.statListeners[status], ch)
  4884. }
  4885. // sendStatusEvent sends connection status event to all channels.
  4886. // If channel is closed, or there is no listener, sendStatusEvent
  4887. // will not block. Lock should be held entering.
  4888. func (nc *Conn) sendStatusEvent(s Status) {
  4889. Loop:
  4890. for i := 0; i < len(nc.statListeners[s]); i++ {
  4891. // make sure channel is not closed
  4892. select {
  4893. case <-nc.statListeners[s][i]:
  4894. // if chan is closed, remove it
  4895. nc.statListeners[s][i] = nc.statListeners[s][len(nc.statListeners[s])-1]
  4896. nc.statListeners[s] = nc.statListeners[s][:len(nc.statListeners[s])-1]
  4897. i--
  4898. continue Loop
  4899. default:
  4900. }
  4901. // only send event if someone's listening
  4902. select {
  4903. case nc.statListeners[s][i] <- s:
  4904. default:
  4905. }
  4906. }
  4907. }
  4908. // changeConnStatus changes connections status and sends events
  4909. // to all listeners. Lock should be held entering.
  4910. func (nc *Conn) changeConnStatus(status Status) {
  4911. if nc == nil {
  4912. return
  4913. }
  4914. nc.sendStatusEvent(status)
  4915. nc.status = status
  4916. }
  4917. // NkeyOptionFromSeed will load an nkey pair from a seed file.
  4918. // It will return the NKey Option and will handle
  4919. // signing of nonce challenges from the server. It will take
  4920. // care to not hold keys in memory and to wipe memory.
  4921. func NkeyOptionFromSeed(seedFile string) (Option, error) {
  4922. kp, err := nkeyPairFromSeedFile(seedFile)
  4923. if err != nil {
  4924. return nil, err
  4925. }
  4926. // Wipe our key on exit.
  4927. defer kp.Wipe()
  4928. pub, err := kp.PublicKey()
  4929. if err != nil {
  4930. return nil, err
  4931. }
  4932. if !nkeys.IsValidPublicUserKey(pub) {
  4933. return nil, fmt.Errorf("nats: Not a valid nkey user seed")
  4934. }
  4935. sigCB := func(nonce []byte) ([]byte, error) {
  4936. return sigHandler(nonce, seedFile)
  4937. }
  4938. return Nkey(string(pub), sigCB), nil
  4939. }
  4940. // Just wipe slice with 'x', for clearing contents of creds or nkey seed file.
  4941. func wipeSlice(buf []byte) {
  4942. for i := range buf {
  4943. buf[i] = 'x'
  4944. }
  4945. }
  4946. func userFromFile(userFile string) (string, error) {
  4947. path, err := expandPath(userFile)
  4948. if err != nil {
  4949. return _EMPTY_, fmt.Errorf("nats: %w", err)
  4950. }
  4951. contents, err := os.ReadFile(path)
  4952. if err != nil {
  4953. return _EMPTY_, fmt.Errorf("nats: %w", err)
  4954. }
  4955. defer wipeSlice(contents)
  4956. return nkeys.ParseDecoratedJWT(contents)
  4957. }
  4958. func homeDir() (string, error) {
  4959. if runtime.GOOS == "windows" {
  4960. homeDrive, homePath := os.Getenv("HOMEDRIVE"), os.Getenv("HOMEPATH")
  4961. userProfile := os.Getenv("USERPROFILE")
  4962. var home string
  4963. if homeDrive == "" || homePath == "" {
  4964. if userProfile == "" {
  4965. return _EMPTY_, errors.New("nats: failed to get home dir, require %HOMEDRIVE% and %HOMEPATH% or %USERPROFILE%")
  4966. }
  4967. home = userProfile
  4968. } else {
  4969. home = filepath.Join(homeDrive, homePath)
  4970. }
  4971. return home, nil
  4972. }
  4973. home := os.Getenv("HOME")
  4974. if home == "" {
  4975. return _EMPTY_, errors.New("nats: failed to get home dir, require $HOME")
  4976. }
  4977. return home, nil
  4978. }
  4979. func expandPath(p string) (string, error) {
  4980. p = os.ExpandEnv(p)
  4981. if !strings.HasPrefix(p, "~") {
  4982. return p, nil
  4983. }
  4984. home, err := homeDir()
  4985. if err != nil {
  4986. return _EMPTY_, err
  4987. }
  4988. return filepath.Join(home, p[1:]), nil
  4989. }
  4990. func nkeyPairFromSeedFile(seedFile string) (nkeys.KeyPair, error) {
  4991. contents, err := os.ReadFile(seedFile)
  4992. if err != nil {
  4993. return nil, fmt.Errorf("nats: %w", err)
  4994. }
  4995. defer wipeSlice(contents)
  4996. return nkeys.ParseDecoratedNKey(contents)
  4997. }
  4998. // Sign authentication challenges from the server.
  4999. // Do not keep private seed in memory.
  5000. func sigHandler(nonce []byte, seedFile string) ([]byte, error) {
  5001. kp, err := nkeyPairFromSeedFile(seedFile)
  5002. if err != nil {
  5003. return nil, fmt.Errorf("unable to extract key pair from file %q: %w", seedFile, err)
  5004. }
  5005. // Wipe our key on exit.
  5006. defer kp.Wipe()
  5007. sig, _ := kp.Sign(nonce)
  5008. return sig, nil
  5009. }
  5010. type timeoutWriter struct {
  5011. timeout time.Duration
  5012. conn net.Conn
  5013. err error
  5014. }
  5015. // Write implements the io.Writer interface.
  5016. func (tw *timeoutWriter) Write(p []byte) (int, error) {
  5017. if tw.err != nil {
  5018. return 0, tw.err
  5019. }
  5020. var n int
  5021. tw.conn.SetWriteDeadline(time.Now().Add(tw.timeout))
  5022. n, tw.err = tw.conn.Write(p)
  5023. tw.conn.SetWriteDeadline(time.Time{})
  5024. return n, tw.err
  5025. }