zookeeper.c 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #if !defined(DLL_EXPORT) && !defined(USE_STATIC_LIB)
  19. # define USE_STATIC_LIB
  20. #endif
  21. #if defined(__CYGWIN__)
  22. #define USE_IPV6
  23. #endif
  24. #include "config.h"
  25. #include <zookeeper.h>
  26. #include <zookeeper.jute.h>
  27. #include <proto.h>
  28. #include "zk_adaptor.h"
  29. #include "zookeeper_log.h"
  30. #include "zk_hashtable.h"
  31. #ifdef HAVE_CYRUS_SASL_H
  32. #include "zk_sasl.h"
  33. #endif /* HAVE_CYRUS_SASL_H */
  34. #include <stdlib.h>
  35. #include <stdio.h>
  36. #include <string.h>
  37. #include <time.h>
  38. #include <errno.h>
  39. #include <fcntl.h>
  40. #include <assert.h>
  41. #include <stdarg.h>
  42. #include <limits.h>
  43. #ifdef HAVE_SYS_TIME_H
  44. #include <sys/time.h>
  45. #endif
  46. #ifdef HAVE_SYS_SOCKET_H
  47. #include <sys/socket.h>
  48. #endif
  49. #ifdef HAVE_POLL
  50. #include <poll.h>
  51. #endif
  52. #ifdef HAVE_NETINET_IN_H
  53. #include <netinet/in.h>
  54. #include <netinet/tcp.h>
  55. #endif
  56. #ifdef HAVE_ARPA_INET_H
  57. #include <arpa/inet.h>
  58. #endif
  59. #ifdef HAVE_NETDB_H
  60. #include <netdb.h>
  61. #endif
  62. #ifdef HAVE_UNISTD_H
  63. #include <unistd.h> // needed for _POSIX_MONOTONIC_CLOCK
  64. #endif
  65. #ifdef HAVE_SYS_UTSNAME_H
  66. #include <sys/utsname.h>
  67. #endif
  68. #ifdef HAVE_GETPWUID_R
  69. #include <pwd.h>
  70. #endif
  71. #ifdef HAVE_OPENSSL_H
  72. #include <openssl/ssl.h>
  73. #include <openssl/err.h>
  74. #endif
  75. #ifdef __MACH__ // OS X
  76. #include <mach/clock.h>
  77. #include <mach/mach.h>
  78. #include <netinet/tcp.h>
  79. #endif
  80. #ifdef WIN32
  81. #include <process.h> /* for getpid */
  82. #include <direct.h> /* for getcwd */
  83. #define EAI_ADDRFAMILY WSAEINVAL /* is this still needed? */
  84. #define EHOSTDOWN EPIPE
  85. #define ESTALE ENODEV
  86. #endif
  87. #define IF_DEBUG(x) if(logLevel==ZOO_LOG_LEVEL_DEBUG) {x;}
  88. const int ZOOKEEPER_WRITE = 1 << 0;
  89. const int ZOOKEEPER_READ = 1 << 1;
  90. const int ZOO_PERSISTENT = 0;
  91. const int ZOO_EPHEMERAL = 1;
  92. const int ZOO_PERSISTENT_SEQUENTIAL = 2;
  93. const int ZOO_EPHEMERAL_SEQUENTIAL = 3;
  94. const int ZOO_CONTAINER = 4;
  95. const int ZOO_PERSISTENT_WITH_TTL = 5;
  96. const int ZOO_PERSISTENT_SEQUENTIAL_WITH_TTL = 6;
  97. #define ZOOKEEPER_IS_SEQUENCE(mode) \
  98. ((mode) == ZOO_PERSISTENT_SEQUENTIAL || \
  99. (mode) == ZOO_EPHEMERAL_SEQUENTIAL || \
  100. (mode) == ZOO_PERSISTENT_SEQUENTIAL_WITH_TTL)
  101. #define ZOOKEEPER_IS_TTL(mode) \
  102. ((mode) == ZOO_PERSISTENT_WITH_TTL || \
  103. (mode) == ZOO_PERSISTENT_SEQUENTIAL_WITH_TTL)
  104. // keep ZOO_SEQUENCE as a bitmask for compatibility reasons
  105. const int ZOO_SEQUENCE = 1 << 1;
  106. #define ZOO_MAX_TTL 0xFFFFFFFFFFLL
  107. const int ZOO_EXPIRED_SESSION_STATE = EXPIRED_SESSION_STATE_DEF;
  108. const int ZOO_AUTH_FAILED_STATE = AUTH_FAILED_STATE_DEF;
  109. const int ZOO_CONNECTING_STATE = CONNECTING_STATE_DEF;
  110. const int ZOO_ASSOCIATING_STATE = ASSOCIATING_STATE_DEF;
  111. const int ZOO_CONNECTED_STATE = CONNECTED_STATE_DEF;
  112. const int ZOO_READONLY_STATE = READONLY_STATE_DEF;
  113. const int ZOO_SSL_CONNECTING_STATE = SSL_CONNECTING_STATE_DEF;
  114. const int ZOO_NOTCONNECTED_STATE = NOTCONNECTED_STATE_DEF;
  115. static __attribute__ ((unused)) const char* state2String(int state){
  116. switch(state){
  117. case 0:
  118. return "ZOO_CLOSED_STATE";
  119. case CONNECTING_STATE_DEF:
  120. return "ZOO_CONNECTING_STATE";
  121. case SSL_CONNECTING_STATE_DEF:
  122. return "ZOO_SSL_CONNECTING_STATE";
  123. case ASSOCIATING_STATE_DEF:
  124. return "ZOO_ASSOCIATING_STATE";
  125. case CONNECTED_STATE_DEF:
  126. return "ZOO_CONNECTED_STATE";
  127. case READONLY_STATE_DEF:
  128. return "ZOO_READONLY_STATE";
  129. case EXPIRED_SESSION_STATE_DEF:
  130. return "ZOO_EXPIRED_SESSION_STATE";
  131. case AUTH_FAILED_STATE_DEF:
  132. return "ZOO_AUTH_FAILED_STATE";
  133. }
  134. return "INVALID_STATE";
  135. }
  136. const int ZOO_CREATED_EVENT = CREATED_EVENT_DEF;
  137. const int ZOO_DELETED_EVENT = DELETED_EVENT_DEF;
  138. const int ZOO_CHANGED_EVENT = CHANGED_EVENT_DEF;
  139. const int ZOO_CHILD_EVENT = CHILD_EVENT_DEF;
  140. const int ZOO_SESSION_EVENT = SESSION_EVENT_DEF;
  141. const int ZOO_NOTWATCHING_EVENT = NOTWATCHING_EVENT_DEF;
  142. static __attribute__ ((unused)) const char* watcherEvent2String(int ev){
  143. switch(ev){
  144. case 0:
  145. return "ZOO_ERROR_EVENT";
  146. case CREATED_EVENT_DEF:
  147. return "ZOO_CREATED_EVENT";
  148. case DELETED_EVENT_DEF:
  149. return "ZOO_DELETED_EVENT";
  150. case CHANGED_EVENT_DEF:
  151. return "ZOO_CHANGED_EVENT";
  152. case CHILD_EVENT_DEF:
  153. return "ZOO_CHILD_EVENT";
  154. case SESSION_EVENT_DEF:
  155. return "ZOO_SESSION_EVENT";
  156. case NOTWATCHING_EVENT_DEF:
  157. return "ZOO_NOTWATCHING_EVENT";
  158. }
  159. return "INVALID_EVENT";
  160. }
  161. const int ZOO_PERM_READ = 1 << 0;
  162. const int ZOO_PERM_WRITE = 1 << 1;
  163. const int ZOO_PERM_CREATE = 1 << 2;
  164. const int ZOO_PERM_DELETE = 1 << 3;
  165. const int ZOO_PERM_ADMIN = 1 << 4;
  166. const int ZOO_PERM_ALL = 0x1f;
  167. struct Id ZOO_ANYONE_ID_UNSAFE = {"world", "anyone"};
  168. struct Id ZOO_AUTH_IDS = {"auth", ""};
  169. static struct ACL _OPEN_ACL_UNSAFE_ACL[] = {{0x1f, {"world", "anyone"}}};
  170. static struct ACL _READ_ACL_UNSAFE_ACL[] = {{0x01, {"world", "anyone"}}};
  171. static struct ACL _CREATOR_ALL_ACL_ACL[] = {{0x1f, {"auth", ""}}};
  172. struct ACL_vector ZOO_OPEN_ACL_UNSAFE = { 1, _OPEN_ACL_UNSAFE_ACL};
  173. struct ACL_vector ZOO_READ_ACL_UNSAFE = { 1, _READ_ACL_UNSAFE_ACL};
  174. struct ACL_vector ZOO_CREATOR_ALL_ACL = { 1, _CREATOR_ALL_ACL_ACL};
  175. #define COMPLETION_WATCH -1
  176. #define COMPLETION_VOID 0
  177. #define COMPLETION_STAT 1
  178. #define COMPLETION_DATA 2
  179. #define COMPLETION_STRINGLIST 3
  180. #define COMPLETION_STRINGLIST_STAT 4
  181. #define COMPLETION_ACLLIST 5
  182. #define COMPLETION_STRING 6
  183. #define COMPLETION_MULTI 7
  184. #define COMPLETION_STRING_STAT 8
  185. typedef struct _auth_completion_list {
  186. void_completion_t completion;
  187. const char *auth_data;
  188. struct _auth_completion_list *next;
  189. } auth_completion_list_t;
  190. typedef struct completion {
  191. int type; /* one of COMPLETION_* values above */
  192. union {
  193. void_completion_t void_result;
  194. stat_completion_t stat_result;
  195. data_completion_t data_result;
  196. strings_completion_t strings_result;
  197. strings_stat_completion_t strings_stat_result;
  198. acl_completion_t acl_result;
  199. string_completion_t string_result;
  200. string_stat_completion_t string_stat_result;
  201. struct watcher_object_list *watcher_result;
  202. };
  203. completion_head_t clist; /* For multi-op */
  204. } completion_t;
  205. typedef struct _completion_list {
  206. int xid;
  207. completion_t c;
  208. const void *data;
  209. buffer_list_t *buffer;
  210. struct _completion_list *next;
  211. watcher_registration_t* watcher;
  212. watcher_deregistration_t* watcher_deregistration;
  213. } completion_list_t;
  214. const char*err2string(int err);
  215. static inline int calculate_interval(const struct timeval *start,
  216. const struct timeval *end);
  217. static int queue_session_event(zhandle_t *zh, int state);
  218. static const char* format_endpoint_info(const struct sockaddr_storage* ep);
  219. /* deserialize forward declarations */
  220. static void deserialize_response(zhandle_t *zh, int type, int xid, int failed, int rc, completion_list_t *cptr, struct iarchive *ia);
  221. static int deserialize_multi(zhandle_t *zh, int xid, completion_list_t *cptr, struct iarchive *ia);
  222. /* completion routine forward declarations */
  223. static int add_completion(zhandle_t *zh, int xid, int completion_type,
  224. const void *dc, const void *data, int add_to_front,
  225. watcher_registration_t* wo, completion_head_t *clist);
  226. static int add_completion_deregistration(zhandle_t *zh, int xid,
  227. int completion_type, const void *dc, const void *data,
  228. int add_to_front, watcher_deregistration_t* wo,
  229. completion_head_t *clist);
  230. static int do_add_completion(zhandle_t *zh, const void *dc, completion_list_t *c,
  231. int add_to_front);
  232. static completion_list_t* create_completion_entry(zhandle_t *zh, int xid, int completion_type,
  233. const void *dc, const void *data, watcher_registration_t* wo,
  234. completion_head_t *clist);
  235. static completion_list_t* create_completion_entry_deregistration(zhandle_t *zh,
  236. int xid, int completion_type, const void *dc, const void *data,
  237. watcher_deregistration_t* wo, completion_head_t *clist);
  238. static completion_list_t* do_create_completion_entry(zhandle_t *zh,
  239. int xid, int completion_type, const void *dc, const void *data,
  240. watcher_registration_t* wo, completion_head_t *clist,
  241. watcher_deregistration_t* wdo);
  242. static void destroy_completion_entry(completion_list_t* c);
  243. static void queue_completion_nolock(completion_head_t *list, completion_list_t *c,
  244. int add_to_front);
  245. static void queue_completion(completion_head_t *list, completion_list_t *c,
  246. int add_to_front);
  247. static int handle_socket_error_msg(zhandle_t *zh, int line, int rc,
  248. const char* format,...);
  249. static void cleanup_bufs(zhandle_t *zh,int callCompletion,int rc);
  250. static int disable_conn_permute=0; // permute enabled by default
  251. static struct sockaddr_storage *addr_rw_server = 0;
  252. static void *SYNCHRONOUS_MARKER = (void*)&SYNCHRONOUS_MARKER;
  253. static int isValidPath(const char* path, const int mode);
  254. #ifdef HAVE_OPENSSL_H
  255. static int init_ssl_for_handler(zhandle_t *zh);
  256. static int init_ssl_for_socket(zsock_t *fd, zhandle_t *zh, int fail_on_error);
  257. #endif
  258. static int aremove_watches(
  259. zhandle_t *zh, const char *path, ZooWatcherType wtype,
  260. watcher_fn watcher, void *watcherCtx, int local,
  261. void_completion_t *completion, const void *data, int all);
  262. #ifdef THREADED
  263. static void process_sync_completion(zhandle_t *zh,
  264. completion_list_t *cptr,
  265. struct sync_completion *sc,
  266. struct iarchive *ia);
  267. static int remove_watches(
  268. zhandle_t *zh, const char *path, ZooWatcherType wtype,
  269. watcher_fn watcher, void *watcherCtx, int local, int all);
  270. #endif
  271. #ifdef _WIN32
  272. typedef SOCKET socket_t;
  273. typedef int sendsize_t;
  274. #define SEND_FLAGS 0
  275. #else
  276. #ifdef __APPLE__
  277. #define SEND_FLAGS SO_NOSIGPIPE
  278. #endif
  279. #ifdef __linux__
  280. #define SEND_FLAGS MSG_NOSIGNAL
  281. #endif
  282. #ifndef SEND_FLAGS
  283. #define SEND_FLAGS 0
  284. #endif
  285. typedef int socket_t;
  286. typedef ssize_t sendsize_t;
  287. #endif
  288. static void zookeeper_set_sock_nodelay(zhandle_t *, socket_t);
  289. static void zookeeper_set_sock_noblock(zhandle_t *, socket_t);
  290. static void zookeeper_set_sock_timeout(zhandle_t *, socket_t, int);
  291. static socket_t zookeeper_connect(zhandle_t *, struct sockaddr_storage *, socket_t);
  292. /*
  293. * return 1 if zh has a SASL client performing authentication, 0 otherwise.
  294. */
  295. static int is_sasl_auth_in_progress(zhandle_t* zh)
  296. {
  297. #ifdef HAVE_CYRUS_SASL_H
  298. return zh->sasl_client && zh->sasl_client->state == ZOO_SASL_INTERMEDIATE;
  299. #else /* !HAVE_CYRUS_SASL_H */
  300. return 0;
  301. #endif /* HAVE_CYRUS_SASL_H */
  302. }
  303. #ifndef THREADED
  304. /*
  305. * abort due to the use of a sync api in a singlethreaded environment
  306. */
  307. static void abort_singlethreaded(zhandle_t *zh)
  308. {
  309. LOG_ERROR(LOGCALLBACK(zh), "Sync completion used without threads");
  310. abort();
  311. }
  312. #endif /* THREADED */
  313. static ssize_t zookeeper_send(zsock_t *fd, const void* buf, size_t len)
  314. {
  315. #ifdef HAVE_OPENSSL_H
  316. if (fd->ssl_sock)
  317. return (ssize_t)SSL_write(fd->ssl_sock, buf, (int)len);
  318. #endif
  319. return send(fd->sock, buf, len, SEND_FLAGS);
  320. }
  321. static ssize_t zookeeper_recv(zsock_t *fd, void *buf, size_t len, int flags)
  322. {
  323. #ifdef HAVE_OPENSSL_H
  324. if (fd->ssl_sock)
  325. return (ssize_t)SSL_read(fd->ssl_sock, buf, (int)len);
  326. #endif
  327. return recv(fd->sock, buf, len, flags);
  328. }
  329. /**
  330. * Get the system time.
  331. *
  332. * If the monotonic clock is available, we use that. The monotonic clock does
  333. * not change when the wall-clock time is adjusted by NTP or the system
  334. * administrator. The monotonic clock returns a value which is monotonically
  335. * increasing.
  336. *
  337. * If POSIX monotonic clocks are not available, we fall back on the wall-clock.
  338. *
  339. * @param tv (out param) The time.
  340. */
  341. void get_system_time(struct timeval *tv)
  342. {
  343. int ret;
  344. #ifdef __MACH__ // OS X
  345. clock_serv_t cclock;
  346. mach_timespec_t mts;
  347. ret = host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
  348. if (!ret) {
  349. ret += clock_get_time(cclock, &mts);
  350. ret += mach_port_deallocate(mach_task_self(), cclock);
  351. if (!ret) {
  352. tv->tv_sec = mts.tv_sec;
  353. tv->tv_usec = mts.tv_nsec / 1000;
  354. }
  355. }
  356. if (ret) {
  357. // Default to gettimeofday in case of failure.
  358. ret = gettimeofday(tv, NULL);
  359. }
  360. #elif defined CLOCK_MONOTONIC_RAW
  361. // On Linux, CLOCK_MONOTONIC is affected by ntp slew but CLOCK_MONOTONIC_RAW
  362. // is not. We want the non-slewed (constant rate) CLOCK_MONOTONIC_RAW if it
  363. // is available.
  364. struct timespec ts = { 0 };
  365. ret = clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
  366. tv->tv_sec = ts.tv_sec;
  367. tv->tv_usec = ts.tv_nsec / 1000;
  368. #elif _POSIX_MONOTONIC_CLOCK
  369. struct timespec ts = { 0 };
  370. ret = clock_gettime(CLOCK_MONOTONIC, &ts);
  371. tv->tv_sec = ts.tv_sec;
  372. tv->tv_usec = ts.tv_nsec / 1000;
  373. #elif _WIN32
  374. LARGE_INTEGER counts, countsPerSecond, countsPerMicrosecond;
  375. if (QueryPerformanceFrequency(&countsPerSecond) &&
  376. QueryPerformanceCounter(&counts)) {
  377. countsPerMicrosecond.QuadPart = countsPerSecond.QuadPart / 1000000;
  378. tv->tv_sec = (long)(counts.QuadPart / countsPerSecond.QuadPart);
  379. tv->tv_usec = (long)((counts.QuadPart % countsPerSecond.QuadPart) /
  380. countsPerMicrosecond.QuadPart);
  381. ret = 0;
  382. } else {
  383. ret = gettimeofday(tv, NULL);
  384. }
  385. #else
  386. ret = gettimeofday(tv, NULL);
  387. #endif
  388. if (ret) {
  389. abort();
  390. }
  391. }
  392. const void *zoo_get_context(zhandle_t *zh)
  393. {
  394. return zh->context;
  395. }
  396. void zoo_set_context(zhandle_t *zh, void *context)
  397. {
  398. if (zh != NULL) {
  399. zh->context = context;
  400. }
  401. }
  402. int zoo_recv_timeout(zhandle_t *zh)
  403. {
  404. return zh->recv_timeout;
  405. }
  406. /** these functions are thread unsafe, so make sure that
  407. zoo_lock_auth is called before you access them **/
  408. static auth_info* get_last_auth(auth_list_head_t *auth_list) {
  409. auth_info *element;
  410. element = auth_list->auth;
  411. if (element == NULL) {
  412. return NULL;
  413. }
  414. while (element->next != NULL) {
  415. element = element->next;
  416. }
  417. return element;
  418. }
  419. static void free_auth_completion(auth_completion_list_t *a_list) {
  420. auth_completion_list_t *tmp, *ftmp;
  421. if (a_list == NULL) {
  422. return;
  423. }
  424. tmp = a_list->next;
  425. while (tmp != NULL) {
  426. ftmp = tmp;
  427. tmp = tmp->next;
  428. ftmp->completion = NULL;
  429. ftmp->auth_data = NULL;
  430. free(ftmp);
  431. }
  432. a_list->completion = NULL;
  433. a_list->auth_data = NULL;
  434. a_list->next = NULL;
  435. return;
  436. }
  437. static void add_auth_completion(auth_completion_list_t* a_list, void_completion_t* completion,
  438. const char *data) {
  439. auth_completion_list_t *element;
  440. auth_completion_list_t *n_element;
  441. element = a_list;
  442. if (a_list->completion == NULL) {
  443. //this is the first element
  444. a_list->completion = *completion;
  445. a_list->next = NULL;
  446. a_list->auth_data = data;
  447. return;
  448. }
  449. while (element->next != NULL) {
  450. element = element->next;
  451. }
  452. n_element = (auth_completion_list_t*) malloc(sizeof(auth_completion_list_t));
  453. n_element->next = NULL;
  454. n_element->completion = *completion;
  455. n_element->auth_data = data;
  456. element->next = n_element;
  457. return;
  458. }
  459. static void get_auth_completions(auth_list_head_t *auth_list, auth_completion_list_t *a_list) {
  460. auth_info *element;
  461. element = auth_list->auth;
  462. if (element == NULL) {
  463. return;
  464. }
  465. while (element) {
  466. if (element->completion) {
  467. add_auth_completion(a_list, &element->completion, element->data);
  468. }
  469. element->completion = NULL;
  470. element = element->next;
  471. }
  472. return;
  473. }
  474. static void add_last_auth(auth_list_head_t *auth_list, auth_info *add_el) {
  475. auth_info *element;
  476. element = auth_list->auth;
  477. if (element == NULL) {
  478. //first element in the list
  479. auth_list->auth = add_el;
  480. return;
  481. }
  482. while (element->next != NULL) {
  483. element = element->next;
  484. }
  485. element->next = add_el;
  486. return;
  487. }
  488. static void init_auth_info(auth_list_head_t *auth_list)
  489. {
  490. auth_list->auth = NULL;
  491. }
  492. static void mark_active_auth(zhandle_t *zh) {
  493. auth_list_head_t auth_h = zh->auth_h;
  494. auth_info *element;
  495. if (auth_h.auth == NULL) {
  496. return;
  497. }
  498. element = auth_h.auth;
  499. while (element != NULL) {
  500. element->state = 1;
  501. element = element->next;
  502. }
  503. }
  504. static void free_auth_info(auth_list_head_t *auth_list)
  505. {
  506. auth_info *auth = auth_list->auth;
  507. while (auth != NULL) {
  508. auth_info* old_auth = NULL;
  509. if(auth->scheme!=NULL)
  510. free(auth->scheme);
  511. deallocate_Buffer(&auth->auth);
  512. old_auth = auth;
  513. auth = auth->next;
  514. free(old_auth);
  515. }
  516. init_auth_info(auth_list);
  517. }
  518. int is_unrecoverable(zhandle_t *zh)
  519. {
  520. return (zh->state<0)? ZINVALIDSTATE: ZOK;
  521. }
  522. zk_hashtable *exists_result_checker(zhandle_t *zh, int rc)
  523. {
  524. if (rc == ZOK) {
  525. return zh->active_node_watchers;
  526. } else if (rc == ZNONODE) {
  527. return zh->active_exist_watchers;
  528. }
  529. return 0;
  530. }
  531. zk_hashtable *data_result_checker(zhandle_t *zh, int rc)
  532. {
  533. return rc==ZOK ? zh->active_node_watchers : 0;
  534. }
  535. zk_hashtable *child_result_checker(zhandle_t *zh, int rc)
  536. {
  537. return rc==ZOK ? zh->active_child_watchers : 0;
  538. }
  539. void close_zsock(zsock_t *fd)
  540. {
  541. if (fd->sock != -1) {
  542. #ifdef HAVE_OPENSSL_H
  543. if (fd->ssl_sock) {
  544. SSL_free(fd->ssl_sock);
  545. fd->ssl_sock = NULL;
  546. SSL_CTX_free(fd->ssl_ctx);
  547. fd->ssl_ctx = NULL;
  548. }
  549. #endif
  550. close(fd->sock);
  551. fd->sock = -1;
  552. }
  553. }
  554. /**
  555. * Frees and closes everything associated with a handle,
  556. * including the handle itself.
  557. */
  558. static void destroy(zhandle_t *zh)
  559. {
  560. if (zh == NULL) {
  561. return;
  562. }
  563. /* call any outstanding completions with a special error code */
  564. cleanup_bufs(zh,1,ZCLOSING);
  565. if (process_async(zh->outstanding_sync)) {
  566. process_completions(zh);
  567. }
  568. if (zh->hostname != 0) {
  569. free(zh->hostname);
  570. zh->hostname = NULL;
  571. }
  572. if (zh->fd->sock != -1) {
  573. close_zsock(zh->fd);
  574. memset(&zh->addr_cur, 0, sizeof(zh->addr_cur));
  575. zh->state = 0;
  576. }
  577. addrvec_free(&zh->addrs);
  578. if (zh->chroot != NULL) {
  579. free(zh->chroot);
  580. zh->chroot = NULL;
  581. }
  582. #ifdef HAVE_OPENSSL_H
  583. if (zh->fd->cert) {
  584. free(zh->fd->cert->certstr);
  585. free(zh->fd->cert);
  586. zh->fd->cert = NULL;
  587. }
  588. #endif
  589. free_auth_info(&zh->auth_h);
  590. destroy_zk_hashtable(zh->active_node_watchers);
  591. destroy_zk_hashtable(zh->active_exist_watchers);
  592. destroy_zk_hashtable(zh->active_child_watchers);
  593. addrvec_free(&zh->addrs_old);
  594. addrvec_free(&zh->addrs_new);
  595. #ifdef HAVE_CYRUS_SASL_H
  596. if (zh->sasl_client) {
  597. zoo_sasl_client_destroy(zh->sasl_client);
  598. zh->sasl_client = NULL;
  599. }
  600. #endif /* HAVE_CYRUS_SASL_H */
  601. }
  602. static void setup_random()
  603. {
  604. #ifndef _WIN32 // TODO: better seed
  605. int seed;
  606. int fd = open("/dev/urandom", O_RDONLY);
  607. if (fd == -1) {
  608. seed = getpid();
  609. } else {
  610. int seed_len = 0;
  611. /* Enter a loop to fill in seed with random data from /dev/urandom.
  612. * This is done in a loop so that we can safely handle short reads
  613. * which can happen due to signal interruptions.
  614. */
  615. while (seed_len < sizeof(seed)) {
  616. /* Assert we either read something or we were interrupted due to a
  617. * signal (errno == EINTR) in which case we need to retry.
  618. */
  619. int rc = read(fd, &seed + seed_len, sizeof(seed) - seed_len);
  620. assert(rc > 0 || errno == EINTR);
  621. if (rc > 0) {
  622. seed_len += rc;
  623. }
  624. }
  625. close(fd);
  626. }
  627. srandom(seed);
  628. srand48(seed);
  629. #endif
  630. }
  631. #ifndef __CYGWIN__
  632. /**
  633. * get the errno from the return code
  634. * of get addrinfo. Errno is not set
  635. * with the call to getaddrinfo, so thats
  636. * why we have to do this.
  637. */
  638. static int getaddrinfo_errno(int rc) {
  639. switch(rc) {
  640. case EAI_NONAME:
  641. // ZOOKEEPER-1323 EAI_NODATA and EAI_ADDRFAMILY are deprecated in FreeBSD.
  642. #if defined EAI_NODATA && EAI_NODATA != EAI_NONAME
  643. case EAI_NODATA:
  644. #endif
  645. return ENOENT;
  646. case EAI_MEMORY:
  647. return ENOMEM;
  648. default:
  649. return EINVAL;
  650. }
  651. }
  652. #endif
  653. /**
  654. * Count the number of hosts in the connection host string. This assumes it's
  655. * a well-formed connection string whereby each host is separated by a comma.
  656. */
  657. static int count_hosts(char *hosts)
  658. {
  659. uint32_t count = 0;
  660. char *loc = hosts;
  661. if (!hosts || strlen(hosts) == 0) {
  662. return 0;
  663. }
  664. while ((loc = strchr(loc, ','))) {
  665. count++;
  666. loc+=1;
  667. }
  668. return count+1;
  669. }
  670. /**
  671. * Resolve hosts and populate provided address vector with shuffled results.
  672. * The contents of the provided address vector will be initialized to an
  673. * empty state.
  674. */
  675. static int resolve_hosts(const zhandle_t *zh, const char *hosts_in, addrvec_t *avec)
  676. {
  677. int rc = ZOK;
  678. char *host = NULL;
  679. char *hosts = NULL;
  680. int num_hosts = 0;
  681. char *strtok_last = NULL;
  682. if (zh == NULL || hosts_in == NULL || avec == NULL) {
  683. return ZBADARGUMENTS;
  684. }
  685. // initialize address vector
  686. addrvec_init(avec);
  687. hosts = strdup(hosts_in);
  688. if (hosts == NULL) {
  689. LOG_ERROR(LOGCALLBACK(zh), "out of memory");
  690. errno=ENOMEM;
  691. rc=ZSYSTEMERROR;
  692. goto fail;
  693. }
  694. num_hosts = count_hosts(hosts);
  695. if (num_hosts == 0) {
  696. free(hosts);
  697. return ZOK;
  698. }
  699. // Allocate list inside avec
  700. rc = addrvec_alloc_capacity(avec, num_hosts);
  701. if (rc != 0) {
  702. LOG_ERROR(LOGCALLBACK(zh), "out of memory");
  703. errno=ENOMEM;
  704. rc=ZSYSTEMERROR;
  705. goto fail;
  706. }
  707. host = strtok_r(hosts, ",", &strtok_last);
  708. while(host) {
  709. char *port_spec = strrchr(host, ':');
  710. char *end_port_spec;
  711. int port;
  712. if (!port_spec) {
  713. LOG_ERROR(LOGCALLBACK(zh), "no port in %s", host);
  714. errno=EINVAL;
  715. rc=ZBADARGUMENTS;
  716. goto fail;
  717. }
  718. *port_spec = '\0';
  719. port_spec++;
  720. port = strtol(port_spec, &end_port_spec, 0);
  721. if (!*port_spec || *end_port_spec || port == 0) {
  722. LOG_ERROR(LOGCALLBACK(zh), "invalid port in %s", host);
  723. errno=EINVAL;
  724. rc=ZBADARGUMENTS;
  725. goto fail;
  726. }
  727. #if defined(__CYGWIN__)
  728. // sadly CYGWIN doesn't have getaddrinfo
  729. // but happily gethostbyname is threadsafe in windows
  730. {
  731. struct hostent *he;
  732. char **ptr;
  733. struct sockaddr_in *addr4;
  734. he = gethostbyname(host);
  735. if (!he) {
  736. LOG_ERROR(LOGCALLBACK(zh), "could not resolve %s", host);
  737. errno=ENOENT;
  738. rc=ZBADARGUMENTS;
  739. goto fail;
  740. }
  741. // Setup the address array
  742. for(ptr = he->h_addr_list;*ptr != 0; ptr++) {
  743. if (addrs->count == addrs->capacity) {
  744. rc = addrvec_grow_default(addrs);
  745. if (rc != 0) {
  746. LOG_ERROR(LOGCALLBACK(zh), "out of memory");
  747. errno=ENOMEM;
  748. rc=ZSYSTEMERROR;
  749. goto fail;
  750. }
  751. }
  752. addr = &addrs->list[addrs->count];
  753. addr4 = (struct sockaddr_in*)addr;
  754. addr->ss_family = he->h_addrtype;
  755. if (addr->ss_family == AF_INET) {
  756. addr4->sin_port = htons(port);
  757. memset(&addr4->sin_zero, 0, sizeof(addr4->sin_zero));
  758. memcpy(&addr4->sin_addr, *ptr, he->h_length);
  759. zh->addrs.count++;
  760. }
  761. #if defined(AF_INET6)
  762. else if (addr->ss_family == AF_INET6) {
  763. struct sockaddr_in6 *addr6;
  764. addr6 = (struct sockaddr_in6*)addr;
  765. addr6->sin6_port = htons(port);
  766. addr6->sin6_scope_id = 0;
  767. addr6->sin6_flowinfo = 0;
  768. memcpy(&addr6->sin6_addr, *ptr, he->h_length);
  769. zh->addrs.count++;
  770. }
  771. #endif
  772. else {
  773. LOG_WARN(LOGCALLBACK(zh), "skipping unknown address family %x for %s",
  774. addr->ss_family, hosts_in);
  775. }
  776. }
  777. host = strtok_r(0, ",", &strtok_last);
  778. }
  779. #else
  780. {
  781. struct addrinfo hints, *res, *res0;
  782. memset(&hints, 0, sizeof(hints));
  783. #ifdef AI_ADDRCONFIG
  784. hints.ai_flags = AI_ADDRCONFIG;
  785. #else
  786. hints.ai_flags = 0;
  787. #endif
  788. hints.ai_family = AF_UNSPEC;
  789. hints.ai_socktype = SOCK_STREAM;
  790. hints.ai_protocol = IPPROTO_TCP;
  791. while(isspace(*host) && host != strtok_last)
  792. host++;
  793. if ((rc = getaddrinfo(host, port_spec, &hints, &res0)) != 0) {
  794. //bug in getaddrinfo implementation when it returns
  795. //EAI_BADFLAGS or EAI_ADDRFAMILY with AF_UNSPEC and
  796. // ai_flags as AI_ADDRCONFIG
  797. #ifdef AI_ADDRCONFIG
  798. if ((hints.ai_flags == AI_ADDRCONFIG) &&
  799. // ZOOKEEPER-1323 EAI_NODATA and EAI_ADDRFAMILY are deprecated in FreeBSD.
  800. #ifdef EAI_ADDRFAMILY
  801. ((rc ==EAI_BADFLAGS) || (rc == EAI_ADDRFAMILY))) {
  802. #else
  803. (rc == EAI_BADFLAGS)) {
  804. #endif
  805. //reset ai_flags to null
  806. hints.ai_flags = 0;
  807. //retry getaddrinfo
  808. rc = getaddrinfo(host, port_spec, &hints, &res0);
  809. }
  810. #endif
  811. if (rc != 0) {
  812. errno = getaddrinfo_errno(rc);
  813. #ifdef _WIN32
  814. LOG_ERROR(LOGCALLBACK(zh), "Win32 message: %s\n", gai_strerror(rc));
  815. #elif __linux__ && __GNUC__
  816. LOG_ERROR(LOGCALLBACK(zh), "getaddrinfo: %s\n", gai_strerror(rc));
  817. #else
  818. LOG_ERROR(LOGCALLBACK(zh), "getaddrinfo: %s\n", strerror(errno));
  819. #endif
  820. rc=ZSYSTEMERROR;
  821. goto next;
  822. }
  823. }
  824. for (res = res0; res; res = res->ai_next) {
  825. // Expand address list if needed
  826. if (avec->count == avec->capacity) {
  827. rc = addrvec_grow_default(avec);
  828. if (rc != 0) {
  829. LOG_ERROR(LOGCALLBACK(zh), "out of memory");
  830. errno=ENOMEM;
  831. rc=ZSYSTEMERROR;
  832. goto fail;
  833. }
  834. }
  835. // Copy addrinfo into address list
  836. switch (res->ai_family) {
  837. case AF_INET:
  838. #if defined(AF_INET6)
  839. case AF_INET6:
  840. #endif
  841. addrvec_append_addrinfo(avec, res);
  842. break;
  843. default:
  844. LOG_WARN(LOGCALLBACK(zh), "skipping unknown address family %x for %s",
  845. res->ai_family, hosts_in);
  846. break;
  847. }
  848. }
  849. freeaddrinfo(res0);
  850. next:
  851. host = strtok_r(0, ",", &strtok_last);
  852. }
  853. #endif
  854. }
  855. if (avec->count == 0) {
  856. rc = ZSYSTEMERROR; // not a single host resolved
  857. goto fail;
  858. }
  859. free(hosts);
  860. if(!disable_conn_permute){
  861. setup_random();
  862. addrvec_shuffle(avec);
  863. }
  864. return ZOK;
  865. fail:
  866. addrvec_free(avec);
  867. if (hosts) {
  868. free(hosts);
  869. hosts = NULL;
  870. }
  871. return rc;
  872. }
  873. /**
  874. * Updates the list of servers and determine if changing connections is necessary.
  875. * Permutes server list for proper load balancing.
  876. *
  877. * Changing connections is necessary if one of the following holds:
  878. * a) the server this client is currently connected is not in new address list.
  879. * Otherwise (if currentHost is in the new list):
  880. * b) the number of servers in the cluster is increasing - in this case the load
  881. * on currentHost should decrease, which means that SOME of the clients
  882. * connected to it will migrate to the new servers. The decision whether this
  883. * client migrates or not is probabilistic so that the expected number of
  884. * clients connected to each server is the same.
  885. *
  886. * If reconfig is set to true, the function sets pOld and pNew that correspond
  887. * to the probability to migrate to ones of the new servers or one of the old
  888. * servers (migrating to one of the old servers is done only if our client's
  889. * currentHost is not in new list).
  890. *
  891. * See zoo_cycle_next_server for the selection logic.
  892. *
  893. * \param ref_time an optional "reference time," used to determine if
  894. * resolution can be skipped in accordance to the delay set by \ref
  895. * zoo_set_servers_resolution_delay. Passing NULL prevents skipping.
  896. *
  897. * See {@link https://issues.apache.org/jira/browse/ZOOKEEPER-1355} for the
  898. * protocol and its evaluation,
  899. */
  900. int update_addrs(zhandle_t *zh, const struct timeval *ref_time)
  901. {
  902. int rc = ZOK;
  903. char *hosts = NULL;
  904. uint32_t num_old = 0;
  905. uint32_t num_new = 0;
  906. uint32_t i = 0;
  907. int found_current = 0;
  908. addrvec_t resolved = { 0 };
  909. // Verify we have a valid handle
  910. if (zh == NULL) {
  911. return ZBADARGUMENTS;
  912. }
  913. // zh->hostname should always be set
  914. if (zh->hostname == NULL)
  915. {
  916. return ZSYSTEMERROR;
  917. }
  918. // NOTE: guard access to {hostname, addr_cur, addrs, addrs_old, addrs_new, last_resolve, resolve_delay_ms}
  919. lock_reconfig(zh);
  920. // Check if we are due for a host name resolution. (See
  921. // zoo_set_servers_resolution_delay. The answer is always "yes"
  922. // if no reference is provided or the file descriptor is invalid.)
  923. if (ref_time && zh->fd->sock != -1) {
  924. int do_resolve;
  925. if (zh->resolve_delay_ms <= 0) {
  926. // -1 disables, 0 means unconditional. Fail safe.
  927. do_resolve = zh->resolve_delay_ms != -1;
  928. } else {
  929. int elapsed_ms = calculate_interval(&zh->last_resolve, ref_time);
  930. // Include < 0 in case of overflow, or if we are not
  931. // backed by a monotonic clock.
  932. do_resolve = elapsed_ms > zh->resolve_delay_ms || elapsed_ms < 0;
  933. }
  934. if (!do_resolve) {
  935. goto finish;
  936. }
  937. }
  938. // Copy zh->hostname for local use
  939. hosts = strdup(zh->hostname);
  940. if (hosts == NULL) {
  941. rc = ZSYSTEMERROR;
  942. goto finish;
  943. }
  944. rc = resolve_hosts(zh, hosts, &resolved);
  945. if (rc != ZOK)
  946. {
  947. goto finish;
  948. }
  949. // Unconditionally note last resolution time.
  950. if (ref_time) {
  951. zh->last_resolve = *ref_time;
  952. } else {
  953. get_system_time(&zh->last_resolve);
  954. }
  955. // If the addrvec list is identical to last time we ran don't do anything
  956. if (addrvec_eq(&zh->addrs, &resolved))
  957. {
  958. goto finish;
  959. }
  960. // Is the server we're connected to in the new resolved list?
  961. found_current = addrvec_contains(&resolved, &zh->addr_cur);
  962. // Clear out old and new address lists
  963. zh->reconfig = 1;
  964. addrvec_free(&zh->addrs_old);
  965. addrvec_free(&zh->addrs_new);
  966. // Divide server list into addrs_old if in previous list and addrs_new if not
  967. for (i = 0; i < resolved.count; i++)
  968. {
  969. struct sockaddr_storage *resolved_address = &resolved.data[i];
  970. if (addrvec_contains(&zh->addrs, resolved_address))
  971. {
  972. rc = addrvec_append(&zh->addrs_old, resolved_address);
  973. if (rc != ZOK)
  974. {
  975. goto finish;
  976. }
  977. }
  978. else {
  979. rc = addrvec_append(&zh->addrs_new, resolved_address);
  980. if (rc != ZOK)
  981. {
  982. goto finish;
  983. }
  984. }
  985. }
  986. num_old = zh->addrs_old.count;
  987. num_new = zh->addrs_new.count;
  988. // Number of servers increased
  989. if (num_old + num_new > zh->addrs.count)
  990. {
  991. if (found_current) {
  992. // my server is in the new config, but load should be decreased.
  993. // Need to decide if the client is moving to one of the new servers
  994. if (drand48() <= (1 - ((double)zh->addrs.count) / (num_old + num_new))) {
  995. zh->pNew = 1;
  996. zh->pOld = 0;
  997. } else {
  998. // do nothing special -- stay with the current server
  999. zh->reconfig = 0;
  1000. }
  1001. } else {
  1002. // my server is not in the new config, and load on old servers must
  1003. // be decreased, so connect to one of the new servers
  1004. zh->pNew = 1;
  1005. zh->pOld = 0;
  1006. }
  1007. }
  1008. // Number of servers stayed the same or decreased
  1009. else {
  1010. if (found_current) {
  1011. // my server is in the new config, and load should be increased, so
  1012. // stay with this server and do nothing special
  1013. zh->reconfig = 0;
  1014. } else {
  1015. zh->pOld = ((double) (num_old * (zh->addrs.count - (num_old + num_new)))) / ((num_old + num_new) * (zh->addrs.count - num_old));
  1016. zh->pNew = 1 - zh->pOld;
  1017. }
  1018. }
  1019. addrvec_free(&zh->addrs);
  1020. zh->addrs = resolved;
  1021. // If we need to do a reconfig and we're currently connected to a server,
  1022. // then force close that connection so on next interest() call we'll make a
  1023. // new connection
  1024. if (zh->reconfig == 1 && zh->fd->sock != -1)
  1025. {
  1026. close_zsock(zh->fd);
  1027. zh->state = ZOO_NOTCONNECTED_STATE;
  1028. }
  1029. finish:
  1030. unlock_reconfig(zh);
  1031. // If we short-circuited out and never assigned resolved to zh->addrs then we
  1032. // need to free resolved to avoid a memleak.
  1033. if (resolved.data && zh->addrs.data != resolved.data)
  1034. {
  1035. addrvec_free(&resolved);
  1036. }
  1037. if (hosts) {
  1038. free(hosts);
  1039. hosts = NULL;
  1040. }
  1041. return rc;
  1042. }
  1043. const clientid_t *zoo_client_id(zhandle_t *zh)
  1044. {
  1045. return &zh->client_id;
  1046. }
  1047. static void null_watcher_fn(zhandle_t* p1, int p2, int p3,const char* p4,void*p5){}
  1048. watcher_fn zoo_set_watcher(zhandle_t *zh,watcher_fn newFn)
  1049. {
  1050. watcher_fn oldWatcher=zh->watcher;
  1051. if (newFn) {
  1052. zh->watcher = newFn;
  1053. } else {
  1054. zh->watcher = null_watcher_fn;
  1055. }
  1056. return oldWatcher;
  1057. }
  1058. struct sockaddr* zookeeper_get_connected_host(zhandle_t *zh,
  1059. struct sockaddr *addr, socklen_t *addr_len)
  1060. {
  1061. if (zh->state!=ZOO_CONNECTED_STATE) {
  1062. return NULL;
  1063. }
  1064. if (getpeername(zh->fd->sock, addr, addr_len)==-1) {
  1065. return NULL;
  1066. }
  1067. return addr;
  1068. }
  1069. static void log_env(zhandle_t *zh) {
  1070. char buf[2048];
  1071. #ifdef HAVE_SYS_UTSNAME_H
  1072. struct utsname utsname;
  1073. #endif
  1074. #if defined(HAVE_GETUID) && defined(HAVE_GETPWUID_R)
  1075. struct passwd pw;
  1076. struct passwd *pwp = NULL;
  1077. uid_t uid = 0;
  1078. #endif
  1079. LOG_INFO(LOGCALLBACK(zh), "Client environment:zookeeper.version=%s", PACKAGE_STRING);
  1080. #ifdef HAVE_GETHOSTNAME
  1081. gethostname(buf, sizeof(buf));
  1082. LOG_INFO(LOGCALLBACK(zh), "Client environment:host.name=%s", buf);
  1083. #else
  1084. LOG_INFO(LOGCALLBACK(zh), "Client environment:host.name=<not implemented>");
  1085. #endif
  1086. #ifdef HAVE_SYS_UTSNAME_H
  1087. uname(&utsname);
  1088. LOG_INFO(LOGCALLBACK(zh), "Client environment:os.name=%s", utsname.sysname);
  1089. LOG_INFO(LOGCALLBACK(zh), "Client environment:os.arch=%s", utsname.release);
  1090. LOG_INFO(LOGCALLBACK(zh), "Client environment:os.version=%s", utsname.version);
  1091. #else
  1092. LOG_INFO(LOGCALLBACK(zh), "Client environment:os.name=<not implemented>");
  1093. LOG_INFO(LOGCALLBACK(zh), "Client environment:os.arch=<not implemented>");
  1094. LOG_INFO(LOGCALLBACK(zh), "Client environment:os.version=<not implemented>");
  1095. #endif
  1096. #ifdef HAVE_GETLOGIN
  1097. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.name=%s", getlogin());
  1098. #else
  1099. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.name=<not implemented>");
  1100. #endif
  1101. #if defined(HAVE_GETUID) && defined(HAVE_GETPWUID_R)
  1102. uid = getuid();
  1103. if (!getpwuid_r(uid, &pw, buf, sizeof(buf), &pwp) && pwp) {
  1104. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.home=%s", pw.pw_dir);
  1105. } else {
  1106. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.home=<NA>");
  1107. }
  1108. #else
  1109. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.home=<not implemented>");
  1110. #endif
  1111. #ifdef HAVE_GETCWD
  1112. if (!getcwd(buf, sizeof(buf))) {
  1113. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.dir=<toolong>");
  1114. } else {
  1115. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.dir=%s", buf);
  1116. }
  1117. #else
  1118. LOG_INFO(LOGCALLBACK(zh), "Client environment:user.dir=<not implemented>");
  1119. #endif
  1120. }
  1121. /**
  1122. * Create a zookeeper handle associated with the given host and port.
  1123. */
  1124. static zhandle_t *zookeeper_init_internal(const char *host, watcher_fn watcher,
  1125. int recv_timeout, const clientid_t *clientid, void *context, int flags,
  1126. log_callback_fn log_callback, zcert_t *cert, void *sasl_params)
  1127. {
  1128. int errnosave = 0;
  1129. zhandle_t *zh = NULL;
  1130. char *index_chroot = NULL;
  1131. // Create our handle
  1132. zh = calloc(1, sizeof(*zh));
  1133. if (!zh) {
  1134. return 0;
  1135. }
  1136. // Set log callback before calling into log_env
  1137. zh->log_callback = log_callback;
  1138. if (!(flags & ZOO_NO_LOG_CLIENTENV)) {
  1139. log_env(zh);
  1140. }
  1141. zh->fd = calloc(1, sizeof(zsock_t));
  1142. zh->fd->sock = -1;
  1143. if (cert) {
  1144. zh->fd->cert = calloc(1, sizeof(zcert_t));
  1145. memcpy(zh->fd->cert, cert, sizeof(zcert_t));
  1146. }
  1147. #ifdef _WIN32
  1148. if (Win32WSAStartup()){
  1149. LOG_ERROR(LOGCALLBACK(zh), "Error initializing ws2_32.dll");
  1150. return 0;
  1151. }
  1152. #endif
  1153. LOG_INFO(LOGCALLBACK(zh), "Initiating client connection, host=%s sessionTimeout=%d watcher=%p"
  1154. " sessionId=%#llx sessionPasswd=%s context=%p flags=%d",
  1155. host,
  1156. recv_timeout,
  1157. watcher,
  1158. (clientid == 0 ? 0 : clientid->client_id),
  1159. ((clientid == 0) || (clientid->passwd[0] == 0) ?
  1160. "<null>" : "<hidden>"),
  1161. context,
  1162. flags);
  1163. zh->hostname = NULL;
  1164. zh->state = ZOO_NOTCONNECTED_STATE;
  1165. zh->context = context;
  1166. zh->recv_timeout = recv_timeout;
  1167. zh->allow_read_only = flags & ZOO_READONLY;
  1168. // non-zero clientid implies we've seen r/w server already
  1169. zh->seen_rw_server_before = (clientid != 0 && clientid->client_id != 0);
  1170. init_auth_info(&zh->auth_h);
  1171. if (watcher) {
  1172. zh->watcher = watcher;
  1173. } else {
  1174. zh->watcher = null_watcher_fn;
  1175. }
  1176. if (host == 0 || *host == 0) { // what we shouldn't dup
  1177. errno=EINVAL;
  1178. goto abort;
  1179. }
  1180. //parse the host to get the chroot if available
  1181. index_chroot = strchr(host, '/');
  1182. if (index_chroot) {
  1183. zh->chroot = strdup(index_chroot);
  1184. if (zh->chroot == NULL) {
  1185. goto abort;
  1186. }
  1187. // if chroot is just / set it to null
  1188. if (strlen(zh->chroot) == 1) {
  1189. free(zh->chroot);
  1190. zh->chroot = NULL;
  1191. }
  1192. // cannot use strndup so allocate and strcpy
  1193. zh->hostname = (char *) malloc(index_chroot - host + 1);
  1194. zh->hostname = strncpy(zh->hostname, host, (index_chroot - host));
  1195. //strncpy does not null terminate
  1196. *(zh->hostname + (index_chroot - host)) = '\0';
  1197. } else {
  1198. zh->chroot = NULL;
  1199. zh->hostname = strdup(host);
  1200. }
  1201. if (zh->chroot && !isValidPath(zh->chroot, 0)) {
  1202. errno = EINVAL;
  1203. goto abort;
  1204. }
  1205. if (zh->hostname == 0) {
  1206. goto abort;
  1207. }
  1208. if(update_addrs(zh, NULL) != 0) {
  1209. goto abort;
  1210. }
  1211. if (clientid) {
  1212. memcpy(&zh->client_id, clientid, sizeof(zh->client_id));
  1213. } else {
  1214. memset(&zh->client_id, 0, sizeof(zh->client_id));
  1215. }
  1216. zh->io_count = 0;
  1217. zh->primer_buffer.buffer = zh->primer_storage_buffer;
  1218. zh->primer_buffer.curr_offset = 0;
  1219. zh->primer_buffer.len = sizeof(zh->primer_storage_buffer);
  1220. zh->primer_buffer.next = 0;
  1221. zh->last_zxid = 0;
  1222. zh->next_deadline.tv_sec=zh->next_deadline.tv_usec=0;
  1223. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  1224. zh->active_node_watchers=create_zk_hashtable();
  1225. zh->active_exist_watchers=create_zk_hashtable();
  1226. zh->active_child_watchers=create_zk_hashtable();
  1227. zh->disable_reconnection_attempt = 0;
  1228. #ifdef HAVE_CYRUS_SASL_H
  1229. if (sasl_params) {
  1230. zh->sasl_client = zoo_sasl_client_create(
  1231. (zoo_sasl_params_t*)sasl_params);
  1232. if (!zh->sasl_client) {
  1233. goto abort;
  1234. }
  1235. }
  1236. #endif /* HAVE_CYRUS_SASL_H */
  1237. if (adaptor_init(zh) == -1) {
  1238. goto abort;
  1239. }
  1240. return zh;
  1241. abort:
  1242. errnosave=errno;
  1243. destroy(zh);
  1244. free(zh->fd);
  1245. free(zh);
  1246. errno=errnosave;
  1247. return 0;
  1248. }
  1249. zhandle_t *zookeeper_init(const char *host, watcher_fn watcher,
  1250. int recv_timeout, const clientid_t *clientid, void *context, int flags)
  1251. {
  1252. return zookeeper_init_internal(host, watcher, recv_timeout, clientid, context, flags, NULL, NULL, NULL);
  1253. }
  1254. zhandle_t *zookeeper_init2(const char *host, watcher_fn watcher,
  1255. int recv_timeout, const clientid_t *clientid, void *context, int flags,
  1256. log_callback_fn log_callback)
  1257. {
  1258. return zookeeper_init_internal(host, watcher, recv_timeout, clientid, context, flags, log_callback, NULL, NULL);
  1259. }
  1260. #ifdef HAVE_OPENSSL_H
  1261. zhandle_t *zookeeper_init_ssl(const char *host, const char *cert, watcher_fn watcher,
  1262. int recv_timeout, const clientid_t *clientid, void *context, int flags)
  1263. {
  1264. zcert_t zcert;
  1265. zcert.certstr = strdup(cert);
  1266. zcert.ca = strtok(strdup(cert), ",");
  1267. zcert.cert = strtok(NULL, ",");
  1268. zcert.key = strtok(NULL, ",");
  1269. zcert.passwd = strtok(NULL, ",");
  1270. return zookeeper_init_internal(host, watcher, recv_timeout, clientid, context, flags, NULL, &zcert, NULL);
  1271. }
  1272. #endif
  1273. #ifdef HAVE_CYRUS_SASL_H
  1274. zhandle_t *zookeeper_init_sasl(const char *host, watcher_fn watcher,
  1275. int recv_timeout, const clientid_t *clientid, void *context, int flags,
  1276. log_callback_fn log_callback, zoo_sasl_params_t *sasl_params)
  1277. {
  1278. return zookeeper_init_internal(host, watcher, recv_timeout, clientid, context, flags, log_callback, NULL, sasl_params);
  1279. }
  1280. #endif /* HAVE_CYRUS_SASL_H */
  1281. /**
  1282. * Set a new list of zk servers to connect to. Disconnect will occur if
  1283. * current connection endpoint is not in the list.
  1284. */
  1285. int zoo_set_servers(zhandle_t *zh, const char *hosts)
  1286. {
  1287. if (hosts == NULL)
  1288. {
  1289. LOG_ERROR(LOGCALLBACK(zh), "New server list cannot be empty");
  1290. return ZBADARGUMENTS;
  1291. }
  1292. // NOTE: guard access to {hostname, addr_cur, addrs, addrs_old, addrs_new, last_resolve, resolve_delay_ms}
  1293. lock_reconfig(zh);
  1294. // Reset hostname to new set of hosts to connect to
  1295. if (zh->hostname) {
  1296. free(zh->hostname);
  1297. }
  1298. zh->hostname = strdup(hosts);
  1299. unlock_reconfig(zh);
  1300. return update_addrs(zh, NULL);
  1301. }
  1302. /*
  1303. * Sets a minimum delay to observe between "routine" host name
  1304. * resolutions. See prototype for full documentation.
  1305. */
  1306. int zoo_set_servers_resolution_delay(zhandle_t *zh, int delay_ms) {
  1307. if (delay_ms < -1) {
  1308. LOG_ERROR(LOGCALLBACK(zh), "Resolution delay cannot be %d", delay_ms);
  1309. return ZBADARGUMENTS;
  1310. }
  1311. // NOTE: guard access to {hostname, addr_cur, addrs, addrs_old, addrs_new, last_resolve, resolve_delay_ms}
  1312. lock_reconfig(zh);
  1313. zh->resolve_delay_ms = delay_ms;
  1314. unlock_reconfig(zh);
  1315. return ZOK;
  1316. }
  1317. /**
  1318. * Get the next server to connect to, when in 'reconfig' mode, which means that
  1319. * we've updated the server list to connect to, and are now trying to find some
  1320. * server to connect to. Once we get successfully connected, 'reconfig' mode is
  1321. * set to false. Similarly, if we tried to connect to all servers in new config
  1322. * and failed, 'reconfig' mode is set to false.
  1323. *
  1324. * While in 'reconfig' mode, we should connect to a server in the new set of
  1325. * servers (addrs_new) with probability pNew and to servers in the old set of
  1326. * servers (addrs_old) with probability pOld (which is just 1-pNew). If we tried
  1327. * out all servers in either, we continue to try servers from the other set,
  1328. * regardless of pNew or pOld. If we tried all servers we give up and go back to
  1329. * the normal round robin mode
  1330. *
  1331. * When called, must be protected by lock_reconfig(zh).
  1332. */
  1333. static int get_next_server_in_reconfig(zhandle_t *zh)
  1334. {
  1335. int take_new = drand48() <= zh->pNew;
  1336. LOG_DEBUG(LOGCALLBACK(zh), "[OLD] count=%d capacity=%d next=%d hasnext=%d",
  1337. zh->addrs_old.count, zh->addrs_old.capacity, zh->addrs_old.next,
  1338. addrvec_hasnext(&zh->addrs_old));
  1339. LOG_DEBUG(LOGCALLBACK(zh), "[NEW] count=%d capacity=%d next=%d hasnext=%d",
  1340. zh->addrs_new.count, zh->addrs_new.capacity, zh->addrs_new.next,
  1341. addrvec_hasnext(&zh->addrs_new));
  1342. // Take one of the new servers if we haven't tried them all yet
  1343. // and either the probability tells us to connect to one of the new servers
  1344. // or if we already tried them all then use one of the old servers
  1345. if (addrvec_hasnext(&zh->addrs_new)
  1346. && (take_new || !addrvec_hasnext(&zh->addrs_old)))
  1347. {
  1348. addrvec_next(&zh->addrs_new, &zh->addr_cur);
  1349. LOG_DEBUG(LOGCALLBACK(zh), "Using next from NEW=%s", format_endpoint_info(&zh->addr_cur));
  1350. return 0;
  1351. }
  1352. // start taking old servers
  1353. if (addrvec_hasnext(&zh->addrs_old)) {
  1354. addrvec_next(&zh->addrs_old, &zh->addr_cur);
  1355. LOG_DEBUG(LOGCALLBACK(zh), "Using next from OLD=%s", format_endpoint_info(&zh->addr_cur));
  1356. return 0;
  1357. }
  1358. LOG_DEBUG(LOGCALLBACK(zh), "Failed to find either new or old");
  1359. memset(&zh->addr_cur, 0, sizeof(zh->addr_cur));
  1360. return 1;
  1361. }
  1362. /**
  1363. * Cycle through our server list to the correct 'next' server. The 'next' server
  1364. * to connect to depends upon whether we're in a 'reconfig' mode or not. Reconfig
  1365. * mode means we've upated the server list and are now trying to find a server
  1366. * to connect to. Once we get connected, we are no longer in the reconfig mode.
  1367. * Similarly, if we try to connect to all the servers in the new configuration
  1368. * and failed, reconfig mode is set to false.
  1369. *
  1370. * For more algorithm details, see get_next_server_in_reconfig.
  1371. */
  1372. void zoo_cycle_next_server(zhandle_t *zh)
  1373. {
  1374. // NOTE: guard access to {hostname, addr_cur, addrs, addrs_old, addrs_new, last_resolve, resolve_delay_ms}
  1375. lock_reconfig(zh);
  1376. memset(&zh->addr_cur, 0, sizeof(zh->addr_cur));
  1377. if (zh->reconfig)
  1378. {
  1379. if (get_next_server_in_reconfig(zh) == 0) {
  1380. unlock_reconfig(zh);
  1381. return;
  1382. }
  1383. // tried all new and old servers and couldn't connect
  1384. zh->reconfig = 0;
  1385. }
  1386. addrvec_next(&zh->addrs, &zh->addr_cur);
  1387. unlock_reconfig(zh);
  1388. return;
  1389. }
  1390. /**
  1391. * Get the host:port for the server we are currently connecting to or connected
  1392. * to. This is largely for testing purposes but is also generally useful for
  1393. * other client software built on top of this client.
  1394. */
  1395. const char* zoo_get_current_server(zhandle_t* zh)
  1396. {
  1397. const char *endpoint_info = NULL;
  1398. // NOTE: guard access to {hostname, addr_cur, addrs, addrs_old, addrs_new, last_resolve, resolve_delay_ms}
  1399. // Need the lock here as it is changed in update_addrs()
  1400. lock_reconfig(zh);
  1401. endpoint_info = format_endpoint_info(&zh->addr_cur);
  1402. unlock_reconfig(zh);
  1403. return endpoint_info;
  1404. }
  1405. /**
  1406. * deallocated the free_path only its beeen allocated
  1407. * and not equal to path
  1408. */
  1409. void free_duplicate_path(const char *free_path, const char* path) {
  1410. if (free_path != path) {
  1411. free((void*)free_path);
  1412. }
  1413. }
  1414. /**
  1415. prepend the chroot path if available else return the path
  1416. */
  1417. static char* prepend_string(zhandle_t *zh, const char* client_path) {
  1418. char *ret_str;
  1419. if (zh == NULL || zh->chroot == NULL)
  1420. return (char *) client_path;
  1421. // handle the chroot itself, client_path = "/"
  1422. if (strlen(client_path) == 1) {
  1423. return strdup(zh->chroot);
  1424. }
  1425. ret_str = (char *) malloc(strlen(zh->chroot) + strlen(client_path) + 1);
  1426. strcpy(ret_str, zh->chroot);
  1427. return strcat(ret_str, client_path);
  1428. }
  1429. /**
  1430. strip off the chroot string from the server path
  1431. if there is one else return the exact path
  1432. */
  1433. char* sub_string(zhandle_t *zh, const char* server_path) {
  1434. char *ret_str;
  1435. if (zh->chroot == NULL)
  1436. return (char *) server_path;
  1437. //ZOOKEEPER-1027
  1438. if (strncmp(server_path, zh->chroot, strlen(zh->chroot)) != 0) {
  1439. LOG_ERROR(LOGCALLBACK(zh), "server path %s does not include chroot path %s",
  1440. server_path, zh->chroot);
  1441. return (char *) server_path;
  1442. }
  1443. if (strlen(server_path) == strlen(zh->chroot)) {
  1444. //return "/"
  1445. ret_str = strdup("/");
  1446. return ret_str;
  1447. }
  1448. ret_str = strdup(server_path + strlen(zh->chroot));
  1449. return ret_str;
  1450. }
  1451. static buffer_list_t *allocate_buffer(char *buff, int len)
  1452. {
  1453. buffer_list_t *buffer = calloc(1, sizeof(*buffer));
  1454. if (buffer == 0)
  1455. return 0;
  1456. buffer->len = len==0?sizeof(*buffer):len;
  1457. buffer->curr_offset = 0;
  1458. buffer->buffer = buff;
  1459. buffer->next = 0;
  1460. return buffer;
  1461. }
  1462. static void free_buffer(buffer_list_t *b)
  1463. {
  1464. if (!b) {
  1465. return;
  1466. }
  1467. if (b->buffer) {
  1468. free(b->buffer);
  1469. }
  1470. free(b);
  1471. }
  1472. static buffer_list_t *dequeue_buffer(buffer_head_t *list)
  1473. {
  1474. buffer_list_t *b;
  1475. lock_buffer_list(list);
  1476. b = list->head;
  1477. if (b) {
  1478. list->head = b->next;
  1479. if (!list->head) {
  1480. assert(b == list->last);
  1481. list->last = 0;
  1482. }
  1483. }
  1484. unlock_buffer_list(list);
  1485. return b;
  1486. }
  1487. static int remove_buffer(buffer_head_t *list)
  1488. {
  1489. buffer_list_t *b = dequeue_buffer(list);
  1490. if (!b) {
  1491. return 0;
  1492. }
  1493. free_buffer(b);
  1494. return 1;
  1495. }
  1496. static void queue_buffer(buffer_head_t *list, buffer_list_t *b, int add_to_front)
  1497. {
  1498. b->next = 0;
  1499. lock_buffer_list(list);
  1500. if (list->head) {
  1501. assert(list->last);
  1502. // The list is not empty
  1503. if (add_to_front) {
  1504. b->next = list->head;
  1505. list->head = b;
  1506. } else {
  1507. list->last->next = b;
  1508. list->last = b;
  1509. }
  1510. }else{
  1511. // The list is empty
  1512. assert(!list->head);
  1513. list->head = b;
  1514. list->last = b;
  1515. }
  1516. unlock_buffer_list(list);
  1517. }
  1518. static int queue_buffer_bytes(buffer_head_t *list, char *buff, int len)
  1519. {
  1520. buffer_list_t *b = allocate_buffer(buff,len);
  1521. if (!b)
  1522. return ZSYSTEMERROR;
  1523. queue_buffer(list, b, 0);
  1524. return ZOK;
  1525. }
  1526. static int queue_front_buffer_bytes(buffer_head_t *list, char *buff, int len)
  1527. {
  1528. buffer_list_t *b = allocate_buffer(buff,len);
  1529. if (!b)
  1530. return ZSYSTEMERROR;
  1531. queue_buffer(list, b, 1);
  1532. return ZOK;
  1533. }
  1534. static __attribute__ ((unused)) int get_queue_len(buffer_head_t *list)
  1535. {
  1536. int i;
  1537. buffer_list_t *ptr;
  1538. lock_buffer_list(list);
  1539. ptr = list->head;
  1540. for (i=0; ptr!=0; ptr=ptr->next, i++)
  1541. ;
  1542. unlock_buffer_list(list);
  1543. return i;
  1544. }
  1545. /* returns:
  1546. * -1 if send failed,
  1547. * 0 if send would block while sending the buffer (or a send was incomplete),
  1548. * 1 if success
  1549. */
  1550. static int send_buffer(zhandle_t *zh, buffer_list_t *buff)
  1551. {
  1552. int len = buff->len;
  1553. int off = buff->curr_offset;
  1554. int rc = -1;
  1555. if (off < 4) {
  1556. /* we need to send the length at the beginning */
  1557. int nlen = htonl(len);
  1558. char *b = (char*)&nlen;
  1559. rc = zookeeper_send(zh->fd, b + off, sizeof(nlen) - off);
  1560. if (rc == -1) {
  1561. #ifdef _WIN32
  1562. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  1563. #else
  1564. if (errno != EAGAIN) {
  1565. #endif
  1566. return -1;
  1567. } else {
  1568. return 0;
  1569. }
  1570. } else {
  1571. buff->curr_offset += rc;
  1572. }
  1573. off = buff->curr_offset;
  1574. }
  1575. if (off >= 4) {
  1576. /* want off to now represent the offset into the buffer */
  1577. off -= sizeof(buff->len);
  1578. rc = zookeeper_send(zh->fd, buff->buffer + off, len - off);
  1579. if (rc == -1) {
  1580. #ifdef _WIN32
  1581. if (WSAGetLastError() != WSAEWOULDBLOCK) {
  1582. #else
  1583. if (errno != EAGAIN) {
  1584. #endif
  1585. return -1;
  1586. }
  1587. } else {
  1588. buff->curr_offset += rc;
  1589. }
  1590. }
  1591. return buff->curr_offset == len + sizeof(buff->len);
  1592. }
  1593. /* returns:
  1594. * -1 if recv call failed,
  1595. * 0 if recv would block,
  1596. * 1 if success
  1597. */
  1598. static int recv_buffer(zhandle_t *zh, buffer_list_t *buff)
  1599. {
  1600. int off = buff->curr_offset;
  1601. int rc = 0;
  1602. /* if buffer is less than 4, we are reading in the length */
  1603. if (off < 4) {
  1604. char *buffer = (char*)&(buff->len);
  1605. rc = zookeeper_recv(zh->fd, buffer+off, sizeof(int)-off, 0);
  1606. switch (rc) {
  1607. case 0:
  1608. errno = EHOSTDOWN;
  1609. case -1:
  1610. #ifdef _WIN32
  1611. if (WSAGetLastError() == WSAEWOULDBLOCK) {
  1612. #else
  1613. if (errno == EAGAIN) {
  1614. #endif
  1615. return 0;
  1616. }
  1617. return -1;
  1618. default:
  1619. buff->curr_offset += rc;
  1620. }
  1621. off = buff->curr_offset;
  1622. if (buff->curr_offset == sizeof(buff->len)) {
  1623. buff->len = ntohl(buff->len);
  1624. buff->buffer = calloc(1, buff->len);
  1625. }
  1626. }
  1627. if (buff->buffer) {
  1628. /* want off to now represent the offset into the buffer */
  1629. off -= sizeof(buff->len);
  1630. rc = zookeeper_recv(zh->fd, buff->buffer+off, buff->len-off, 0);
  1631. /* dirty hack to make new client work against old server
  1632. * old server sends 40 bytes to finish connection handshake,
  1633. * while we're expecting 41 (1 byte for read-only mode data) */
  1634. if (buff == &zh->primer_buffer && rc == buff->len - 1) ++rc;
  1635. switch(rc) {
  1636. case 0:
  1637. errno = EHOSTDOWN;
  1638. case -1:
  1639. #ifdef _WIN32
  1640. if (WSAGetLastError() == WSAEWOULDBLOCK) {
  1641. #else
  1642. if (errno == EAGAIN) {
  1643. #endif
  1644. break;
  1645. }
  1646. return -1;
  1647. default:
  1648. buff->curr_offset += rc;
  1649. }
  1650. }
  1651. return buff->curr_offset == buff->len + sizeof(buff->len);
  1652. }
  1653. void free_buffers(buffer_head_t *list)
  1654. {
  1655. while (remove_buffer(list))
  1656. ;
  1657. }
  1658. void free_completions(zhandle_t *zh,int callCompletion,int reason)
  1659. {
  1660. completion_head_t tmp_list;
  1661. struct oarchive *oa;
  1662. struct ReplyHeader h;
  1663. void_completion_t auth_completion = NULL;
  1664. auth_completion_list_t a_list, *a_tmp;
  1665. if (lock_completion_list(&zh->sent_requests) == 0) {
  1666. tmp_list = zh->sent_requests;
  1667. zh->sent_requests.head = 0;
  1668. zh->sent_requests.last = 0;
  1669. unlock_completion_list(&zh->sent_requests);
  1670. while (tmp_list.head) {
  1671. completion_list_t *cptr = tmp_list.head;
  1672. tmp_list.head = cptr->next;
  1673. if (cptr->c.data_result == SYNCHRONOUS_MARKER) {
  1674. #ifdef THREADED
  1675. struct sync_completion
  1676. *sc = (struct sync_completion*)cptr->data;
  1677. sc->rc = reason;
  1678. notify_sync_completion(sc);
  1679. zh->outstanding_sync--;
  1680. destroy_completion_entry(cptr);
  1681. #else
  1682. abort_singlethreaded(zh);
  1683. #endif
  1684. } else if (callCompletion) {
  1685. // Fake the response
  1686. buffer_list_t *bptr;
  1687. h.xid = cptr->xid;
  1688. h.zxid = -1;
  1689. h.err = reason;
  1690. oa = create_buffer_oarchive();
  1691. serialize_ReplyHeader(oa, "header", &h);
  1692. bptr = calloc(sizeof(*bptr), 1);
  1693. assert(bptr);
  1694. bptr->len = get_buffer_len(oa);
  1695. bptr->buffer = get_buffer(oa);
  1696. close_buffer_oarchive(&oa, 0);
  1697. cptr->buffer = bptr;
  1698. queue_completion(&zh->completions_to_process, cptr, 0);
  1699. }
  1700. }
  1701. }
  1702. if (zoo_lock_auth(zh) == 0) {
  1703. a_list.completion = NULL;
  1704. a_list.next = NULL;
  1705. get_auth_completions(&zh->auth_h, &a_list);
  1706. zoo_unlock_auth(zh);
  1707. a_tmp = &a_list;
  1708. // chain call user's completion function
  1709. while (a_tmp->completion != NULL) {
  1710. auth_completion = a_tmp->completion;
  1711. auth_completion(reason, a_tmp->auth_data);
  1712. a_tmp = a_tmp->next;
  1713. if (a_tmp == NULL)
  1714. break;
  1715. }
  1716. }
  1717. free_auth_completion(&a_list);
  1718. }
  1719. static void cleanup_bufs(zhandle_t *zh,int callCompletion,int rc)
  1720. {
  1721. enter_critical(zh);
  1722. free_buffers(&zh->to_send);
  1723. free_buffers(&zh->to_process);
  1724. free_completions(zh,callCompletion,rc);
  1725. leave_critical(zh);
  1726. if (zh->input_buffer && zh->input_buffer != &zh->primer_buffer) {
  1727. free_buffer(zh->input_buffer);
  1728. zh->input_buffer = 0;
  1729. }
  1730. }
  1731. /* return 1 if zh's state is ZOO_CONNECTED_STATE or ZOO_READONLY_STATE,
  1732. * 0 otherwise */
  1733. static int is_connected(zhandle_t* zh)
  1734. {
  1735. return (zh->state==ZOO_CONNECTED_STATE || zh->state==ZOO_READONLY_STATE);
  1736. }
  1737. static void cleanup(zhandle_t *zh,int rc)
  1738. {
  1739. close_zsock(zh->fd);
  1740. if (is_unrecoverable(zh)) {
  1741. LOG_DEBUG(LOGCALLBACK(zh), "Calling a watcher for a ZOO_SESSION_EVENT and the state=%s",
  1742. state2String(zh->state));
  1743. PROCESS_SESSION_EVENT(zh, zh->state);
  1744. } else if (is_connected(zh)) {
  1745. LOG_DEBUG(LOGCALLBACK(zh), "Calling a watcher for a ZOO_SESSION_EVENT and the state=CONNECTING_STATE");
  1746. PROCESS_SESSION_EVENT(zh, ZOO_CONNECTING_STATE);
  1747. }
  1748. cleanup_bufs(zh,1,rc);
  1749. LOG_DEBUG(LOGCALLBACK(zh), "Previous connection=%s delay=%d", zoo_get_current_server(zh), zh->delay);
  1750. if (!is_unrecoverable(zh)) {
  1751. zh->state = 0;
  1752. }
  1753. if (process_async(zh->outstanding_sync)) {
  1754. process_completions(zh);
  1755. }
  1756. }
  1757. static void handle_error(zhandle_t *zh,int rc)
  1758. {
  1759. cleanup(zh, rc);
  1760. // NOTE: If we're at the end of the list of addresses to connect to, then
  1761. // we want to delay the next connection attempt to avoid spinning.
  1762. // Then increment what host we'll connect to since we failed to connect to current
  1763. zh->delay = addrvec_atend(&zh->addrs);
  1764. addrvec_next(&zh->addrs, &zh->addr_cur);
  1765. }
  1766. static int handle_socket_error_msg(zhandle_t *zh, int line, int rc,
  1767. const char* format, ...)
  1768. {
  1769. if(logLevel>=ZOO_LOG_LEVEL_ERROR){
  1770. va_list va;
  1771. char buf[1024];
  1772. va_start(va,format);
  1773. vsnprintf(buf, sizeof(buf)-1,format,va);
  1774. log_message(LOGCALLBACK(zh), ZOO_LOG_LEVEL_ERROR,line,__func__,
  1775. "Socket %s zk retcode=%d, errno=%d(%s): %s",
  1776. zoo_get_current_server(zh),rc,errno,strerror(errno),buf);
  1777. va_end(va);
  1778. }
  1779. handle_error(zh,rc);
  1780. return rc;
  1781. }
  1782. static void auth_completion_func(int rc, zhandle_t* zh)
  1783. {
  1784. void_completion_t auth_completion = NULL;
  1785. auth_completion_list_t a_list;
  1786. auth_completion_list_t *a_tmp;
  1787. if(zh==NULL)
  1788. return;
  1789. zoo_lock_auth(zh);
  1790. if(rc!=0){
  1791. zh->state=ZOO_AUTH_FAILED_STATE;
  1792. }else{
  1793. //change state for all auths
  1794. mark_active_auth(zh);
  1795. }
  1796. a_list.completion = NULL;
  1797. a_list.next = NULL;
  1798. get_auth_completions(&zh->auth_h, &a_list);
  1799. zoo_unlock_auth(zh);
  1800. if (rc) {
  1801. LOG_ERROR(LOGCALLBACK(zh), "Authentication scheme %s failed. Connection closed.",
  1802. zh->auth_h.auth->scheme);
  1803. }
  1804. else {
  1805. LOG_INFO(LOGCALLBACK(zh), "Authentication scheme %s succeeded", zh->auth_h.auth->scheme);
  1806. }
  1807. a_tmp = &a_list;
  1808. // chain call user's completion function
  1809. while (a_tmp->completion != NULL) {
  1810. auth_completion = a_tmp->completion;
  1811. auth_completion(rc, a_tmp->auth_data);
  1812. a_tmp = a_tmp->next;
  1813. if (a_tmp == NULL)
  1814. break;
  1815. }
  1816. free_auth_completion(&a_list);
  1817. }
  1818. static int send_info_packet(zhandle_t *zh, auth_info* auth) {
  1819. struct oarchive *oa;
  1820. struct RequestHeader h = {AUTH_XID, ZOO_SETAUTH_OP};
  1821. struct AuthPacket req;
  1822. int rc;
  1823. oa = create_buffer_oarchive();
  1824. rc = serialize_RequestHeader(oa, "header", &h);
  1825. req.type=0; // ignored by the server
  1826. req.scheme = auth->scheme;
  1827. req.auth = auth->auth;
  1828. rc = rc < 0 ? rc : serialize_AuthPacket(oa, "req", &req);
  1829. /* add this buffer to the head of the send queue */
  1830. rc = rc < 0 ? rc : queue_front_buffer_bytes(&zh->to_send, get_buffer(oa),
  1831. get_buffer_len(oa));
  1832. /* We queued the buffer, so don't free it */
  1833. close_buffer_oarchive(&oa, 0);
  1834. return rc;
  1835. }
  1836. /** send all auths, not just the last one **/
  1837. static int send_auth_info(zhandle_t *zh) {
  1838. int rc = 0;
  1839. auth_info *auth = NULL;
  1840. zoo_lock_auth(zh);
  1841. auth = zh->auth_h.auth;
  1842. if (auth == NULL) {
  1843. zoo_unlock_auth(zh);
  1844. return ZOK;
  1845. }
  1846. while (auth != NULL) {
  1847. rc = send_info_packet(zh, auth);
  1848. auth = auth->next;
  1849. }
  1850. zoo_unlock_auth(zh);
  1851. LOG_DEBUG(LOGCALLBACK(zh), "Sending all auth info request to %s", zoo_get_current_server(zh));
  1852. return (rc <0) ? ZMARSHALLINGERROR:ZOK;
  1853. }
  1854. static int send_last_auth_info(zhandle_t *zh)
  1855. {
  1856. int rc = 0;
  1857. auth_info *auth = NULL;
  1858. zoo_lock_auth(zh);
  1859. auth = get_last_auth(&zh->auth_h);
  1860. if(auth==NULL) {
  1861. zoo_unlock_auth(zh);
  1862. return ZOK; // there is nothing to send
  1863. }
  1864. rc = send_info_packet(zh, auth);
  1865. zoo_unlock_auth(zh);
  1866. LOG_DEBUG(LOGCALLBACK(zh), "Sending auth info request to %s",zoo_get_current_server(zh));
  1867. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  1868. }
  1869. static void free_key_list(char **list, int count)
  1870. {
  1871. int i;
  1872. for(i = 0; i < count; i++) {
  1873. free(list[i]);
  1874. }
  1875. free(list);
  1876. }
  1877. static int send_set_watches(zhandle_t *zh)
  1878. {
  1879. struct oarchive *oa;
  1880. struct RequestHeader h = {SET_WATCHES_XID, ZOO_SETWATCHES_OP};
  1881. struct SetWatches req;
  1882. int rc;
  1883. req.relativeZxid = zh->last_zxid;
  1884. req.dataWatches.data = collect_keys(zh->active_node_watchers, (int*)&req.dataWatches.count);
  1885. req.existWatches.data = collect_keys(zh->active_exist_watchers, (int*)&req.existWatches.count);
  1886. req.childWatches.data = collect_keys(zh->active_child_watchers, (int*)&req.childWatches.count);
  1887. // return if there are no pending watches
  1888. if (!req.dataWatches.count && !req.existWatches.count &&
  1889. !req.childWatches.count) {
  1890. free_key_list(req.dataWatches.data, req.dataWatches.count);
  1891. free_key_list(req.existWatches.data, req.existWatches.count);
  1892. free_key_list(req.childWatches.data, req.childWatches.count);
  1893. return ZOK;
  1894. }
  1895. oa = create_buffer_oarchive();
  1896. rc = serialize_RequestHeader(oa, "header", &h);
  1897. rc = rc < 0 ? rc : serialize_SetWatches(oa, "req", &req);
  1898. /* add this buffer to the head of the send queue */
  1899. rc = rc < 0 ? rc : queue_front_buffer_bytes(&zh->to_send, get_buffer(oa),
  1900. get_buffer_len(oa));
  1901. /* We queued the buffer, so don't free it */
  1902. close_buffer_oarchive(&oa, 0);
  1903. free_key_list(req.dataWatches.data, req.dataWatches.count);
  1904. free_key_list(req.existWatches.data, req.existWatches.count);
  1905. free_key_list(req.childWatches.data, req.childWatches.count);
  1906. LOG_DEBUG(LOGCALLBACK(zh), "Sending set watches request to %s",zoo_get_current_server(zh));
  1907. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  1908. }
  1909. static int serialize_prime_connect(struct connect_req *req, char* buffer){
  1910. //this should be the order of serialization
  1911. int offset = 0;
  1912. req->protocolVersion = htonl(req->protocolVersion);
  1913. memcpy(buffer + offset, &req->protocolVersion, sizeof(req->protocolVersion));
  1914. offset = offset + sizeof(req->protocolVersion);
  1915. req->lastZxidSeen = zoo_htonll(req->lastZxidSeen);
  1916. memcpy(buffer + offset, &req->lastZxidSeen, sizeof(req->lastZxidSeen));
  1917. offset = offset + sizeof(req->lastZxidSeen);
  1918. req->timeOut = htonl(req->timeOut);
  1919. memcpy(buffer + offset, &req->timeOut, sizeof(req->timeOut));
  1920. offset = offset + sizeof(req->timeOut);
  1921. req->sessionId = zoo_htonll(req->sessionId);
  1922. memcpy(buffer + offset, &req->sessionId, sizeof(req->sessionId));
  1923. offset = offset + sizeof(req->sessionId);
  1924. req->passwd_len = htonl(req->passwd_len);
  1925. memcpy(buffer + offset, &req->passwd_len, sizeof(req->passwd_len));
  1926. offset = offset + sizeof(req->passwd_len);
  1927. memcpy(buffer + offset, req->passwd, sizeof(req->passwd));
  1928. offset = offset + sizeof(req->passwd);
  1929. memcpy(buffer + offset, &req->readOnly, sizeof(req->readOnly));
  1930. return 0;
  1931. }
  1932. static int deserialize_prime_response(struct prime_struct *resp, char* buffer)
  1933. {
  1934. //this should be the order of deserialization
  1935. int offset = 0;
  1936. memcpy(&resp->len, buffer + offset, sizeof(resp->len));
  1937. offset = offset + sizeof(resp->len);
  1938. resp->len = ntohl(resp->len);
  1939. memcpy(&resp->protocolVersion,
  1940. buffer + offset,
  1941. sizeof(resp->protocolVersion));
  1942. offset = offset + sizeof(resp->protocolVersion);
  1943. resp->protocolVersion = ntohl(resp->protocolVersion);
  1944. memcpy(&resp->timeOut, buffer + offset, sizeof(resp->timeOut));
  1945. offset = offset + sizeof(resp->timeOut);
  1946. resp->timeOut = ntohl(resp->timeOut);
  1947. memcpy(&resp->sessionId, buffer + offset, sizeof(resp->sessionId));
  1948. offset = offset + sizeof(resp->sessionId);
  1949. resp->sessionId = zoo_htonll(resp->sessionId);
  1950. memcpy(&resp->passwd_len, buffer + offset, sizeof(resp->passwd_len));
  1951. offset = offset + sizeof(resp->passwd_len);
  1952. resp->passwd_len = ntohl(resp->passwd_len);
  1953. memcpy(resp->passwd, buffer + offset, sizeof(resp->passwd));
  1954. offset = offset + sizeof(resp->passwd);
  1955. memcpy(&resp->readOnly, buffer + offset, sizeof(resp->readOnly));
  1956. return 0;
  1957. }
  1958. static int prime_connection(zhandle_t *zh)
  1959. {
  1960. int rc;
  1961. /*this is the size of buffer to serialize req into*/
  1962. char buffer_req[HANDSHAKE_REQ_SIZE];
  1963. int len = sizeof(buffer_req);
  1964. int hlen = 0;
  1965. struct connect_req req;
  1966. if (zh->state == ZOO_SSL_CONNECTING_STATE) {
  1967. // The SSL connection is yet to happen.
  1968. return ZOK;
  1969. }
  1970. req.protocolVersion = 0;
  1971. req.sessionId = zh->seen_rw_server_before ? zh->client_id.client_id : 0;
  1972. req.passwd_len = sizeof(req.passwd);
  1973. memcpy(req.passwd, zh->client_id.passwd, sizeof(zh->client_id.passwd));
  1974. req.timeOut = zh->recv_timeout;
  1975. req.lastZxidSeen = zh->last_zxid;
  1976. req.readOnly = zh->allow_read_only;
  1977. hlen = htonl(len);
  1978. /* We are running fast and loose here, but this string should fit in the initial buffer! */
  1979. rc=zookeeper_send(zh->fd, &hlen, sizeof(len));
  1980. serialize_prime_connect(&req, buffer_req);
  1981. rc=rc<0 ? rc : zookeeper_send(zh->fd, buffer_req, len);
  1982. if (rc<0) {
  1983. return handle_socket_error_msg(zh, __LINE__, ZCONNECTIONLOSS,
  1984. "failed to send a handshake packet: %s", strerror(errno));
  1985. }
  1986. zh->state = ZOO_ASSOCIATING_STATE;
  1987. zh->input_buffer = &zh->primer_buffer;
  1988. memset(zh->input_buffer->buffer, 0, zh->input_buffer->len);
  1989. /* This seems a bit weird to to set the offset to 4, but we already have a
  1990. * length, so we skip reading the length (and allocating the buffer) by
  1991. * saying that we are already at offset 4 */
  1992. zh->input_buffer->curr_offset = 4;
  1993. return ZOK;
  1994. }
  1995. static inline int calculate_interval(const struct timeval *start,
  1996. const struct timeval *end)
  1997. {
  1998. int interval;
  1999. struct timeval i = *end;
  2000. i.tv_sec -= start->tv_sec;
  2001. i.tv_usec -= start->tv_usec;
  2002. interval = i.tv_sec * 1000 + (i.tv_usec/1000);
  2003. return interval;
  2004. }
  2005. static struct timeval get_timeval(int interval)
  2006. {
  2007. struct timeval tv;
  2008. if (interval < 0) {
  2009. interval = 0;
  2010. }
  2011. tv.tv_sec = interval/1000;
  2012. tv.tv_usec = (interval%1000)*1000;
  2013. return tv;
  2014. }
  2015. static int add_void_completion(zhandle_t *zh, int xid, void_completion_t dc,
  2016. const void *data);
  2017. static int add_string_completion(zhandle_t *zh, int xid,
  2018. string_completion_t dc, const void *data);
  2019. static int add_string_stat_completion(zhandle_t *zh, int xid,
  2020. string_stat_completion_t dc, const void *data);
  2021. int send_ping(zhandle_t* zh)
  2022. {
  2023. int rc;
  2024. struct oarchive *oa = create_buffer_oarchive();
  2025. struct RequestHeader h = {PING_XID, ZOO_PING_OP};
  2026. rc = serialize_RequestHeader(oa, "header", &h);
  2027. enter_critical(zh);
  2028. get_system_time(&zh->last_ping);
  2029. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  2030. get_buffer_len(oa));
  2031. leave_critical(zh);
  2032. close_buffer_oarchive(&oa, 0);
  2033. return rc<0 ? rc : adaptor_send_queue(zh, 0);
  2034. }
  2035. /* upper bound of a timeout for seeking for r/w server when in read-only mode */
  2036. const int MAX_RW_TIMEOUT = 60000;
  2037. const int MIN_RW_TIMEOUT = 200;
  2038. static int ping_rw_server(zhandle_t* zh)
  2039. {
  2040. char buf[10];
  2041. zsock_t fd;
  2042. int rc;
  2043. sendsize_t ssize;
  2044. int sock_flags;
  2045. addrvec_peek(&zh->addrs, &zh->addr_rw_server);
  2046. #ifdef SOCK_CLOEXEC_ENABLED
  2047. sock_flags = SOCK_STREAM | SOCK_CLOEXEC;
  2048. #else
  2049. sock_flags = SOCK_STREAM;
  2050. #endif
  2051. fd.sock = socket(zh->addr_rw_server.ss_family, sock_flags, 0);
  2052. if (fd.sock < 0) {
  2053. return 0;
  2054. }
  2055. zookeeper_set_sock_nodelay(zh, fd.sock);
  2056. zookeeper_set_sock_timeout(zh, fd.sock, 1);
  2057. rc = zookeeper_connect(zh, &zh->addr_rw_server, fd.sock);
  2058. if (rc < 0) {
  2059. return 0;
  2060. }
  2061. #ifdef HAVE_OPENSSL_H
  2062. fd.ssl_sock = NULL;
  2063. fd.ssl_ctx = NULL;
  2064. if (zh->fd->cert != NULL) {
  2065. fd.cert = zh->fd->cert;
  2066. rc = init_ssl_for_socket(&fd, zh, 0);
  2067. if (rc != ZOK) {
  2068. rc = 0;
  2069. goto out;
  2070. }
  2071. }
  2072. #endif
  2073. ssize = zookeeper_send(&fd, "isro", 4);
  2074. if (ssize < 0) {
  2075. rc = 0;
  2076. goto out;
  2077. }
  2078. memset(buf, 0, sizeof(buf));
  2079. rc = zookeeper_recv(&fd, buf, sizeof(buf), 0);
  2080. if (rc < 0) {
  2081. rc = 0;
  2082. goto out;
  2083. }
  2084. rc = strcmp("rw", buf) == 0;
  2085. out:
  2086. close_zsock(&fd);
  2087. addr_rw_server = rc ? &zh->addr_rw_server : 0;
  2088. return rc;
  2089. }
  2090. #if !defined(WIN32) && !defined(min)
  2091. static inline int min(int a, int b)
  2092. {
  2093. return a < b ? a : b;
  2094. }
  2095. #endif
  2096. static void zookeeper_set_sock_noblock(zhandle_t *zh, socket_t sock)
  2097. {
  2098. #ifdef _WIN32
  2099. ULONG nonblocking_flag = 1;
  2100. ioctlsocket(sock, FIONBIO, &nonblocking_flag);
  2101. #else
  2102. fcntl(sock, F_SETFL, O_NONBLOCK|fcntl(sock, F_GETFL, 0));
  2103. #endif
  2104. }
  2105. static void zookeeper_set_sock_timeout(zhandle_t *zh, socket_t s, int timeout)
  2106. {
  2107. struct timeval tv;
  2108. tv.tv_sec = timeout;
  2109. setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval));
  2110. setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval));
  2111. }
  2112. static void zookeeper_set_sock_nodelay(zhandle_t *zh, socket_t sock)
  2113. {
  2114. #ifdef _WIN32
  2115. char enable_tcp_nodelay = 1;
  2116. #else
  2117. int enable_tcp_nodelay = 1;
  2118. #endif
  2119. int rc;
  2120. rc = setsockopt(sock,
  2121. IPPROTO_TCP,
  2122. TCP_NODELAY,
  2123. &enable_tcp_nodelay,
  2124. sizeof(enable_tcp_nodelay));
  2125. if (rc) {
  2126. LOG_WARN(LOGCALLBACK(zh),
  2127. "Unable to set TCP_NODELAY, latency may be effected");
  2128. }
  2129. }
  2130. static socket_t zookeeper_connect(zhandle_t *zh,
  2131. struct sockaddr_storage *addr,
  2132. socket_t fd)
  2133. {
  2134. int rc;
  2135. int addr_len;
  2136. #if defined(AF_INET6)
  2137. if (addr->ss_family == AF_INET6) {
  2138. addr_len = sizeof(struct sockaddr_in6);
  2139. } else {
  2140. addr_len = sizeof(struct sockaddr_in);
  2141. }
  2142. #else
  2143. addr_len = sizeof(struct sockaddr_in);
  2144. #endif
  2145. LOG_DEBUG(LOGCALLBACK(zh), "[zk] connect()\n");
  2146. rc = connect(fd, (struct sockaddr *)addr, addr_len);
  2147. #ifdef _WIN32
  2148. errno = GetLastError();
  2149. #ifndef EWOULDBLOCK
  2150. #define EWOULDBLOCK WSAEWOULDBLOCK
  2151. #endif
  2152. #ifndef EINPROGRESS
  2153. #define EINPROGRESS WSAEINPROGRESS
  2154. #endif
  2155. #if _MSC_VER >= 1600
  2156. switch(errno) {
  2157. case WSAEWOULDBLOCK:
  2158. errno = EWOULDBLOCK;
  2159. break;
  2160. case WSAEINPROGRESS:
  2161. errno = EINPROGRESS;
  2162. break;
  2163. }
  2164. #endif
  2165. #endif
  2166. return rc;
  2167. }
  2168. int zookeeper_interest(zhandle_t *zh, socket_t *fd, int *interest,
  2169. struct timeval *tv)
  2170. {
  2171. int sock_flags;
  2172. int rc = 0;
  2173. struct timeval now;
  2174. #ifdef SOCK_CLOEXEC_ENABLED
  2175. sock_flags = SOCK_STREAM | SOCK_CLOEXEC;
  2176. #else
  2177. sock_flags = SOCK_STREAM;
  2178. #endif
  2179. if(zh==0 || fd==0 ||interest==0 || tv==0)
  2180. return ZBADARGUMENTS;
  2181. if (is_unrecoverable(zh))
  2182. return ZINVALIDSTATE;
  2183. get_system_time(&now);
  2184. if(zh->next_deadline.tv_sec!=0 || zh->next_deadline.tv_usec!=0){
  2185. int time_left = calculate_interval(&zh->next_deadline, &now);
  2186. int max_exceed = zh->recv_timeout / 10 > 200 ? 200 :
  2187. (zh->recv_timeout / 10);
  2188. if (time_left > max_exceed)
  2189. LOG_WARN(LOGCALLBACK(zh), "Exceeded deadline by %dms", time_left);
  2190. }
  2191. api_prolog(zh);
  2192. rc = update_addrs(zh, &now);
  2193. if (rc != ZOK) {
  2194. return api_epilog(zh, rc);
  2195. }
  2196. *fd = zh->fd->sock;
  2197. *interest = 0;
  2198. tv->tv_sec = 0;
  2199. tv->tv_usec = 0;
  2200. if (*fd == -1) {
  2201. /*
  2202. * If we previously failed to connect to server pool (zh->delay == 1)
  2203. * then we need delay our connection on this iteration 1/60 of the
  2204. * recv timeout before trying again so we don't spin.
  2205. *
  2206. * We always clear the delay setting. If we fail again, we'll set delay
  2207. * again and on the next iteration we'll do the same.
  2208. *
  2209. * We will also delay if the disable_reconnection_attempt is set.
  2210. */
  2211. if (zh->delay == 1 || zh->disable_reconnection_attempt == 1) {
  2212. *tv = get_timeval(zh->recv_timeout/60);
  2213. zh->delay = 0;
  2214. LOG_WARN(LOGCALLBACK(zh), "Delaying connection after exhaustively trying all servers [%s]",
  2215. zh->hostname);
  2216. } else {
  2217. if (addr_rw_server) {
  2218. zh->addr_cur = *addr_rw_server;
  2219. addr_rw_server = 0;
  2220. } else {
  2221. // No need to delay -- grab the next server and attempt connection
  2222. zoo_cycle_next_server(zh);
  2223. }
  2224. zh->fd->sock = socket(zh->addr_cur.ss_family, sock_flags, 0);
  2225. if (zh->fd->sock < 0) {
  2226. rc = handle_socket_error_msg(zh,
  2227. __LINE__,
  2228. ZSYSTEMERROR,
  2229. "socket() call failed");
  2230. return api_epilog(zh, rc);
  2231. }
  2232. zookeeper_set_sock_nodelay(zh, zh->fd->sock);
  2233. zookeeper_set_sock_noblock(zh, zh->fd->sock);
  2234. rc = zookeeper_connect(zh, &zh->addr_cur, zh->fd->sock);
  2235. if (rc == -1) {
  2236. /* we are handling the non-blocking connect according to
  2237. * the description in section 16.3 "Non-blocking connect"
  2238. * in UNIX Network Programming vol 1, 3rd edition */
  2239. if (errno == EWOULDBLOCK || errno == EINPROGRESS) {
  2240. // For SSL, we first go to ZOO_SSL_CONNECTING_STATE
  2241. if (zh->fd->cert != NULL)
  2242. zh->state = ZOO_SSL_CONNECTING_STATE;
  2243. else
  2244. zh->state = ZOO_CONNECTING_STATE;
  2245. } else {
  2246. rc = handle_socket_error_msg(zh,
  2247. __LINE__,
  2248. ZCONNECTIONLOSS,
  2249. "connect() call failed");
  2250. return api_epilog(zh, rc);
  2251. }
  2252. } else {
  2253. #ifdef HAVE_OPENSSL_H
  2254. if (zh->fd->cert != NULL) {
  2255. // We do SSL_connect() here
  2256. if (init_ssl_for_handler(zh) != ZOK) {
  2257. return ZSSLCONNECTIONERROR;
  2258. }
  2259. }
  2260. #endif
  2261. rc = prime_connection(zh);
  2262. if (rc != 0) {
  2263. return api_epilog(zh,rc);
  2264. }
  2265. LOG_INFO(LOGCALLBACK(zh),
  2266. "Initiated connection to server %s",
  2267. format_endpoint_info(&zh->addr_cur));
  2268. }
  2269. *tv = get_timeval(zh->recv_timeout/3);
  2270. }
  2271. *fd = zh->fd->sock;
  2272. zh->last_recv = now;
  2273. zh->last_send = now;
  2274. zh->last_ping = now;
  2275. zh->last_ping_rw = now;
  2276. zh->ping_rw_timeout = MIN_RW_TIMEOUT;
  2277. }
  2278. if (zh->fd->sock != -1) {
  2279. int idle_recv = calculate_interval(&zh->last_recv, &now);
  2280. int idle_send = calculate_interval(&zh->last_send, &now);
  2281. int recv_to = zh->recv_timeout*2/3 - idle_recv;
  2282. int send_to = zh->recv_timeout/3;
  2283. // have we exceeded the receive timeout threshold?
  2284. if (recv_to <= 0 && zh->state != ZOO_SSL_CONNECTING_STATE) {
  2285. // We gotta cut our losses and connect to someone else
  2286. #ifdef _WIN32
  2287. errno = WSAETIMEDOUT;
  2288. #else
  2289. errno = ETIMEDOUT;
  2290. #endif
  2291. *interest=0;
  2292. *tv = get_timeval(0);
  2293. return api_epilog(zh,handle_socket_error_msg(zh,
  2294. __LINE__,ZOPERATIONTIMEOUT,
  2295. "connection to %s timed out (exceeded timeout by %dms)",
  2296. format_endpoint_info(&zh->addr_cur),
  2297. -recv_to));
  2298. }
  2299. // We only allow 1/3 of our timeout time to expire before sending
  2300. // a PING
  2301. if (is_connected(zh)) {
  2302. send_to = zh->recv_timeout/3 - idle_send;
  2303. if (send_to <= 0) {
  2304. if (zh->sent_requests.head == 0) {
  2305. rc = send_ping(zh);
  2306. if (rc < 0) {
  2307. LOG_ERROR(LOGCALLBACK(zh), "failed to send PING request (zk retcode=%d)",rc);
  2308. return api_epilog(zh,rc);
  2309. }
  2310. }
  2311. send_to = zh->recv_timeout/3;
  2312. }
  2313. }
  2314. // If we are in read-only mode, seek for read/write server
  2315. if (zh->state == ZOO_READONLY_STATE) {
  2316. int idle_ping_rw = calculate_interval(&zh->last_ping_rw, &now);
  2317. if (idle_ping_rw >= zh->ping_rw_timeout) {
  2318. zh->last_ping_rw = now;
  2319. idle_ping_rw = 0;
  2320. zh->ping_rw_timeout = min(zh->ping_rw_timeout * 2,
  2321. MAX_RW_TIMEOUT);
  2322. if (ping_rw_server(zh)) {
  2323. struct sockaddr_storage addr;
  2324. addrvec_peek(&zh->addrs, &addr);
  2325. zh->ping_rw_timeout = MIN_RW_TIMEOUT;
  2326. LOG_INFO(LOGCALLBACK(zh),
  2327. "r/w server found at %s",
  2328. format_endpoint_info(&addr));
  2329. cleanup(zh, ZOK);
  2330. } else {
  2331. addrvec_next(&zh->addrs, NULL);
  2332. }
  2333. }
  2334. send_to = min(send_to, zh->ping_rw_timeout - idle_ping_rw);
  2335. }
  2336. // choose the lesser value as the timeout
  2337. *tv = get_timeval(min(recv_to, send_to));
  2338. zh->next_deadline.tv_sec = now.tv_sec + tv->tv_sec;
  2339. zh->next_deadline.tv_usec = now.tv_usec + tv->tv_usec;
  2340. if (zh->next_deadline.tv_usec > 1000000) {
  2341. zh->next_deadline.tv_sec += zh->next_deadline.tv_usec / 1000000;
  2342. zh->next_deadline.tv_usec = zh->next_deadline.tv_usec % 1000000;
  2343. }
  2344. *interest = ZOOKEEPER_READ;
  2345. /* we are interested in a write if we are connected and have something
  2346. * to send, or we are waiting for a connect to finish. */
  2347. if ((zh->to_send.head && (is_connected(zh) || is_sasl_auth_in_progress(zh)))
  2348. || zh->state == ZOO_CONNECTING_STATE
  2349. || zh->state == ZOO_SSL_CONNECTING_STATE) {
  2350. *interest |= ZOOKEEPER_WRITE;
  2351. }
  2352. }
  2353. return api_epilog(zh,ZOK);
  2354. }
  2355. #ifdef HAVE_OPENSSL_H
  2356. /*
  2357. * use this function, if you want to init SSL for the socket currently registered in the zookeeper handler
  2358. */
  2359. static int init_ssl_for_handler(zhandle_t *zh)
  2360. {
  2361. int rc = init_ssl_for_socket(zh->fd, zh, 1);
  2362. if (rc == ZOK) {
  2363. // (SUCCESS) Now mark the ZOO_CONNECTING_STATE so that
  2364. // prime_connection() happen.
  2365. // prime_connection() only happens in ZOO_CONNECTING_STATE
  2366. zh->state = ZOO_CONNECTING_STATE;
  2367. }
  2368. return rc;
  2369. }
  2370. /*
  2371. * use this function, if you want to init SSL for a socket, pointing to a different server address than the one
  2372. * currently registered in the zookeeper handler (e.g. ping other servers when you are connected to a read-only one)
  2373. */
  2374. static int init_ssl_for_socket(zsock_t *fd, zhandle_t *zh, int fail_on_error) {
  2375. SSL_CTX **ctx;
  2376. if (!fd->ssl_sock) {
  2377. const SSL_METHOD *method;
  2378. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  2379. OpenSSL_add_all_algorithms();
  2380. ERR_load_BIO_strings();
  2381. ERR_load_crypto_strings();
  2382. SSL_load_error_strings();
  2383. SSL_library_init();
  2384. method = SSLv23_client_method();
  2385. #else
  2386. OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
  2387. method = TLS_client_method();
  2388. #endif
  2389. if (FIPS_mode() == 0) {
  2390. LOG_INFO(LOGCALLBACK(zh), "FIPS mode is OFF ");
  2391. } else {
  2392. LOG_INFO(LOGCALLBACK(zh), "FIPS mode is ON ");
  2393. }
  2394. fd->ssl_ctx = SSL_CTX_new(method);
  2395. ctx = &fd->ssl_ctx;
  2396. SSL_CTX_set_verify(*ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
  2397. /*SERVER CA FILE*/
  2398. if (SSL_CTX_load_verify_locations(*ctx, fd->cert->ca, 0) != 1) {
  2399. SSL_CTX_free(*ctx);
  2400. LOG_ERROR(LOGCALLBACK(zh), "Failed to load CA file %s", fd->cert->ca);
  2401. errno = EINVAL;
  2402. return ZBADARGUMENTS;
  2403. }
  2404. if (SSL_CTX_set_default_verify_paths(*ctx) != 1) {
  2405. SSL_CTX_free(*ctx);
  2406. LOG_ERROR(LOGCALLBACK(zh), "Call to SSL_CTX_set_default_verify_paths failed");
  2407. errno = EINVAL;
  2408. return ZBADARGUMENTS;
  2409. }
  2410. /*CLIENT CA FILE (With Certificate Chain)*/
  2411. if (SSL_CTX_use_certificate_chain_file(*ctx, fd->cert->cert) != 1) {
  2412. SSL_CTX_free(*ctx);
  2413. LOG_ERROR(LOGCALLBACK(zh), "Failed to load client certificate chain from %s", fd->cert->cert);
  2414. errno = EINVAL;
  2415. return ZBADARGUMENTS;
  2416. }
  2417. /*CLIENT PRIVATE KEY*/
  2418. SSL_CTX_set_default_passwd_cb_userdata(*ctx, fd->cert->passwd);
  2419. if (SSL_CTX_use_PrivateKey_file(*ctx, fd->cert->key, SSL_FILETYPE_PEM) != 1) {
  2420. SSL_CTX_free(*ctx);
  2421. LOG_ERROR(LOGCALLBACK(zh), "Failed to load client private key from %s", fd->cert->key);
  2422. errno = EINVAL;
  2423. return ZBADARGUMENTS;
  2424. }
  2425. /*CHECK*/
  2426. if (SSL_CTX_check_private_key(*ctx) != 1) {
  2427. SSL_CTX_free(*ctx);
  2428. LOG_ERROR(LOGCALLBACK(zh), "SSL_CTX_check_private_key failed");
  2429. errno = EINVAL;
  2430. return ZBADARGUMENTS;
  2431. }
  2432. /*MULTIPLE HANDSHAKE*/
  2433. SSL_CTX_set_mode(*ctx, SSL_MODE_AUTO_RETRY);
  2434. fd->ssl_sock = SSL_new(*ctx);
  2435. if (fd->ssl_sock == NULL) {
  2436. if (fail_on_error) {
  2437. return handle_socket_error_msg(zh,__LINE__,ZSSLCONNECTIONERROR, "error creating ssl context");
  2438. } else {
  2439. LOG_ERROR(LOGCALLBACK(zh), "error creating ssl context");
  2440. return ZSSLCONNECTIONERROR;
  2441. }
  2442. }
  2443. SSL_set_fd(fd->ssl_sock, fd->sock);
  2444. }
  2445. while(1) {
  2446. int rc;
  2447. int sock = fd->sock;
  2448. struct timeval tv;
  2449. fd_set s_rfds, s_wfds;
  2450. tv.tv_sec = 1;
  2451. tv.tv_usec = 0;
  2452. FD_ZERO(&s_rfds);
  2453. FD_ZERO(&s_wfds);
  2454. rc = SSL_connect(fd->ssl_sock);
  2455. if (rc == 1) {
  2456. return ZOK;
  2457. } else {
  2458. rc = SSL_get_error(fd->ssl_sock, rc);
  2459. if (rc == SSL_ERROR_WANT_READ) {
  2460. FD_SET(sock, &s_rfds);
  2461. FD_CLR(sock, &s_wfds);
  2462. } else if (rc == SSL_ERROR_WANT_WRITE) {
  2463. FD_SET(sock, &s_wfds);
  2464. FD_CLR(sock, &s_rfds);
  2465. } else {
  2466. if (fail_on_error) {
  2467. return handle_socket_error_msg(zh,__LINE__,ZSSLCONNECTIONERROR, "error in ssl connect");
  2468. } else {
  2469. LOG_ERROR(LOGCALLBACK(zh), "error in ssl connect");
  2470. return ZSSLCONNECTIONERROR;
  2471. }
  2472. }
  2473. rc = select(sock + 1, &s_rfds, &s_wfds, NULL, &tv);
  2474. if (rc == -1) {
  2475. if (fail_on_error) {
  2476. return handle_socket_error_msg(zh,__LINE__,ZSSLCONNECTIONERROR, "error in ssl connect (after select)");
  2477. } else {
  2478. LOG_ERROR(LOGCALLBACK(zh), "error in ssl connect (after select)");
  2479. return ZSSLCONNECTIONERROR;
  2480. }
  2481. }
  2482. }
  2483. }
  2484. }
  2485. #endif
  2486. /*
  2487. * the "bottom half" of the session establishment procedure, executed
  2488. * either after receiving the "prime response," or after SASL
  2489. * authentication is complete
  2490. */
  2491. static void finalize_session_establishment(zhandle_t *zh) {
  2492. zh->state = zh->primer_storage.readOnly ?
  2493. ZOO_READONLY_STATE : ZOO_CONNECTED_STATE;
  2494. zh->reconfig = 0;
  2495. LOG_INFO(LOGCALLBACK(zh),
  2496. "session establishment complete on server %s, sessionId=%#llx, negotiated timeout=%d %s",
  2497. format_endpoint_info(&zh->addr_cur),
  2498. zh->client_id.client_id, zh->recv_timeout,
  2499. zh->primer_storage.readOnly ? "(READ-ONLY mode)" : "");
  2500. /* we want the auth to be sent for, but since both call push to front
  2501. we need to call send_watch_set first */
  2502. send_set_watches(zh);
  2503. /* send the authentication packet now */
  2504. send_auth_info(zh);
  2505. LOG_DEBUG(LOGCALLBACK(zh), "Calling a watcher for a ZOO_SESSION_EVENT and the state=ZOO_CONNECTED_STATE");
  2506. zh->input_buffer = 0; // just in case the watcher calls zookeeper_process() again
  2507. PROCESS_SESSION_EVENT(zh, zh->state);
  2508. }
  2509. #ifdef HAVE_CYRUS_SASL_H
  2510. /*
  2511. * queue an encoded SASL request to ZooKeeper. The packet is added to
  2512. * the front of the queue.
  2513. *
  2514. * \param zh the ZooKeeper handle
  2515. * \param client_data the encoded SASL data, ready to send
  2516. * \param client_data_len the length of \c client_data
  2517. * \return ZOK on success, or ZMARSHALLINGERROR if something went wrong
  2518. */
  2519. int queue_sasl_request(zhandle_t *zh, const char *client_data, int client_data_len)
  2520. {
  2521. struct oarchive *oa;
  2522. int rc;
  2523. /* Java client use normal xid, too. */
  2524. struct RequestHeader h = { get_xid(), ZOO_SASL_OP };
  2525. struct GetSASLRequest req = { { client_data_len, client_data_len>0 ? (char *) client_data : "" } };
  2526. oa = create_buffer_oarchive();
  2527. rc = serialize_RequestHeader(oa, "header", &h);
  2528. rc = rc < 0 ? rc : serialize_GetSASLRequest(oa, "req", &req);
  2529. rc = rc < 0 ? rc : queue_front_buffer_bytes(&zh->to_send, get_buffer(oa),
  2530. get_buffer_len(oa));
  2531. close_buffer_oarchive(&oa, 0);
  2532. LOG_DEBUG(LOGCALLBACK(zh),
  2533. "SASL: Queued request len=%d rc=%d", client_data_len, rc);
  2534. return (rc < 0) ? ZMARSHALLINGERROR : ZOK;
  2535. }
  2536. /*
  2537. * decode an expected SASL response and perform the corresponding
  2538. * authentication step
  2539. */
  2540. static int process_sasl_response(zhandle_t *zh, char *buffer, int len)
  2541. {
  2542. struct iarchive *ia = create_buffer_iarchive(buffer, len);
  2543. struct ReplyHeader hdr;
  2544. struct SetSASLResponse res;
  2545. int rc;
  2546. rc = ia ? ZOK : ZSYSTEMERROR;
  2547. rc = rc < 0 ? rc : deserialize_ReplyHeader(ia, "hdr", &hdr);
  2548. rc = rc < 0 ? rc : deserialize_SetSASLResponse(ia, "reply", &res);
  2549. rc = rc < 0 ? rc : zoo_sasl_client_step(zh, res.token.buff, res.token.len);
  2550. deallocate_SetSASLResponse(&res);
  2551. if (ia) {
  2552. close_buffer_iarchive(&ia);
  2553. }
  2554. LOG_DEBUG(LOGCALLBACK(zh),
  2555. "SASL: Processed response len=%d rc=%d", len, rc);
  2556. return rc;
  2557. }
  2558. #endif /* HAVE_CYRUS_SASL_H */
  2559. static int check_events(zhandle_t *zh, int events)
  2560. {
  2561. if (zh->fd->sock == -1)
  2562. return ZINVALIDSTATE;
  2563. #ifdef HAVE_OPENSSL_H
  2564. if ((events&ZOOKEEPER_WRITE) && (zh->state == ZOO_SSL_CONNECTING_STATE) && zh->fd->cert != NULL) {
  2565. int rc, error;
  2566. socklen_t len = sizeof(error);
  2567. rc = getsockopt(zh->fd->sock, SOL_SOCKET, SO_ERROR, &error, &len);
  2568. /* the description in section 16.4 "Non-blocking connect"
  2569. * in UNIX Network Programming vol 1, 3rd edition, points out
  2570. * that sometimes the error is in errno and sometimes in error */
  2571. if (rc < 0 || error) {
  2572. if (rc == 0)
  2573. errno = error;
  2574. return handle_socket_error_msg(zh, __LINE__,ZCONNECTIONLOSS,
  2575. "server refused to accept the client");
  2576. }
  2577. // We do SSL_connect() here
  2578. if (init_ssl_for_handler(zh) != ZOK) {
  2579. return ZSSLCONNECTIONERROR;
  2580. }
  2581. }
  2582. #endif
  2583. if ((events&ZOOKEEPER_WRITE)&&(zh->state == ZOO_CONNECTING_STATE)) {
  2584. int rc, error;
  2585. socklen_t len = sizeof(error);
  2586. rc = getsockopt(zh->fd->sock, SOL_SOCKET, SO_ERROR, &error, &len);
  2587. /* the description in section 16.4 "Non-blocking connect"
  2588. * in UNIX Network Programming vol 1, 3rd edition, points out
  2589. * that sometimes the error is in errno and sometimes in error */
  2590. if (rc < 0 || error) {
  2591. if (rc == 0)
  2592. errno = error;
  2593. return handle_socket_error_msg(zh, __LINE__,ZCONNECTIONLOSS,
  2594. "server refused to accept the client");
  2595. }
  2596. if((rc=prime_connection(zh))!=0)
  2597. return rc;
  2598. LOG_INFO(LOGCALLBACK(zh), "initiated connection to server %s", format_endpoint_info(&zh->addr_cur));
  2599. return ZOK;
  2600. }
  2601. if (zh->to_send.head && (events&ZOOKEEPER_WRITE)) {
  2602. /* make the flush call non-blocking by specifying a 0 timeout */
  2603. int rc=flush_send_queue(zh,0);
  2604. if (rc < 0)
  2605. return handle_socket_error_msg(zh,__LINE__,ZCONNECTIONLOSS,
  2606. "failed while flushing send queue");
  2607. }
  2608. if (events&ZOOKEEPER_READ) {
  2609. int rc;
  2610. if (zh->input_buffer == 0) {
  2611. zh->input_buffer = allocate_buffer(0,0);
  2612. }
  2613. rc = recv_buffer(zh, zh->input_buffer);
  2614. if (rc < 0) {
  2615. return handle_socket_error_msg(zh, __LINE__,ZCONNECTIONLOSS,
  2616. "failed while receiving a server response");
  2617. }
  2618. if (rc > 0) {
  2619. get_system_time(&zh->last_recv);
  2620. if (zh->input_buffer != &zh->primer_buffer) {
  2621. if (is_connected(zh) || !is_sasl_auth_in_progress(zh)) {
  2622. queue_buffer(&zh->to_process, zh->input_buffer, 0);
  2623. #ifdef HAVE_CYRUS_SASL_H
  2624. } else {
  2625. rc = process_sasl_response(zh, zh->input_buffer->buffer, zh->input_buffer->curr_offset);
  2626. free_buffer(zh->input_buffer);
  2627. if (rc < 0) {
  2628. zoo_sasl_mark_failed(zh);
  2629. return rc;
  2630. } else if (zh->sasl_client->state == ZOO_SASL_COMPLETE) {
  2631. /*
  2632. * SASL authentication just completed; send
  2633. * watches, auth. info, etc. now.
  2634. */
  2635. finalize_session_establishment(zh);
  2636. }
  2637. #endif /* HAVE_CYRUS_SASL_H */
  2638. }
  2639. } else {
  2640. int64_t oldid, newid;
  2641. //deserialize
  2642. deserialize_prime_response(&zh->primer_storage, zh->primer_buffer.buffer);
  2643. /* We are processing the primer_buffer, so we need to finish
  2644. * the connection handshake */
  2645. oldid = zh->seen_rw_server_before ? zh->client_id.client_id : 0;
  2646. zh->seen_rw_server_before |= !zh->primer_storage.readOnly;
  2647. newid = zh->primer_storage.sessionId;
  2648. if (oldid != 0 && oldid != newid) {
  2649. zh->state = ZOO_EXPIRED_SESSION_STATE;
  2650. errno = ESTALE;
  2651. return handle_socket_error_msg(zh,__LINE__,ZSESSIONEXPIRED,
  2652. "sessionId=%#llx has expired.",oldid);
  2653. } else {
  2654. zh->recv_timeout = zh->primer_storage.timeOut;
  2655. zh->client_id.client_id = newid;
  2656. memcpy(zh->client_id.passwd, &zh->primer_storage.passwd,
  2657. sizeof(zh->client_id.passwd));
  2658. #ifdef HAVE_CYRUS_SASL_H
  2659. if (zh->sasl_client) {
  2660. /*
  2661. * Start a SASL authentication session.
  2662. * Watches, auth. info, etc. will be sent
  2663. * after it completes.
  2664. */
  2665. rc = zoo_sasl_connect(zh);
  2666. rc = rc < 0 ? rc : zoo_sasl_client_start(zh);
  2667. if (rc < 0) {
  2668. zoo_sasl_mark_failed(zh);
  2669. return rc;
  2670. }
  2671. } else {
  2672. /* Can send watches, auth. info, etc. immediately. */
  2673. finalize_session_establishment(zh);
  2674. }
  2675. #else /* HAVE_CYRUS_SASL_H */
  2676. /* Can send watches, auth. info, etc. immediately. */
  2677. finalize_session_establishment(zh);
  2678. #endif /* HAVE_CYRUS_SASL_H */
  2679. }
  2680. }
  2681. zh->input_buffer = 0;
  2682. } else {
  2683. // zookeeper_process was called but there was nothing to read
  2684. // from the socket
  2685. return ZNOTHING;
  2686. }
  2687. }
  2688. return ZOK;
  2689. }
  2690. void api_prolog(zhandle_t* zh)
  2691. {
  2692. inc_ref_counter(zh,1);
  2693. }
  2694. int api_epilog(zhandle_t *zh,int rc)
  2695. {
  2696. if(inc_ref_counter(zh,-1)==0 && zh->close_requested!=0)
  2697. zookeeper_close(zh);
  2698. return rc;
  2699. }
  2700. //#ifdef THREADED
  2701. // IO thread queues session events to be processed by the completion thread
  2702. static int queue_session_event(zhandle_t *zh, int state)
  2703. {
  2704. int rc;
  2705. struct WatcherEvent evt = { ZOO_SESSION_EVENT, state, "" };
  2706. struct ReplyHeader hdr = { WATCHER_EVENT_XID, 0, 0 };
  2707. struct oarchive *oa;
  2708. completion_list_t *cptr;
  2709. if ((oa=create_buffer_oarchive())==NULL) {
  2710. LOG_ERROR(LOGCALLBACK(zh), "out of memory");
  2711. goto error;
  2712. }
  2713. rc = serialize_ReplyHeader(oa, "hdr", &hdr);
  2714. rc = rc<0?rc: serialize_WatcherEvent(oa, "event", &evt);
  2715. if(rc<0){
  2716. close_buffer_oarchive(&oa, 1);
  2717. goto error;
  2718. }
  2719. cptr = create_completion_entry(zh, WATCHER_EVENT_XID,-1,0,0,0,0);
  2720. cptr->buffer = allocate_buffer(get_buffer(oa), get_buffer_len(oa));
  2721. cptr->buffer->curr_offset = get_buffer_len(oa);
  2722. if (!cptr->buffer) {
  2723. free(cptr);
  2724. close_buffer_oarchive(&oa, 1);
  2725. goto error;
  2726. }
  2727. /* We queued the buffer, so don't free it */
  2728. close_buffer_oarchive(&oa, 0);
  2729. cptr->c.watcher_result = collectWatchers(zh, ZOO_SESSION_EVENT, "");
  2730. queue_completion(&zh->completions_to_process, cptr, 0);
  2731. if (process_async(zh->outstanding_sync)) {
  2732. process_completions(zh);
  2733. }
  2734. return ZOK;
  2735. error:
  2736. errno=ENOMEM;
  2737. return ZSYSTEMERROR;
  2738. }
  2739. //#endif
  2740. completion_list_t *dequeue_completion(completion_head_t *list)
  2741. {
  2742. completion_list_t *cptr;
  2743. lock_completion_list(list);
  2744. cptr = list->head;
  2745. if (cptr) {
  2746. list->head = cptr->next;
  2747. if (!list->head) {
  2748. assert(list->last == cptr);
  2749. list->last = 0;
  2750. }
  2751. }
  2752. unlock_completion_list(list);
  2753. return cptr;
  2754. }
  2755. // cleanup completion list of a failed multi request
  2756. static void cleanup_failed_multi(zhandle_t *zh, int xid, int rc, completion_list_t *cptr) {
  2757. completion_list_t *entry;
  2758. completion_head_t *clist = &cptr->c.clist;
  2759. while ((entry = dequeue_completion(clist)) != NULL) {
  2760. // Fake failed response for all sub-requests
  2761. deserialize_response(zh, entry->c.type, xid, 1, rc, entry, NULL);
  2762. destroy_completion_entry(entry);
  2763. }
  2764. }
  2765. static int deserialize_multi(zhandle_t *zh, int xid, completion_list_t *cptr, struct iarchive *ia)
  2766. {
  2767. int rc = 0;
  2768. completion_head_t *clist = &cptr->c.clist;
  2769. struct MultiHeader mhdr = {0, 0, 0};
  2770. assert(clist);
  2771. deserialize_MultiHeader(ia, "multiheader", &mhdr);
  2772. while (!mhdr.done) {
  2773. completion_list_t *entry = dequeue_completion(clist);
  2774. assert(entry);
  2775. if (mhdr.type == -1) {
  2776. struct ErrorResponse er;
  2777. deserialize_ErrorResponse(ia, "error", &er);
  2778. mhdr.err = er.err ;
  2779. if (rc == 0 && er.err != 0 && er.err != ZRUNTIMEINCONSISTENCY) {
  2780. rc = er.err;
  2781. }
  2782. }
  2783. deserialize_response(zh, entry->c.type, xid, mhdr.type == -1, mhdr.err, entry, ia);
  2784. deserialize_MultiHeader(ia, "multiheader", &mhdr);
  2785. //While deserializing the response we must destroy completion entry for each operation in
  2786. //the zoo_multi transaction. Otherwise this results in memory leak when client invokes zoo_multi
  2787. //operation.
  2788. destroy_completion_entry(entry);
  2789. }
  2790. return rc;
  2791. }
  2792. static void deserialize_response(zhandle_t *zh, int type, int xid, int failed, int rc, completion_list_t *cptr, struct iarchive *ia)
  2793. {
  2794. switch (type) {
  2795. case COMPLETION_DATA:
  2796. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_DATA for xid=%#x failed=%d rc=%d",
  2797. cptr->xid, failed, rc);
  2798. if (failed) {
  2799. cptr->c.data_result(rc, 0, 0, 0, cptr->data);
  2800. } else {
  2801. struct GetDataResponse res;
  2802. deserialize_GetDataResponse(ia, "reply", &res);
  2803. cptr->c.data_result(rc, res.data.buff, res.data.len,
  2804. &res.stat, cptr->data);
  2805. deallocate_GetDataResponse(&res);
  2806. }
  2807. break;
  2808. case COMPLETION_STAT:
  2809. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_STAT for xid=%#x failed=%d rc=%d",
  2810. cptr->xid, failed, rc);
  2811. if (failed) {
  2812. cptr->c.stat_result(rc, 0, cptr->data);
  2813. } else {
  2814. struct SetDataResponse res;
  2815. deserialize_SetDataResponse(ia, "reply", &res);
  2816. cptr->c.stat_result(rc, &res.stat, cptr->data);
  2817. deallocate_SetDataResponse(&res);
  2818. }
  2819. break;
  2820. case COMPLETION_STRINGLIST:
  2821. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_STRINGLIST for xid=%#x failed=%d rc=%d",
  2822. cptr->xid, failed, rc);
  2823. if (failed) {
  2824. cptr->c.strings_result(rc, 0, cptr->data);
  2825. } else {
  2826. struct GetChildrenResponse res;
  2827. deserialize_GetChildrenResponse(ia, "reply", &res);
  2828. cptr->c.strings_result(rc, &res.children, cptr->data);
  2829. deallocate_GetChildrenResponse(&res);
  2830. }
  2831. break;
  2832. case COMPLETION_STRINGLIST_STAT:
  2833. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_STRINGLIST_STAT for xid=%#x failed=%d rc=%d",
  2834. cptr->xid, failed, rc);
  2835. if (failed) {
  2836. cptr->c.strings_stat_result(rc, 0, 0, cptr->data);
  2837. } else {
  2838. struct GetChildren2Response res;
  2839. deserialize_GetChildren2Response(ia, "reply", &res);
  2840. cptr->c.strings_stat_result(rc, &res.children, &res.stat, cptr->data);
  2841. deallocate_GetChildren2Response(&res);
  2842. }
  2843. break;
  2844. case COMPLETION_STRING:
  2845. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_STRING for xid=%#x failed=%d, rc=%d",
  2846. cptr->xid, failed, rc);
  2847. if (failed) {
  2848. cptr->c.string_result(rc, 0, cptr->data);
  2849. } else {
  2850. struct CreateResponse res;
  2851. const char *client_path;
  2852. memset(&res, 0, sizeof(res));
  2853. deserialize_CreateResponse(ia, "reply", &res);
  2854. client_path = sub_string(zh, res.path);
  2855. cptr->c.string_result(rc, client_path, cptr->data);
  2856. free_duplicate_path(client_path, res.path);
  2857. deallocate_CreateResponse(&res);
  2858. }
  2859. break;
  2860. case COMPLETION_STRING_STAT:
  2861. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_STRING_STAT for xid=%#x failed=%d, rc=%d",
  2862. cptr->xid, failed, rc);
  2863. if (failed) {
  2864. cptr->c.string_stat_result(rc, 0, 0, cptr->data);
  2865. } else {
  2866. struct Create2Response res;
  2867. const char *client_path;
  2868. deserialize_Create2Response(ia, "reply", &res);
  2869. client_path = sub_string(zh, res.path);
  2870. cptr->c.string_stat_result(rc, client_path, &res.stat, cptr->data);
  2871. free_duplicate_path(client_path, res.path);
  2872. deallocate_Create2Response(&res);
  2873. }
  2874. break;
  2875. case COMPLETION_ACLLIST:
  2876. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_ACLLIST for xid=%#x failed=%d rc=%d",
  2877. cptr->xid, failed, rc);
  2878. if (failed) {
  2879. cptr->c.acl_result(rc, 0, 0, cptr->data);
  2880. } else {
  2881. struct GetACLResponse res;
  2882. deserialize_GetACLResponse(ia, "reply", &res);
  2883. cptr->c.acl_result(rc, &res.acl, &res.stat, cptr->data);
  2884. deallocate_GetACLResponse(&res);
  2885. }
  2886. break;
  2887. case COMPLETION_VOID:
  2888. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_VOID for xid=%#x failed=%d rc=%d",
  2889. cptr->xid, failed, rc);
  2890. assert(cptr->c.void_result);
  2891. cptr->c.void_result(rc, cptr->data);
  2892. break;
  2893. case COMPLETION_MULTI:
  2894. LOG_DEBUG(LOGCALLBACK(zh), "Calling COMPLETION_MULTI for xid=%#x failed=%d rc=%d",
  2895. cptr->xid, failed, rc);
  2896. assert(cptr->c.void_result);
  2897. if (failed) {
  2898. cleanup_failed_multi(zh, xid, rc, cptr);
  2899. } else {
  2900. rc = deserialize_multi(zh, xid, cptr, ia);
  2901. }
  2902. cptr->c.void_result(rc, cptr->data);
  2903. break;
  2904. default:
  2905. LOG_DEBUG(LOGCALLBACK(zh), "Unsupported completion type=%d", cptr->c.type);
  2906. }
  2907. }
  2908. /* handles async completion (both single- and multithreaded) */
  2909. void process_completions(zhandle_t *zh)
  2910. {
  2911. completion_list_t *cptr;
  2912. while ((cptr = dequeue_completion(&zh->completions_to_process)) != 0) {
  2913. struct ReplyHeader hdr;
  2914. buffer_list_t *bptr = cptr->buffer;
  2915. struct iarchive *ia = create_buffer_iarchive(bptr->buffer,
  2916. bptr->len);
  2917. deserialize_ReplyHeader(ia, "hdr", &hdr);
  2918. if (hdr.xid == WATCHER_EVENT_XID) {
  2919. int type, state;
  2920. struct WatcherEvent evt;
  2921. deserialize_WatcherEvent(ia, "event", &evt);
  2922. /* We are doing a notification, so there is no pending request */
  2923. type = evt.type;
  2924. state = evt.state;
  2925. /* This is a notification so there aren't any pending requests */
  2926. LOG_DEBUG(LOGCALLBACK(zh), "Calling a watcher for node [%s], type = %d event=%s",
  2927. (evt.path==NULL?"NULL":evt.path), cptr->c.type,
  2928. watcherEvent2String(type));
  2929. deliverWatchers(zh,type,state,evt.path, &cptr->c.watcher_result);
  2930. deallocate_WatcherEvent(&evt);
  2931. } else {
  2932. deserialize_response(zh, cptr->c.type, hdr.xid, hdr.err != 0, hdr.err, cptr, ia);
  2933. }
  2934. destroy_completion_entry(cptr);
  2935. close_buffer_iarchive(&ia);
  2936. }
  2937. }
  2938. static void isSocketReadable(zhandle_t* zh)
  2939. {
  2940. #ifndef _WIN32
  2941. struct pollfd fds;
  2942. fds.fd = zh->fd->sock;
  2943. fds.events = POLLIN;
  2944. if (poll(&fds,1,0)<=0) {
  2945. // socket not readable -- no more responses to process
  2946. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  2947. }
  2948. #else
  2949. fd_set rfds;
  2950. struct timeval waittime = {0, 0};
  2951. FD_ZERO(&rfds);
  2952. FD_SET( zh->fd , &rfds);
  2953. if (select(0, &rfds, NULL, NULL, &waittime) <= 0){
  2954. // socket not readable -- no more responses to process
  2955. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  2956. }
  2957. #endif
  2958. else{
  2959. get_system_time(&zh->socket_readable);
  2960. }
  2961. }
  2962. static void checkResponseLatency(zhandle_t* zh)
  2963. {
  2964. int delay;
  2965. struct timeval now;
  2966. if(zh->socket_readable.tv_sec==0)
  2967. return;
  2968. get_system_time(&now);
  2969. delay=calculate_interval(&zh->socket_readable, &now);
  2970. if(delay>20)
  2971. LOG_DEBUG(LOGCALLBACK(zh), "The following server response has spent at least %dms sitting in the client socket recv buffer",delay);
  2972. zh->socket_readable.tv_sec=zh->socket_readable.tv_usec=0;
  2973. }
  2974. int zookeeper_process(zhandle_t *zh, int events)
  2975. {
  2976. buffer_list_t *bptr;
  2977. int rc;
  2978. if (zh==NULL)
  2979. return ZBADARGUMENTS;
  2980. if (is_unrecoverable(zh))
  2981. return ZINVALIDSTATE;
  2982. api_prolog(zh);
  2983. IF_DEBUG(checkResponseLatency(zh));
  2984. rc = check_events(zh, events);
  2985. if (rc!=ZOK)
  2986. return api_epilog(zh, rc);
  2987. IF_DEBUG(isSocketReadable(zh));
  2988. while (rc >= 0 && (bptr=dequeue_buffer(&zh->to_process))) {
  2989. struct ReplyHeader hdr;
  2990. struct iarchive *ia = create_buffer_iarchive(
  2991. bptr->buffer, bptr->curr_offset);
  2992. deserialize_ReplyHeader(ia, "hdr", &hdr);
  2993. if (hdr.xid == PING_XID) {
  2994. // Ping replies can arrive out-of-order
  2995. int elapsed = 0;
  2996. struct timeval now;
  2997. gettimeofday(&now, 0);
  2998. elapsed = calculate_interval(&zh->last_ping, &now);
  2999. LOG_DEBUG(LOGCALLBACK(zh), "Got ping response in %d ms", elapsed);
  3000. free_buffer(bptr);
  3001. } else if (hdr.xid == WATCHER_EVENT_XID) {
  3002. struct WatcherEvent evt;
  3003. int type = 0;
  3004. char *path = NULL;
  3005. completion_list_t *c = NULL;
  3006. LOG_DEBUG(LOGCALLBACK(zh), "Processing WATCHER_EVENT");
  3007. deserialize_WatcherEvent(ia, "event", &evt);
  3008. type = evt.type;
  3009. path = evt.path;
  3010. /* We are doing a notification, so there is no pending request */
  3011. c = create_completion_entry(zh, WATCHER_EVENT_XID,-1,0,0,0,0);
  3012. c->buffer = bptr;
  3013. c->c.watcher_result = collectWatchers(zh, type, path);
  3014. // We cannot free until now, otherwise path will become invalid
  3015. deallocate_WatcherEvent(&evt);
  3016. queue_completion(&zh->completions_to_process, c, 0);
  3017. } else if (hdr.xid == SET_WATCHES_XID) {
  3018. LOG_DEBUG(LOGCALLBACK(zh), "Processing SET_WATCHES");
  3019. free_buffer(bptr);
  3020. } else if (hdr.xid == AUTH_XID){
  3021. LOG_DEBUG(LOGCALLBACK(zh), "Processing AUTH_XID");
  3022. /* special handling for the AUTH response as it may come back
  3023. * out-of-band */
  3024. auth_completion_func(hdr.err,zh);
  3025. free_buffer(bptr);
  3026. /* authentication completion may change the connection state to
  3027. * unrecoverable */
  3028. if(is_unrecoverable(zh)){
  3029. handle_error(zh, ZAUTHFAILED);
  3030. close_buffer_iarchive(&ia);
  3031. return api_epilog(zh, ZAUTHFAILED);
  3032. }
  3033. } else {
  3034. int rc = hdr.err;
  3035. /* Find the request corresponding to the response */
  3036. completion_list_t *cptr = dequeue_completion(&zh->sent_requests);
  3037. /* [ZOOKEEPER-804] Don't assert if zookeeper_close has been called. */
  3038. if (zh->close_requested == 1 && cptr == NULL) {
  3039. LOG_DEBUG(LOGCALLBACK(zh), "Completion queue has been cleared by zookeeper_close()");
  3040. close_buffer_iarchive(&ia);
  3041. free_buffer(bptr);
  3042. return api_epilog(zh,ZINVALIDSTATE);
  3043. }
  3044. assert(cptr);
  3045. /* The requests are going to come back in order */
  3046. if (cptr->xid != hdr.xid) {
  3047. LOG_DEBUG(LOGCALLBACK(zh), "Processing unexpected or out-of-order response!");
  3048. // received unexpected (or out-of-order) response
  3049. close_buffer_iarchive(&ia);
  3050. free_buffer(bptr);
  3051. // put the completion back on the queue (so it gets properly
  3052. // signaled and deallocated) and disconnect from the server
  3053. queue_completion(&zh->sent_requests,cptr,1);
  3054. return api_epilog(zh,
  3055. handle_socket_error_msg(zh, __LINE__,ZRUNTIMEINCONSISTENCY,
  3056. "unexpected server response: expected %#x, but received %#x",
  3057. hdr.xid,cptr->xid));
  3058. }
  3059. if (hdr.zxid > 0) {
  3060. // Update last_zxid only when it is a request response
  3061. zh->last_zxid = hdr.zxid;
  3062. }
  3063. activateWatcher(zh, cptr->watcher, rc);
  3064. deactivateWatcher(zh, cptr->watcher_deregistration, rc);
  3065. if (cptr->c.void_result != SYNCHRONOUS_MARKER) {
  3066. LOG_DEBUG(LOGCALLBACK(zh), "Queueing asynchronous response");
  3067. cptr->buffer = bptr;
  3068. queue_completion(&zh->completions_to_process, cptr, 0);
  3069. } else {
  3070. #ifdef THREADED
  3071. struct sync_completion
  3072. *sc = (struct sync_completion*)cptr->data;
  3073. sc->rc = rc;
  3074. process_sync_completion(zh, cptr, sc, ia);
  3075. notify_sync_completion(sc);
  3076. free_buffer(bptr);
  3077. zh->outstanding_sync--;
  3078. destroy_completion_entry(cptr);
  3079. #else
  3080. abort_singlethreaded(zh);
  3081. #endif
  3082. }
  3083. }
  3084. close_buffer_iarchive(&ia);
  3085. }
  3086. if (process_async(zh->outstanding_sync)) {
  3087. process_completions(zh);
  3088. }
  3089. return api_epilog(zh, ZOK);
  3090. }
  3091. int zoo_state(zhandle_t *zh)
  3092. {
  3093. if(zh!=0)
  3094. return zh->state;
  3095. return 0;
  3096. }
  3097. static watcher_registration_t* create_watcher_registration(const char* path,
  3098. result_checker_fn checker,watcher_fn watcher,void* ctx){
  3099. watcher_registration_t* wo;
  3100. if(watcher==0)
  3101. return 0;
  3102. wo=calloc(1,sizeof(watcher_registration_t));
  3103. wo->path=strdup(path);
  3104. wo->watcher=watcher;
  3105. wo->context=ctx;
  3106. wo->checker=checker;
  3107. return wo;
  3108. }
  3109. static watcher_deregistration_t* create_watcher_deregistration(const char* path,
  3110. watcher_fn watcher, void *watcherCtx, ZooWatcherType wtype) {
  3111. watcher_deregistration_t *wdo;
  3112. wdo = calloc(1, sizeof(watcher_deregistration_t));
  3113. if (!wdo) {
  3114. return NULL;
  3115. }
  3116. wdo->path = strdup(path);
  3117. wdo->watcher = watcher;
  3118. wdo->context = watcherCtx;
  3119. wdo->type = wtype;
  3120. return wdo;
  3121. }
  3122. static void destroy_watcher_registration(watcher_registration_t* wo){
  3123. if(wo!=0){
  3124. free((void*)wo->path);
  3125. free(wo);
  3126. }
  3127. }
  3128. static void destroy_watcher_deregistration(watcher_deregistration_t *wdo) {
  3129. if (wdo) {
  3130. free((void *)wdo->path);
  3131. free(wdo);
  3132. }
  3133. }
  3134. static completion_list_t* create_completion_entry(zhandle_t *zh, int xid, int completion_type,
  3135. const void *dc, const void *data,watcher_registration_t* wo, completion_head_t *clist)
  3136. {
  3137. return do_create_completion_entry(zh, xid, completion_type, dc, data, wo,
  3138. clist, NULL);
  3139. }
  3140. static completion_list_t* create_completion_entry_deregistration(zhandle_t *zh,
  3141. int xid, int completion_type, const void *dc, const void *data,
  3142. watcher_deregistration_t* wdo, completion_head_t *clist)
  3143. {
  3144. return do_create_completion_entry(zh, xid, completion_type, dc, data, NULL,
  3145. clist, wdo);
  3146. }
  3147. static completion_list_t* do_create_completion_entry(zhandle_t *zh, int xid,
  3148. int completion_type, const void *dc, const void *data,
  3149. watcher_registration_t* wo, completion_head_t *clist,
  3150. watcher_deregistration_t* wdo)
  3151. {
  3152. completion_list_t *c = calloc(1, sizeof(completion_list_t));
  3153. if (!c) {
  3154. LOG_ERROR(LOGCALLBACK(zh), "out of memory");
  3155. return 0;
  3156. }
  3157. c->c.type = completion_type;
  3158. c->data = data;
  3159. switch(c->c.type) {
  3160. case COMPLETION_VOID:
  3161. c->c.void_result = (void_completion_t)dc;
  3162. break;
  3163. case COMPLETION_STRING:
  3164. c->c.string_result = (string_completion_t)dc;
  3165. break;
  3166. case COMPLETION_DATA:
  3167. c->c.data_result = (data_completion_t)dc;
  3168. break;
  3169. case COMPLETION_STAT:
  3170. c->c.stat_result = (stat_completion_t)dc;
  3171. break;
  3172. case COMPLETION_STRINGLIST:
  3173. c->c.strings_result = (strings_completion_t)dc;
  3174. break;
  3175. case COMPLETION_STRINGLIST_STAT:
  3176. c->c.strings_stat_result = (strings_stat_completion_t)dc;
  3177. break;
  3178. case COMPLETION_STRING_STAT:
  3179. c->c.string_stat_result = (string_stat_completion_t)dc;
  3180. case COMPLETION_ACLLIST:
  3181. c->c.acl_result = (acl_completion_t)dc;
  3182. break;
  3183. case COMPLETION_MULTI:
  3184. assert(clist);
  3185. c->c.void_result = (void_completion_t)dc;
  3186. c->c.clist = *clist;
  3187. break;
  3188. }
  3189. c->xid = xid;
  3190. c->watcher = wo;
  3191. c->watcher_deregistration = wdo;
  3192. return c;
  3193. }
  3194. static void destroy_completion_entry(completion_list_t* c){
  3195. if(c!=0){
  3196. destroy_watcher_registration(c->watcher);
  3197. destroy_watcher_deregistration(c->watcher_deregistration);
  3198. if(c->buffer!=0)
  3199. free_buffer(c->buffer);
  3200. free(c);
  3201. }
  3202. }
  3203. static void queue_completion_nolock(completion_head_t *list,
  3204. completion_list_t *c,
  3205. int add_to_front)
  3206. {
  3207. c->next = 0;
  3208. /* appending a new entry to the back of the list */
  3209. if (list->last) {
  3210. assert(list->head);
  3211. // List is not empty
  3212. if (!add_to_front) {
  3213. list->last->next = c;
  3214. list->last = c;
  3215. } else {
  3216. c->next = list->head;
  3217. list->head = c;
  3218. }
  3219. } else {
  3220. // List is empty
  3221. assert(!list->head);
  3222. list->head = c;
  3223. list->last = c;
  3224. }
  3225. }
  3226. static void queue_completion(completion_head_t *list, completion_list_t *c,
  3227. int add_to_front)
  3228. {
  3229. lock_completion_list(list);
  3230. queue_completion_nolock(list, c, add_to_front);
  3231. unlock_completion_list(list);
  3232. }
  3233. static int add_completion(zhandle_t *zh, int xid, int completion_type,
  3234. const void *dc, const void *data, int add_to_front,
  3235. watcher_registration_t* wo, completion_head_t *clist)
  3236. {
  3237. completion_list_t *c =create_completion_entry(zh, xid, completion_type, dc,
  3238. data, wo, clist);
  3239. return do_add_completion(zh, dc, c, add_to_front);
  3240. }
  3241. static int add_completion_deregistration(zhandle_t *zh, int xid,
  3242. int completion_type, const void *dc, const void *data, int add_to_front,
  3243. watcher_deregistration_t* wdo, completion_head_t *clist)
  3244. {
  3245. completion_list_t *c = create_completion_entry_deregistration(zh, xid,
  3246. completion_type, dc, data, wdo, clist);
  3247. return do_add_completion(zh, dc, c, add_to_front);
  3248. }
  3249. static int do_add_completion(zhandle_t *zh, const void *dc,
  3250. completion_list_t *c, int add_to_front)
  3251. {
  3252. int rc = 0;
  3253. if (!c)
  3254. return ZSYSTEMERROR;
  3255. lock_completion_list(&zh->sent_requests);
  3256. if (zh->close_requested != 1) {
  3257. queue_completion_nolock(&zh->sent_requests, c, add_to_front);
  3258. if (dc == SYNCHRONOUS_MARKER) {
  3259. zh->outstanding_sync++;
  3260. }
  3261. rc = ZOK;
  3262. } else {
  3263. free(c);
  3264. rc = ZINVALIDSTATE;
  3265. }
  3266. unlock_completion_list(&zh->sent_requests);
  3267. return rc;
  3268. }
  3269. static int add_data_completion(zhandle_t *zh, int xid, data_completion_t dc,
  3270. const void *data,watcher_registration_t* wo)
  3271. {
  3272. return add_completion(zh, xid, COMPLETION_DATA, dc, data, 0, wo, 0);
  3273. }
  3274. static int add_stat_completion(zhandle_t *zh, int xid, stat_completion_t dc,
  3275. const void *data,watcher_registration_t* wo)
  3276. {
  3277. return add_completion(zh, xid, COMPLETION_STAT, dc, data, 0, wo, 0);
  3278. }
  3279. static int add_strings_completion(zhandle_t *zh, int xid,
  3280. strings_completion_t dc, const void *data,watcher_registration_t* wo)
  3281. {
  3282. return add_completion(zh, xid, COMPLETION_STRINGLIST, dc, data, 0, wo, 0);
  3283. }
  3284. static int add_strings_stat_completion(zhandle_t *zh, int xid,
  3285. strings_stat_completion_t dc, const void *data,watcher_registration_t* wo)
  3286. {
  3287. return add_completion(zh, xid, COMPLETION_STRINGLIST_STAT, dc, data, 0, wo, 0);
  3288. }
  3289. static int add_acl_completion(zhandle_t *zh, int xid, acl_completion_t dc,
  3290. const void *data)
  3291. {
  3292. return add_completion(zh, xid, COMPLETION_ACLLIST, dc, data, 0, 0, 0);
  3293. }
  3294. static int add_void_completion(zhandle_t *zh, int xid, void_completion_t dc,
  3295. const void *data)
  3296. {
  3297. return add_completion(zh, xid, COMPLETION_VOID, dc, data, 0, 0, 0);
  3298. }
  3299. static int add_string_completion(zhandle_t *zh, int xid,
  3300. string_completion_t dc, const void *data)
  3301. {
  3302. return add_completion(zh, xid, COMPLETION_STRING, dc, data, 0, 0, 0);
  3303. }
  3304. static int add_string_stat_completion(zhandle_t *zh, int xid,
  3305. string_stat_completion_t dc, const void *data)
  3306. {
  3307. return add_completion(zh, xid, COMPLETION_STRING_STAT, dc, data, 0, 0, 0);
  3308. }
  3309. static int add_multi_completion(zhandle_t *zh, int xid, void_completion_t dc,
  3310. const void *data, completion_head_t *clist)
  3311. {
  3312. return add_completion(zh, xid, COMPLETION_MULTI, dc, data, 0,0, clist);
  3313. }
  3314. /**
  3315. * After sending the close request, we are waiting for a given millisecs for
  3316. * getting the answer and/or for the socket to be closed by the server.
  3317. *
  3318. * This function should not be called while we still want to process
  3319. * any response from the server. It must be called after adaptor_finish called,
  3320. * in order not to mess with the I/O receiver thread in multi-threaded mode.
  3321. */
  3322. int wait_for_session_to_be_closed(zhandle_t *zh, int timeout_ms)
  3323. {
  3324. int ret = 0;
  3325. #ifndef WIN32
  3326. struct pollfd fd_s[1];
  3327. #else
  3328. fd_set rfds;
  3329. struct timeval waittime = {timeout_ms / 1000, (timeout_ms % 1000) * 1000};
  3330. #endif
  3331. if (zh == NULL) {
  3332. return ZBADARGUMENTS;
  3333. }
  3334. #ifndef WIN32
  3335. fd_s[0].fd = zh->fd->sock;
  3336. fd_s[0].events = POLLIN;
  3337. ret = poll(fd_s, 1, timeout_ms);
  3338. #else
  3339. FD_ZERO(&rfds);
  3340. FD_SET(zh->fd->sock , &rfds);
  3341. ret = select(zh->fd->sock + 1, &rfds, NULL, NULL, &waittime);
  3342. #endif
  3343. if (ret == 0){
  3344. LOG_WARN(LOGCALLBACK(zh), "Timed out (%dms) during waiting for server's reply after sending a close request, sessionId=%#llx\n",
  3345. timeout_ms, zh->client_id.client_id);
  3346. } else if (ret < 0) {
  3347. LOG_WARN(LOGCALLBACK(zh), "System error (%d) happened while waiting for server's reply, sessionId=%#llx\n",
  3348. ret, zh->client_id.client_id);
  3349. }
  3350. return ZOK;
  3351. }
  3352. int zookeeper_close(zhandle_t *zh)
  3353. {
  3354. int rc=ZOK;
  3355. if (zh==0)
  3356. return ZBADARGUMENTS;
  3357. zh->close_requested=1;
  3358. if (inc_ref_counter(zh,1)>1) {
  3359. /* We have incremented the ref counter to prevent the
  3360. * completions from calling zookeeper_close before we have
  3361. * completed the adaptor_finish call below. */
  3362. /* Signal any syncronous completions before joining the threads */
  3363. enter_critical(zh);
  3364. free_completions(zh,1,ZCLOSING);
  3365. leave_critical(zh);
  3366. adaptor_finish(zh);
  3367. /* Now we can allow the handle to be cleaned up, if the completion
  3368. * threads finished during the adaptor_finish call. */
  3369. api_epilog(zh, 0);
  3370. return ZOK;
  3371. }
  3372. /* No need to decrement the counter since we're just going to
  3373. * destroy the handle later. */
  3374. if (is_connected(zh)) {
  3375. struct oarchive *oa;
  3376. struct RequestHeader h = {get_xid(), ZOO_CLOSE_OP};
  3377. LOG_INFO(LOGCALLBACK(zh), "Closing zookeeper sessionId=%#llx to %s\n",
  3378. zh->client_id.client_id, zoo_get_current_server(zh));
  3379. oa = create_buffer_oarchive();
  3380. rc = serialize_RequestHeader(oa, "header", &h);
  3381. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa), get_buffer_len(oa));
  3382. /* We queued the buffer, so don't free it */
  3383. close_buffer_oarchive(&oa, 0);
  3384. if (rc < 0) {
  3385. LOG_DEBUG(LOGCALLBACK(zh), "Error during closing zookeeper session, sessionId=%#llx to %s (error: %d)\n",
  3386. zh->client_id.client_id, zoo_get_current_server(zh), rc);
  3387. rc = ZMARSHALLINGERROR;
  3388. } else {
  3389. /* make sure the close request is sent; we set timeout to an arbitrary
  3390. * (but reasonable) number of milliseconds since we want the call to block*/
  3391. rc = adaptor_send_queue(zh, 3000);
  3392. /* give some time to the server to process the session close request properly */
  3393. rc = rc < 0 ? rc : wait_for_session_to_be_closed(zh, 1500);
  3394. }
  3395. } else {
  3396. rc = ZOK;
  3397. }
  3398. LOG_INFO(LOGCALLBACK(zh), "Freeing zookeeper resources for sessionId=%#llx\n", zh->client_id.client_id);
  3399. destroy(zh);
  3400. adaptor_destroy(zh);
  3401. free(zh->fd);
  3402. free(zh);
  3403. #ifdef _WIN32
  3404. Win32WSACleanup();
  3405. #endif
  3406. return rc;
  3407. }
  3408. static int isValidPath(const char* path, const int mode) {
  3409. int len = 0;
  3410. char lastc = '/';
  3411. char c;
  3412. int i = 0;
  3413. if (path == 0)
  3414. return 0;
  3415. len = strlen(path);
  3416. if (len == 0)
  3417. return 0;
  3418. if (path[0] != '/')
  3419. return 0;
  3420. if (len == 1) // done checking - it's the root
  3421. return 1;
  3422. if (path[len - 1] == '/' && !ZOOKEEPER_IS_SEQUENCE(mode))
  3423. return 0;
  3424. i = 1;
  3425. for (; i < len; lastc = path[i], i++) {
  3426. c = path[i];
  3427. if (c == 0) {
  3428. return 0;
  3429. } else if (c == '/' && lastc == '/') {
  3430. return 0;
  3431. } else if (c == '.' && lastc == '.') {
  3432. if (path[i-2] == '/' && (((i + 1 == len) && !ZOOKEEPER_IS_SEQUENCE(mode))
  3433. || path[i+1] == '/')) {
  3434. return 0;
  3435. }
  3436. } else if (c == '.') {
  3437. if ((path[i-1] == '/') && (((i + 1 == len) && !ZOOKEEPER_IS_SEQUENCE(mode))
  3438. || path[i+1] == '/')) {
  3439. return 0;
  3440. }
  3441. } else if (c > 0x00 && c < 0x1f) {
  3442. return 0;
  3443. }
  3444. }
  3445. return 1;
  3446. }
  3447. /*---------------------------------------------------------------------------*
  3448. * REQUEST INIT HELPERS
  3449. *---------------------------------------------------------------------------*/
  3450. /* Common Request init helper functions to reduce code duplication */
  3451. static int Request_path_init(zhandle_t *zh, int mode,
  3452. char **path_out, const char *path)
  3453. {
  3454. assert(path_out);
  3455. *path_out = prepend_string(zh, path);
  3456. if (zh == NULL || !isValidPath(*path_out, mode)) {
  3457. free_duplicate_path(*path_out, path);
  3458. return ZBADARGUMENTS;
  3459. }
  3460. if (is_unrecoverable(zh)) {
  3461. free_duplicate_path(*path_out, path);
  3462. return ZINVALIDSTATE;
  3463. }
  3464. return ZOK;
  3465. }
  3466. static int Request_path_watch_init(zhandle_t *zh, int mode,
  3467. char **path_out, const char *path,
  3468. int32_t *watch_out, uint32_t watch)
  3469. {
  3470. int rc = Request_path_init(zh, mode, path_out, path);
  3471. if (rc != ZOK) {
  3472. return rc;
  3473. }
  3474. *watch_out = watch;
  3475. return ZOK;
  3476. }
  3477. /*---------------------------------------------------------------------------*
  3478. * ASYNC API
  3479. *---------------------------------------------------------------------------*/
  3480. int zoo_aget(zhandle_t *zh, const char *path, int watch, data_completion_t dc,
  3481. const void *data)
  3482. {
  3483. return zoo_awget(zh,path,watch?zh->watcher:0,zh->context,dc,data);
  3484. }
  3485. int zoo_awget(zhandle_t *zh, const char *path,
  3486. watcher_fn watcher, void* watcherCtx,
  3487. data_completion_t dc, const void *data)
  3488. {
  3489. struct oarchive *oa;
  3490. char *server_path = prepend_string(zh, path);
  3491. struct RequestHeader h = {get_xid(), ZOO_GETDATA_OP};
  3492. struct GetDataRequest req = { (char*)server_path, watcher!=0 };
  3493. int rc;
  3494. if (zh==0 || !isValidPath(server_path, 0)) {
  3495. free_duplicate_path(server_path, path);
  3496. return ZBADARGUMENTS;
  3497. }
  3498. if (is_unrecoverable(zh)) {
  3499. free_duplicate_path(server_path, path);
  3500. return ZINVALIDSTATE;
  3501. }
  3502. oa=create_buffer_oarchive();
  3503. rc = serialize_RequestHeader(oa, "header", &h);
  3504. rc = rc < 0 ? rc : serialize_GetDataRequest(oa, "req", &req);
  3505. enter_critical(zh);
  3506. rc = rc < 0 ? rc : add_data_completion(zh, h.xid, dc, data,
  3507. create_watcher_registration(server_path,data_result_checker,watcher,watcherCtx));
  3508. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3509. get_buffer_len(oa));
  3510. leave_critical(zh);
  3511. free_duplicate_path(server_path, path);
  3512. /* We queued the buffer, so don't free it */
  3513. close_buffer_oarchive(&oa, 0);
  3514. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3515. zoo_get_current_server(zh));
  3516. /* make a best (non-blocking) effort to send the requests asap */
  3517. adaptor_send_queue(zh, 0);
  3518. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3519. }
  3520. int zoo_agetconfig(zhandle_t *zh, int watch, data_completion_t dc,
  3521. const void *data)
  3522. {
  3523. return zoo_awgetconfig(zh,watch?zh->watcher:0,zh->context,dc,data);
  3524. }
  3525. int zoo_awgetconfig(zhandle_t *zh, watcher_fn watcher, void* watcherCtx,
  3526. data_completion_t dc, const void *data)
  3527. {
  3528. struct oarchive *oa;
  3529. char *path = ZOO_CONFIG_NODE;
  3530. char *server_path = ZOO_CONFIG_NODE;
  3531. struct RequestHeader h = { get_xid(), ZOO_GETDATA_OP };
  3532. struct GetDataRequest req = { (char*)server_path, watcher!=0 };
  3533. int rc;
  3534. if (zh==0 || !isValidPath(server_path, 0)) {
  3535. free_duplicate_path(server_path, path);
  3536. return ZBADARGUMENTS;
  3537. }
  3538. if (is_unrecoverable(zh)) {
  3539. free_duplicate_path(server_path, path);
  3540. return ZINVALIDSTATE;
  3541. }
  3542. oa=create_buffer_oarchive();
  3543. rc = serialize_RequestHeader(oa, "header", &h);
  3544. rc = rc < 0 ? rc : serialize_GetDataRequest(oa, "req", &req);
  3545. enter_critical(zh);
  3546. rc = rc < 0 ? rc : add_data_completion(zh, h.xid, dc, data,
  3547. create_watcher_registration(server_path,data_result_checker,watcher,watcherCtx));
  3548. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3549. get_buffer_len(oa));
  3550. leave_critical(zh);
  3551. free_duplicate_path(server_path, path);
  3552. /* We queued the buffer, so don't free it */
  3553. close_buffer_oarchive(&oa, 0);
  3554. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3555. zoo_get_current_server(zh));
  3556. /* make a best (non-blocking) effort to send the requests asap */
  3557. adaptor_send_queue(zh, 0);
  3558. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3559. }
  3560. int zoo_areconfig(zhandle_t *zh, const char *joining, const char *leaving,
  3561. const char *members, int64_t version, data_completion_t dc, const void *data)
  3562. {
  3563. struct oarchive *oa;
  3564. struct RequestHeader h = { get_xid(), ZOO_RECONFIG_OP };
  3565. struct ReconfigRequest req;
  3566. int rc = 0;
  3567. if (zh==0) {
  3568. return ZBADARGUMENTS;
  3569. }
  3570. if (is_unrecoverable(zh)) {
  3571. return ZINVALIDSTATE;
  3572. }
  3573. oa=create_buffer_oarchive();
  3574. req.joiningServers = (char *)joining;
  3575. req.leavingServers = (char *)leaving;
  3576. req.newMembers = (char *)members;
  3577. req.curConfigId = version;
  3578. rc = serialize_RequestHeader(oa, "header", &h);
  3579. rc = rc < 0 ? rc : serialize_ReconfigRequest(oa, "req", &req);
  3580. enter_critical(zh);
  3581. rc = rc < 0 ? rc : add_data_completion(zh, h.xid, dc, data, NULL);
  3582. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3583. get_buffer_len(oa));
  3584. leave_critical(zh);
  3585. /* We queued the buffer, so don't free it */
  3586. close_buffer_oarchive(&oa, 0);
  3587. LOG_DEBUG(LOGCALLBACK(zh), "Sending Reconfig request xid=%#x to %s",h.xid, zoo_get_current_server(zh));
  3588. /* make a best (non-blocking) effort to send the requests asap */
  3589. adaptor_send_queue(zh, 0);
  3590. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3591. }
  3592. static int SetDataRequest_init(zhandle_t *zh, struct SetDataRequest *req,
  3593. const char *path, const char *buffer, int buflen, int version)
  3594. {
  3595. int rc;
  3596. assert(req);
  3597. rc = Request_path_init(zh, 0, &req->path, path);
  3598. if (rc != ZOK) {
  3599. return rc;
  3600. }
  3601. req->data.buff = (char*)buffer;
  3602. req->data.len = buflen;
  3603. req->version = version;
  3604. return ZOK;
  3605. }
  3606. int zoo_aset(zhandle_t *zh, const char *path, const char *buffer, int buflen,
  3607. int version, stat_completion_t dc, const void *data)
  3608. {
  3609. struct oarchive *oa;
  3610. struct RequestHeader h = {get_xid(), ZOO_SETDATA_OP};
  3611. struct SetDataRequest req;
  3612. int rc = SetDataRequest_init(zh, &req, path, buffer, buflen, version);
  3613. if (rc != ZOK) {
  3614. return rc;
  3615. }
  3616. oa = create_buffer_oarchive();
  3617. rc = serialize_RequestHeader(oa, "header", &h);
  3618. rc = rc < 0 ? rc : serialize_SetDataRequest(oa, "req", &req);
  3619. enter_critical(zh);
  3620. rc = rc < 0 ? rc : add_stat_completion(zh, h.xid, dc, data,0);
  3621. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3622. get_buffer_len(oa));
  3623. leave_critical(zh);
  3624. free_duplicate_path(req.path, path);
  3625. /* We queued the buffer, so don't free it */
  3626. close_buffer_oarchive(&oa, 0);
  3627. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3628. zoo_get_current_server(zh));
  3629. /* make a best (non-blocking) effort to send the requests asap */
  3630. adaptor_send_queue(zh, 0);
  3631. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3632. }
  3633. static int CreateRequest_init(zhandle_t *zh, struct CreateRequest *req,
  3634. const char *path, const char *value,
  3635. int valuelen, const struct ACL_vector *acl_entries, int mode)
  3636. {
  3637. int rc;
  3638. assert(req);
  3639. rc = Request_path_init(zh, mode, &req->path, path);
  3640. assert(req);
  3641. if (rc != ZOK) {
  3642. return rc;
  3643. }
  3644. req->flags = mode;
  3645. req->data.buff = (char*)value;
  3646. req->data.len = valuelen;
  3647. if (acl_entries == 0) {
  3648. req->acl.count = 0;
  3649. req->acl.data = 0;
  3650. } else {
  3651. req->acl = *acl_entries;
  3652. }
  3653. return ZOK;
  3654. }
  3655. static int CreateTTLRequest_init(zhandle_t *zh, struct CreateTTLRequest *req,
  3656. const char *path, const char *value,
  3657. int valuelen, const struct ACL_vector *acl_entries, int mode, int64_t ttl)
  3658. {
  3659. int rc;
  3660. assert(req);
  3661. rc = Request_path_init(zh, mode, &req->path, path);
  3662. assert(req);
  3663. if (rc != ZOK) {
  3664. return rc;
  3665. }
  3666. req->flags = mode;
  3667. req->data.buff = (char*)value;
  3668. req->data.len = valuelen;
  3669. if (acl_entries == 0) {
  3670. req->acl.count = 0;
  3671. req->acl.data = 0;
  3672. } else {
  3673. req->acl = *acl_entries;
  3674. }
  3675. req->ttl = ttl;
  3676. return ZOK;
  3677. }
  3678. static int get_create_op_type(int mode, int default_op) {
  3679. if (mode == ZOO_CONTAINER) {
  3680. return ZOO_CREATE_CONTAINER_OP;
  3681. } else if (ZOOKEEPER_IS_TTL(mode)) {
  3682. return ZOO_CREATE_TTL_OP;
  3683. } else {
  3684. return default_op;
  3685. }
  3686. }
  3687. int zoo_acreate(zhandle_t *zh, const char *path, const char *value,
  3688. int valuelen, const struct ACL_vector *acl_entries, int mode,
  3689. string_completion_t completion, const void *data)
  3690. {
  3691. return zoo_acreate_ttl(zh, path, value, valuelen, acl_entries, mode, -1, completion, data);
  3692. }
  3693. int zoo_acreate_ttl(zhandle_t *zh, const char *path, const char *value,
  3694. int valuelen, const struct ACL_vector *acl_entries, int mode, int64_t ttl,
  3695. string_completion_t completion, const void *data)
  3696. {
  3697. struct oarchive *oa;
  3698. struct RequestHeader h = {get_xid(), get_create_op_type(mode, ZOO_CREATE_OP)};
  3699. int rc;
  3700. char *req_path;
  3701. if (ZOOKEEPER_IS_TTL(mode)) {
  3702. struct CreateTTLRequest req;
  3703. if (ttl <= 0 || ttl > ZOO_MAX_TTL) {
  3704. return ZBADARGUMENTS;
  3705. }
  3706. rc = CreateTTLRequest_init(zh, &req,
  3707. path, value, valuelen, acl_entries, mode, ttl);
  3708. if (rc != ZOK) {
  3709. return rc;
  3710. }
  3711. oa = create_buffer_oarchive();
  3712. rc = serialize_RequestHeader(oa, "header", &h);
  3713. rc = rc < 0 ? rc : serialize_CreateTTLRequest(oa, "req", &req);
  3714. req_path = req.path;
  3715. } else {
  3716. struct CreateRequest req;
  3717. if (ttl >= 0) {
  3718. return ZBADARGUMENTS;
  3719. }
  3720. rc = CreateRequest_init(zh, &req,
  3721. path, value, valuelen, acl_entries, mode);
  3722. if (rc != ZOK) {
  3723. return rc;
  3724. }
  3725. oa = create_buffer_oarchive();
  3726. rc = serialize_RequestHeader(oa, "header", &h);
  3727. rc = rc < 0 ? rc : serialize_CreateRequest(oa, "req", &req);
  3728. req_path = req.path;
  3729. }
  3730. enter_critical(zh);
  3731. rc = rc < 0 ? rc : add_string_completion(zh, h.xid, completion, data);
  3732. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3733. get_buffer_len(oa));
  3734. leave_critical(zh);
  3735. free_duplicate_path(req_path, path);
  3736. /* We queued the buffer, so don't free it */
  3737. close_buffer_oarchive(&oa, 0);
  3738. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3739. zoo_get_current_server(zh));
  3740. /* make a best (non-blocking) effort to send the requests asap */
  3741. adaptor_send_queue(zh, 0);
  3742. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3743. }
  3744. int zoo_acreate2(zhandle_t *zh, const char *path, const char *value,
  3745. int valuelen, const struct ACL_vector *acl_entries, int mode,
  3746. string_stat_completion_t completion, const void *data)
  3747. {
  3748. return zoo_acreate2_ttl(zh, path, value, valuelen, acl_entries, mode, -1, completion, data);
  3749. }
  3750. int zoo_acreate2_ttl(zhandle_t *zh, const char *path, const char *value,
  3751. int valuelen, const struct ACL_vector *acl_entries, int mode, int64_t ttl,
  3752. string_stat_completion_t completion, const void *data)
  3753. {
  3754. struct oarchive *oa;
  3755. struct RequestHeader h = { get_xid(), get_create_op_type(mode, ZOO_CREATE2_OP) };
  3756. int rc;
  3757. char *req_path;
  3758. if (ZOOKEEPER_IS_TTL(mode)) {
  3759. struct CreateTTLRequest req;
  3760. if (ttl <= 0 || ttl > ZOO_MAX_TTL) {
  3761. return ZBADARGUMENTS;
  3762. }
  3763. rc = CreateTTLRequest_init(zh, &req,
  3764. path, value, valuelen, acl_entries, mode, ttl);
  3765. if (rc != ZOK) {
  3766. return rc;
  3767. }
  3768. oa = create_buffer_oarchive();
  3769. rc = serialize_RequestHeader(oa, "header", &h);
  3770. rc = rc < 0 ? rc : serialize_CreateTTLRequest(oa, "req", &req);
  3771. req_path = req.path;
  3772. } else {
  3773. struct CreateRequest req;
  3774. if (ttl >= 0) {
  3775. return ZBADARGUMENTS;
  3776. }
  3777. rc = CreateRequest_init(zh, &req, path, value, valuelen, acl_entries, mode);
  3778. if (rc != ZOK) {
  3779. return rc;
  3780. }
  3781. oa = create_buffer_oarchive();
  3782. rc = serialize_RequestHeader(oa, "header", &h);
  3783. rc = rc < 0 ? rc : serialize_CreateRequest(oa, "req", &req);
  3784. req_path = req.path;
  3785. }
  3786. enter_critical(zh);
  3787. rc = rc < 0 ? rc : add_string_stat_completion(zh, h.xid, completion, data);
  3788. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3789. get_buffer_len(oa));
  3790. leave_critical(zh);
  3791. free_duplicate_path(req_path, path);
  3792. /* We queued the buffer, so don't free it */
  3793. close_buffer_oarchive(&oa, 0);
  3794. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3795. zoo_get_current_server(zh));
  3796. /* make a best (non-blocking) effort to send the requests asap */
  3797. adaptor_send_queue(zh, 0);
  3798. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3799. }
  3800. int DeleteRequest_init(zhandle_t *zh, struct DeleteRequest *req,
  3801. const char *path, int version)
  3802. {
  3803. int rc = Request_path_init(zh, 0, &req->path, path);
  3804. if (rc != ZOK) {
  3805. return rc;
  3806. }
  3807. req->version = version;
  3808. return ZOK;
  3809. }
  3810. int zoo_adelete(zhandle_t *zh, const char *path, int version,
  3811. void_completion_t completion, const void *data)
  3812. {
  3813. struct oarchive *oa;
  3814. struct RequestHeader h = {get_xid(), ZOO_DELETE_OP};
  3815. struct DeleteRequest req;
  3816. int rc = DeleteRequest_init(zh, &req, path, version);
  3817. if (rc != ZOK) {
  3818. return rc;
  3819. }
  3820. oa = create_buffer_oarchive();
  3821. rc = serialize_RequestHeader(oa, "header", &h);
  3822. rc = rc < 0 ? rc : serialize_DeleteRequest(oa, "req", &req);
  3823. enter_critical(zh);
  3824. rc = rc < 0 ? rc : add_void_completion(zh, h.xid, completion, data);
  3825. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3826. get_buffer_len(oa));
  3827. leave_critical(zh);
  3828. free_duplicate_path(req.path, path);
  3829. /* We queued the buffer, so don't free it */
  3830. close_buffer_oarchive(&oa, 0);
  3831. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3832. zoo_get_current_server(zh));
  3833. /* make a best (non-blocking) effort to send the requests asap */
  3834. adaptor_send_queue(zh, 0);
  3835. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3836. }
  3837. int zoo_aexists(zhandle_t *zh, const char *path, int watch,
  3838. stat_completion_t sc, const void *data)
  3839. {
  3840. return zoo_awexists(zh,path,watch?zh->watcher:0,zh->context,sc,data);
  3841. }
  3842. int zoo_awexists(zhandle_t *zh, const char *path,
  3843. watcher_fn watcher, void* watcherCtx,
  3844. stat_completion_t completion, const void *data)
  3845. {
  3846. struct oarchive *oa;
  3847. struct RequestHeader h = {get_xid(), ZOO_EXISTS_OP};
  3848. struct ExistsRequest req;
  3849. int rc = Request_path_watch_init(zh, 0, &req.path, path,
  3850. &req.watch, watcher != NULL);
  3851. if (rc != ZOK) {
  3852. return rc;
  3853. }
  3854. oa = create_buffer_oarchive();
  3855. rc = serialize_RequestHeader(oa, "header", &h);
  3856. rc = rc < 0 ? rc : serialize_ExistsRequest(oa, "req", &req);
  3857. enter_critical(zh);
  3858. rc = rc < 0 ? rc : add_stat_completion(zh, h.xid, completion, data,
  3859. create_watcher_registration(req.path,exists_result_checker,
  3860. watcher,watcherCtx));
  3861. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3862. get_buffer_len(oa));
  3863. leave_critical(zh);
  3864. free_duplicate_path(req.path, path);
  3865. /* We queued the buffer, so don't free it */
  3866. close_buffer_oarchive(&oa, 0);
  3867. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3868. zoo_get_current_server(zh));
  3869. /* make a best (non-blocking) effort to send the requests asap */
  3870. adaptor_send_queue(zh, 0);
  3871. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3872. }
  3873. static int zoo_awget_children_(zhandle_t *zh, const char *path,
  3874. watcher_fn watcher, void* watcherCtx,
  3875. strings_completion_t sc,
  3876. const void *data)
  3877. {
  3878. struct oarchive *oa;
  3879. struct RequestHeader h = {get_xid(), ZOO_GETCHILDREN_OP};
  3880. struct GetChildrenRequest req ;
  3881. int rc = Request_path_watch_init(zh, 0, &req.path, path,
  3882. &req.watch, watcher != NULL);
  3883. if (rc != ZOK) {
  3884. return rc;
  3885. }
  3886. oa = create_buffer_oarchive();
  3887. rc = serialize_RequestHeader(oa, "header", &h);
  3888. rc = rc < 0 ? rc : serialize_GetChildrenRequest(oa, "req", &req);
  3889. enter_critical(zh);
  3890. rc = rc < 0 ? rc : add_strings_completion(zh, h.xid, sc, data,
  3891. create_watcher_registration(req.path,child_result_checker,watcher,watcherCtx));
  3892. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3893. get_buffer_len(oa));
  3894. leave_critical(zh);
  3895. free_duplicate_path(req.path, path);
  3896. /* We queued the buffer, so don't free it */
  3897. close_buffer_oarchive(&oa, 0);
  3898. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3899. zoo_get_current_server(zh));
  3900. /* make a best (non-blocking) effort to send the requests asap */
  3901. adaptor_send_queue(zh, 0);
  3902. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3903. }
  3904. int zoo_aget_children(zhandle_t *zh, const char *path, int watch,
  3905. strings_completion_t dc, const void *data)
  3906. {
  3907. return zoo_awget_children_(zh,path,watch?zh->watcher:0,zh->context,dc,data);
  3908. }
  3909. int zoo_awget_children(zhandle_t *zh, const char *path,
  3910. watcher_fn watcher, void* watcherCtx,
  3911. strings_completion_t dc,
  3912. const void *data)
  3913. {
  3914. return zoo_awget_children_(zh,path,watcher,watcherCtx,dc,data);
  3915. }
  3916. static int zoo_awget_children2_(zhandle_t *zh, const char *path,
  3917. watcher_fn watcher, void* watcherCtx,
  3918. strings_stat_completion_t ssc,
  3919. const void *data)
  3920. {
  3921. /* invariant: (sc == NULL) != (sc == NULL) */
  3922. struct oarchive *oa;
  3923. struct RequestHeader h = {get_xid(), ZOO_GETCHILDREN2_OP};
  3924. struct GetChildren2Request req ;
  3925. int rc = Request_path_watch_init(zh, 0, &req.path, path,
  3926. &req.watch, watcher != NULL);
  3927. if (rc != ZOK) {
  3928. return rc;
  3929. }
  3930. oa = create_buffer_oarchive();
  3931. rc = serialize_RequestHeader(oa, "header", &h);
  3932. rc = rc < 0 ? rc : serialize_GetChildren2Request(oa, "req", &req);
  3933. enter_critical(zh);
  3934. rc = rc < 0 ? rc : add_strings_stat_completion(zh, h.xid, ssc, data,
  3935. create_watcher_registration(req.path,child_result_checker,watcher,watcherCtx));
  3936. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3937. get_buffer_len(oa));
  3938. leave_critical(zh);
  3939. free_duplicate_path(req.path, path);
  3940. /* We queued the buffer, so don't free it */
  3941. close_buffer_oarchive(&oa, 0);
  3942. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3943. zoo_get_current_server(zh));
  3944. /* make a best (non-blocking) effort to send the requests asap */
  3945. adaptor_send_queue(zh, 0);
  3946. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3947. }
  3948. int zoo_aget_children2(zhandle_t *zh, const char *path, int watch,
  3949. strings_stat_completion_t dc, const void *data)
  3950. {
  3951. return zoo_awget_children2_(zh,path,watch?zh->watcher:0,zh->context,dc,data);
  3952. }
  3953. int zoo_awget_children2(zhandle_t *zh, const char *path,
  3954. watcher_fn watcher, void* watcherCtx,
  3955. strings_stat_completion_t dc,
  3956. const void *data)
  3957. {
  3958. return zoo_awget_children2_(zh,path,watcher,watcherCtx,dc,data);
  3959. }
  3960. int zoo_async(zhandle_t *zh, const char *path,
  3961. string_completion_t completion, const void *data)
  3962. {
  3963. struct oarchive *oa;
  3964. struct RequestHeader h = {get_xid(), ZOO_SYNC_OP};
  3965. struct SyncRequest req;
  3966. int rc = Request_path_init(zh, 0, &req.path, path);
  3967. if (rc != ZOK) {
  3968. return rc;
  3969. }
  3970. oa = create_buffer_oarchive();
  3971. rc = serialize_RequestHeader(oa, "header", &h);
  3972. rc = rc < 0 ? rc : serialize_SyncRequest(oa, "req", &req);
  3973. enter_critical(zh);
  3974. rc = rc < 0 ? rc : add_string_completion(zh, h.xid, completion, data);
  3975. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  3976. get_buffer_len(oa));
  3977. leave_critical(zh);
  3978. free_duplicate_path(req.path, path);
  3979. /* We queued the buffer, so don't free it */
  3980. close_buffer_oarchive(&oa, 0);
  3981. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  3982. zoo_get_current_server(zh));
  3983. /* make a best (non-blocking) effort to send the requests asap */
  3984. adaptor_send_queue(zh, 0);
  3985. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  3986. }
  3987. int zoo_aget_acl(zhandle_t *zh, const char *path, acl_completion_t completion,
  3988. const void *data)
  3989. {
  3990. struct oarchive *oa;
  3991. struct RequestHeader h = {get_xid(), ZOO_GETACL_OP};
  3992. struct GetACLRequest req;
  3993. int rc = Request_path_init(zh, 0, &req.path, path) ;
  3994. if (rc != ZOK) {
  3995. return rc;
  3996. }
  3997. oa = create_buffer_oarchive();
  3998. rc = serialize_RequestHeader(oa, "header", &h);
  3999. rc = rc < 0 ? rc : serialize_GetACLRequest(oa, "req", &req);
  4000. enter_critical(zh);
  4001. rc = rc < 0 ? rc : add_acl_completion(zh, h.xid, completion, data);
  4002. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  4003. get_buffer_len(oa));
  4004. leave_critical(zh);
  4005. free_duplicate_path(req.path, path);
  4006. /* We queued the buffer, so don't free it */
  4007. close_buffer_oarchive(&oa, 0);
  4008. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  4009. zoo_get_current_server(zh));
  4010. /* make a best (non-blocking) effort to send the requests asap */
  4011. adaptor_send_queue(zh, 0);
  4012. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  4013. }
  4014. int zoo_aset_acl(zhandle_t *zh, const char *path, int version,
  4015. struct ACL_vector *acl, void_completion_t completion, const void *data)
  4016. {
  4017. struct oarchive *oa;
  4018. struct RequestHeader h = {get_xid(), ZOO_SETACL_OP};
  4019. struct SetACLRequest req;
  4020. int rc = Request_path_init(zh, 0, &req.path, path);
  4021. if (rc != ZOK) {
  4022. return rc;
  4023. }
  4024. oa = create_buffer_oarchive();
  4025. req.acl = *acl;
  4026. req.version = version;
  4027. rc = serialize_RequestHeader(oa, "header", &h);
  4028. rc = rc < 0 ? rc : serialize_SetACLRequest(oa, "req", &req);
  4029. enter_critical(zh);
  4030. rc = rc < 0 ? rc : add_void_completion(zh, h.xid, completion, data);
  4031. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  4032. get_buffer_len(oa));
  4033. leave_critical(zh);
  4034. free_duplicate_path(req.path, path);
  4035. /* We queued the buffer, so don't free it */
  4036. close_buffer_oarchive(&oa, 0);
  4037. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",h.xid,path,
  4038. zoo_get_current_server(zh));
  4039. /* make a best (non-blocking) effort to send the requests asap */
  4040. adaptor_send_queue(zh, 0);
  4041. return (rc < 0)?ZMARSHALLINGERROR:ZOK;
  4042. }
  4043. /* Completions for multi-op results */
  4044. static void op_result_string_completion(int err, const char *value, const void *data)
  4045. {
  4046. struct zoo_op_result *result = (struct zoo_op_result *)data;
  4047. assert(result);
  4048. result->err = err;
  4049. if (result->value && value) {
  4050. int len = strlen(value) + 1;
  4051. if (len > result->valuelen) {
  4052. len = result->valuelen;
  4053. }
  4054. if (len > 0) {
  4055. memcpy(result->value, value, len - 1);
  4056. result->value[len - 1] = '\0';
  4057. }
  4058. } else {
  4059. result->value = NULL;
  4060. }
  4061. }
  4062. static void op_result_void_completion(int err, const void *data)
  4063. {
  4064. struct zoo_op_result *result = (struct zoo_op_result *)data;
  4065. assert(result);
  4066. result->err = err;
  4067. }
  4068. static void op_result_stat_completion(int err, const struct Stat *stat, const void *data)
  4069. {
  4070. struct zoo_op_result *result = (struct zoo_op_result *)data;
  4071. assert(result);
  4072. result->err = err;
  4073. if (result->stat && err == 0 && stat) {
  4074. *result->stat = *stat;
  4075. } else {
  4076. result->stat = NULL ;
  4077. }
  4078. }
  4079. static int CheckVersionRequest_init(zhandle_t *zh, struct CheckVersionRequest *req,
  4080. const char *path, int version)
  4081. {
  4082. int rc ;
  4083. assert(req);
  4084. rc = Request_path_init(zh, 0, &req->path, path);
  4085. if (rc != ZOK) {
  4086. return rc;
  4087. }
  4088. req->version = version;
  4089. return ZOK;
  4090. }
  4091. int zoo_amulti(zhandle_t *zh, int count, const zoo_op_t *ops,
  4092. zoo_op_result_t *results, void_completion_t completion, const void *data)
  4093. {
  4094. struct RequestHeader h = {get_xid(), ZOO_MULTI_OP};
  4095. struct MultiHeader mh = {-1, 1, -1};
  4096. struct oarchive *oa = create_buffer_oarchive();
  4097. completion_head_t clist = { 0 };
  4098. int rc = serialize_RequestHeader(oa, "header", &h);
  4099. int index = 0;
  4100. for (index=0; index < count; index++) {
  4101. const zoo_op_t *op = ops+index;
  4102. zoo_op_result_t *result = results+index;
  4103. completion_list_t *entry = NULL;
  4104. struct MultiHeader mh = {op->type, 0, -1};
  4105. rc = rc < 0 ? rc : serialize_MultiHeader(oa, "multiheader", &mh);
  4106. switch(op->type) {
  4107. case ZOO_CREATE_CONTAINER_OP:
  4108. case ZOO_CREATE_OP: {
  4109. struct CreateRequest req;
  4110. rc = rc < 0 ? rc : CreateRequest_init(zh, &req,
  4111. op->create_op.path, op->create_op.data,
  4112. op->create_op.datalen, op->create_op.acl,
  4113. op->create_op.flags);
  4114. rc = rc < 0 ? rc : serialize_CreateRequest(oa, "req", &req);
  4115. result->value = op->create_op.buf;
  4116. result->valuelen = op->create_op.buflen;
  4117. enter_critical(zh);
  4118. entry = create_completion_entry(zh, h.xid, COMPLETION_STRING, op_result_string_completion, result, 0, 0);
  4119. leave_critical(zh);
  4120. free_duplicate_path(req.path, op->create_op.path);
  4121. break;
  4122. }
  4123. case ZOO_DELETE_OP: {
  4124. struct DeleteRequest req;
  4125. rc = rc < 0 ? rc : DeleteRequest_init(zh, &req, op->delete_op.path, op->delete_op.version);
  4126. rc = rc < 0 ? rc : serialize_DeleteRequest(oa, "req", &req);
  4127. enter_critical(zh);
  4128. entry = create_completion_entry(zh, h.xid, COMPLETION_VOID, op_result_void_completion, result, 0, 0);
  4129. leave_critical(zh);
  4130. free_duplicate_path(req.path, op->delete_op.path);
  4131. break;
  4132. }
  4133. case ZOO_SETDATA_OP: {
  4134. struct SetDataRequest req;
  4135. rc = rc < 0 ? rc : SetDataRequest_init(zh, &req,
  4136. op->set_op.path, op->set_op.data,
  4137. op->set_op.datalen, op->set_op.version);
  4138. rc = rc < 0 ? rc : serialize_SetDataRequest(oa, "req", &req);
  4139. result->stat = op->set_op.stat;
  4140. enter_critical(zh);
  4141. entry = create_completion_entry(zh, h.xid, COMPLETION_STAT, op_result_stat_completion, result, 0, 0);
  4142. leave_critical(zh);
  4143. free_duplicate_path(req.path, op->set_op.path);
  4144. break;
  4145. }
  4146. case ZOO_CHECK_OP: {
  4147. struct CheckVersionRequest req;
  4148. rc = rc < 0 ? rc : CheckVersionRequest_init(zh, &req,
  4149. op->check_op.path, op->check_op.version);
  4150. rc = rc < 0 ? rc : serialize_CheckVersionRequest(oa, "req", &req);
  4151. enter_critical(zh);
  4152. entry = create_completion_entry(zh, h.xid, COMPLETION_VOID, op_result_void_completion, result, 0, 0);
  4153. leave_critical(zh);
  4154. free_duplicate_path(req.path, op->check_op.path);
  4155. break;
  4156. }
  4157. default:
  4158. LOG_ERROR(LOGCALLBACK(zh), "Unimplemented sub-op type=%d in multi-op", op->type);
  4159. return ZUNIMPLEMENTED;
  4160. }
  4161. queue_completion(&clist, entry, 0);
  4162. }
  4163. rc = rc < 0 ? rc : serialize_MultiHeader(oa, "multiheader", &mh);
  4164. /* BEGIN: CRTICIAL SECTION */
  4165. enter_critical(zh);
  4166. rc = rc < 0 ? rc : add_multi_completion(zh, h.xid, completion, data, &clist);
  4167. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  4168. get_buffer_len(oa));
  4169. leave_critical(zh);
  4170. /* We queued the buffer, so don't free it */
  4171. close_buffer_oarchive(&oa, 0);
  4172. LOG_DEBUG(LOGCALLBACK(zh), "Sending multi request xid=%#x with %d subrequests to %s",
  4173. h.xid, index, zoo_get_current_server(zh));
  4174. /* make a best (non-blocking) effort to send the requests asap */
  4175. adaptor_send_queue(zh, 0);
  4176. return (rc < 0) ? ZMARSHALLINGERROR : ZOK;
  4177. }
  4178. typedef union WatchesRequest WatchesRequest;
  4179. union WatchesRequest {
  4180. struct CheckWatchesRequest check;
  4181. struct RemoveWatchesRequest remove;
  4182. };
  4183. static int aremove_watches(
  4184. zhandle_t *zh, const char *path, ZooWatcherType wtype,
  4185. watcher_fn watcher, void *watcherCtx, int local,
  4186. void_completion_t *completion, const void *data, int all)
  4187. {
  4188. char *server_path = prepend_string(zh, path);
  4189. int rc;
  4190. struct oarchive *oa;
  4191. struct RequestHeader h = {
  4192. get_xid(),
  4193. all ? ZOO_REMOVE_WATCHES : ZOO_CHECK_WATCHES
  4194. };
  4195. WatchesRequest req;
  4196. watcher_deregistration_t *wdo;
  4197. if (!zh || !isValidPath(server_path, 0)) {
  4198. rc = ZBADARGUMENTS;
  4199. goto done;
  4200. }
  4201. if (!local && is_unrecoverable(zh)) {
  4202. rc = ZINVALIDSTATE;
  4203. goto done;
  4204. }
  4205. if (!pathHasWatcher(zh, server_path, wtype, watcher, watcherCtx)) {
  4206. rc = ZNOWATCHER;
  4207. goto done;
  4208. }
  4209. if (local) {
  4210. removeWatchers(zh, server_path, wtype, watcher, watcherCtx);
  4211. #ifdef THREADED
  4212. notify_sync_completion((struct sync_completion *)data);
  4213. #endif
  4214. rc = ZOK;
  4215. goto done;
  4216. }
  4217. oa = create_buffer_oarchive();
  4218. rc = serialize_RequestHeader(oa, "header", &h);
  4219. if (all) {
  4220. req.remove.path = (char*)server_path;
  4221. req.remove.type = wtype;
  4222. rc = rc < 0 ? rc : serialize_RemoveWatchesRequest(oa, "req", &req.remove);
  4223. } else {
  4224. req.check.path = (char*)server_path;
  4225. req.check.type = wtype;
  4226. rc = rc < 0 ? rc : serialize_CheckWatchesRequest(oa, "req", &req.check);
  4227. }
  4228. if (rc < 0) {
  4229. goto done;
  4230. }
  4231. wdo = create_watcher_deregistration(
  4232. server_path, watcher, watcherCtx, wtype);
  4233. if (!wdo) {
  4234. rc = ZSYSTEMERROR;
  4235. goto done;
  4236. }
  4237. enter_critical(zh);
  4238. rc = add_completion_deregistration(
  4239. zh, h.xid, COMPLETION_VOID, completion, data, 0, wdo, 0);
  4240. rc = rc < 0 ? rc : queue_buffer_bytes(&zh->to_send, get_buffer(oa),
  4241. get_buffer_len(oa));
  4242. rc = rc < 0 ? ZMARSHALLINGERROR : ZOK;
  4243. leave_critical(zh);
  4244. /* We queued the buffer, so don't free it */
  4245. close_buffer_oarchive(&oa, 0);
  4246. LOG_DEBUG(LOGCALLBACK(zh), "Sending request xid=%#x for path [%s] to %s",
  4247. h.xid, path, zoo_get_current_server(zh));
  4248. adaptor_send_queue(zh, 0);
  4249. done:
  4250. free_duplicate_path(server_path, path);
  4251. return rc;
  4252. }
  4253. void zoo_create_op_init(zoo_op_t *op, const char *path, const char *value,
  4254. int valuelen, const struct ACL_vector *acl, int mode,
  4255. char *path_buffer, int path_buffer_len)
  4256. {
  4257. assert(op);
  4258. op->type = get_create_op_type(mode, ZOO_CREATE_OP);
  4259. op->create_op.path = path;
  4260. op->create_op.data = value;
  4261. op->create_op.datalen = valuelen;
  4262. op->create_op.acl = acl;
  4263. op->create_op.flags = mode;
  4264. op->create_op.ttl = 0;
  4265. op->create_op.buf = path_buffer;
  4266. op->create_op.buflen = path_buffer_len;
  4267. }
  4268. void zoo_create2_op_init(zoo_op_t *op, const char *path, const char *value,
  4269. int valuelen, const struct ACL_vector *acl, int mode,
  4270. char *path_buffer, int path_buffer_len)
  4271. {
  4272. assert(op);
  4273. op->type = get_create_op_type(mode, ZOO_CREATE2_OP);
  4274. op->create_op.path = path;
  4275. op->create_op.data = value;
  4276. op->create_op.datalen = valuelen;
  4277. op->create_op.acl = acl;
  4278. op->create_op.flags = mode;
  4279. op->create_op.buf = path_buffer;
  4280. op->create_op.buflen = path_buffer_len;
  4281. }
  4282. void zoo_delete_op_init(zoo_op_t *op, const char *path, int version)
  4283. {
  4284. assert(op);
  4285. op->type = ZOO_DELETE_OP;
  4286. op->delete_op.path = path;
  4287. op->delete_op.version = version;
  4288. }
  4289. void zoo_set_op_init(zoo_op_t *op, const char *path, const char *buffer,
  4290. int buflen, int version, struct Stat *stat)
  4291. {
  4292. assert(op);
  4293. op->type = ZOO_SETDATA_OP;
  4294. op->set_op.path = path;
  4295. op->set_op.data = buffer;
  4296. op->set_op.datalen = buflen;
  4297. op->set_op.version = version;
  4298. op->set_op.stat = stat;
  4299. }
  4300. void zoo_check_op_init(zoo_op_t *op, const char *path, int version)
  4301. {
  4302. assert(op);
  4303. op->type = ZOO_CHECK_OP;
  4304. op->check_op.path = path;
  4305. op->check_op.version = version;
  4306. }
  4307. /* specify timeout of 0 to make the function non-blocking */
  4308. /* timeout is in milliseconds */
  4309. int flush_send_queue(zhandle_t*zh, int timeout)
  4310. {
  4311. int rc= ZOK;
  4312. struct timeval started;
  4313. #ifdef _WIN32
  4314. fd_set pollSet;
  4315. struct timeval wait;
  4316. #endif
  4317. get_system_time(&started);
  4318. // we can't use dequeue_buffer() here because if (non-blocking) send_buffer()
  4319. // returns EWOULDBLOCK we'd have to put the buffer back on the queue.
  4320. // we use a recursive lock instead and only dequeue the buffer if a send was
  4321. // successful
  4322. lock_buffer_list(&zh->to_send);
  4323. while (zh->to_send.head != 0 && (is_connected(zh) || is_sasl_auth_in_progress(zh))) {
  4324. if(timeout!=0){
  4325. #ifndef _WIN32
  4326. struct pollfd fds;
  4327. #endif
  4328. int elapsed;
  4329. struct timeval now;
  4330. get_system_time(&now);
  4331. elapsed=calculate_interval(&started,&now);
  4332. if (elapsed>timeout) {
  4333. rc = ZOPERATIONTIMEOUT;
  4334. break;
  4335. }
  4336. #ifdef _WIN32
  4337. wait = get_timeval(timeout-elapsed);
  4338. FD_ZERO(&pollSet);
  4339. FD_SET(zh->fd->sock, &pollSet);
  4340. // Poll the socket
  4341. rc = select((int)(zh->fd->sock)+1, NULL, &pollSet, NULL, &wait);
  4342. #else
  4343. fds.fd = zh->fd->sock;
  4344. fds.events = POLLOUT;
  4345. fds.revents = 0;
  4346. rc = poll(&fds, 1, timeout-elapsed);
  4347. #endif
  4348. if (rc<=0) {
  4349. /* timed out or an error or POLLERR */
  4350. rc = rc==0 ? ZOPERATIONTIMEOUT : ZSYSTEMERROR;
  4351. break;
  4352. }
  4353. }
  4354. rc = send_buffer(zh, zh->to_send.head);
  4355. if(rc==0 && timeout==0){
  4356. /* send_buffer would block while sending this buffer */
  4357. rc = ZOK;
  4358. break;
  4359. }
  4360. if (rc < 0) {
  4361. rc = ZCONNECTIONLOSS;
  4362. break;
  4363. }
  4364. // if the buffer has been sent successfully, remove it from the queue
  4365. if (rc > 0)
  4366. remove_buffer(&zh->to_send);
  4367. get_system_time(&zh->last_send);
  4368. rc = ZOK;
  4369. }
  4370. unlock_buffer_list(&zh->to_send);
  4371. return rc;
  4372. }
  4373. const char* zerror(int c)
  4374. {
  4375. switch (c){
  4376. case ZOK:
  4377. return "ok";
  4378. case ZSYSTEMERROR:
  4379. return "system error";
  4380. case ZRUNTIMEINCONSISTENCY:
  4381. return "run time inconsistency";
  4382. case ZDATAINCONSISTENCY:
  4383. return "data inconsistency";
  4384. case ZCONNECTIONLOSS:
  4385. return "connection loss";
  4386. case ZMARSHALLINGERROR:
  4387. return "marshalling error";
  4388. case ZUNIMPLEMENTED:
  4389. return "unimplemented";
  4390. case ZOPERATIONTIMEOUT:
  4391. return "operation timeout";
  4392. case ZBADARGUMENTS:
  4393. return "bad arguments";
  4394. case ZINVALIDSTATE:
  4395. return "invalid zhandle state";
  4396. case ZNEWCONFIGNOQUORUM:
  4397. return "no quorum of new config is connected and up-to-date with the leader of last commmitted config - try invoking reconfiguration after new servers are connected and synced";
  4398. case ZRECONFIGINPROGRESS:
  4399. return "Another reconfiguration is in progress -- concurrent reconfigs not supported (yet)";
  4400. case ZAPIERROR:
  4401. return "api error";
  4402. case ZNONODE:
  4403. return "no node";
  4404. case ZNOAUTH:
  4405. return "not authenticated";
  4406. case ZBADVERSION:
  4407. return "bad version";
  4408. case ZNOCHILDRENFOREPHEMERALS:
  4409. return "no children for ephemerals";
  4410. case ZNODEEXISTS:
  4411. return "node exists";
  4412. case ZNOTEMPTY:
  4413. return "not empty";
  4414. case ZSESSIONEXPIRED:
  4415. return "session expired";
  4416. case ZINVALIDCALLBACK:
  4417. return "invalid callback";
  4418. case ZINVALIDACL:
  4419. return "invalid acl";
  4420. case ZAUTHFAILED:
  4421. return "authentication failed";
  4422. case ZCLOSING:
  4423. return "zookeeper is closing";
  4424. case ZNOTHING:
  4425. return "(not error) no server responses to process";
  4426. case ZSESSIONMOVED:
  4427. return "session moved to another server, so operation is ignored";
  4428. case ZNOTREADONLY:
  4429. return "state-changing request is passed to read-only server";
  4430. case ZEPHEMERALONLOCALSESSION:
  4431. return "attempt to create ephemeral node on a local session";
  4432. case ZNOWATCHER:
  4433. return "the watcher couldn't be found";
  4434. case ZRECONFIGDISABLED:
  4435. return "attempts to perform a reconfiguration operation when reconfiguration feature is disable";
  4436. case ZTHROTTLEDOP:
  4437. return "Operation was throttled due to high load";
  4438. }
  4439. if (c > 0) {
  4440. return strerror(c);
  4441. }
  4442. return "unknown error";
  4443. }
  4444. int zoo_add_auth(zhandle_t *zh,const char* scheme,const char* cert,
  4445. int certLen,void_completion_t completion, const void *data)
  4446. {
  4447. struct buffer auth;
  4448. auth_info *authinfo;
  4449. if(scheme==NULL || zh==NULL)
  4450. return ZBADARGUMENTS;
  4451. if (is_unrecoverable(zh))
  4452. return ZINVALIDSTATE;
  4453. // [ZOOKEEPER-800] zoo_add_auth should return ZINVALIDSTATE if
  4454. // the connection is closed.
  4455. if (zoo_state(zh) == 0) {
  4456. return ZINVALIDSTATE;
  4457. }
  4458. if(cert!=NULL && certLen!=0){
  4459. auth.buff=calloc(1,certLen);
  4460. if(auth.buff==0) {
  4461. return ZSYSTEMERROR;
  4462. }
  4463. memcpy(auth.buff,cert,certLen);
  4464. auth.len=certLen;
  4465. } else {
  4466. auth.buff = 0;
  4467. auth.len = 0;
  4468. }
  4469. zoo_lock_auth(zh);
  4470. authinfo = (auth_info*) malloc(sizeof(auth_info));
  4471. authinfo->scheme=strdup(scheme);
  4472. authinfo->auth=auth;
  4473. authinfo->completion=completion;
  4474. authinfo->data=data;
  4475. authinfo->next = NULL;
  4476. add_last_auth(&zh->auth_h, authinfo);
  4477. zoo_unlock_auth(zh);
  4478. if (is_connected(zh) || zh->state == ZOO_ASSOCIATING_STATE)
  4479. return send_last_auth_info(zh);
  4480. return ZOK;
  4481. }
  4482. static const char* format_endpoint_info(const struct sockaddr_storage* ep)
  4483. {
  4484. static char buf[134] = { 0 };
  4485. char addrstr[INET6_ADDRSTRLEN] = { 0 };
  4486. const char *fmtstring;
  4487. void *inaddr;
  4488. char is_inet6 = 0; // poor man's boolean
  4489. #ifdef _WIN32
  4490. char * addrstring;
  4491. #endif
  4492. int port;
  4493. if(ep==0)
  4494. return "null";
  4495. #if defined(AF_INET6)
  4496. if(ep->ss_family==AF_INET6){
  4497. inaddr=&((struct sockaddr_in6*)ep)->sin6_addr;
  4498. port=((struct sockaddr_in6*)ep)->sin6_port;
  4499. is_inet6 = 1;
  4500. } else {
  4501. #endif
  4502. inaddr=&((struct sockaddr_in*)ep)->sin_addr;
  4503. port=((struct sockaddr_in*)ep)->sin_port;
  4504. #if defined(AF_INET6)
  4505. }
  4506. #endif
  4507. fmtstring = (is_inet6 ? "[%s]:%d" : "%s:%d");
  4508. #ifdef _WIN32
  4509. addrstring = inet_ntoa (*(struct in_addr*)inaddr);
  4510. sprintf(buf,fmtstring,addrstring,ntohs(port));
  4511. #else
  4512. inet_ntop(ep->ss_family,inaddr,addrstr,sizeof(addrstr)-1);
  4513. sprintf(buf,fmtstring,addrstr,ntohs(port));
  4514. #endif
  4515. return buf;
  4516. }
  4517. log_callback_fn zoo_get_log_callback(const zhandle_t* zh)
  4518. {
  4519. // Verify we have a valid handle
  4520. if (zh == NULL) {
  4521. return NULL;
  4522. }
  4523. return zh->log_callback;
  4524. }
  4525. void zoo_set_log_callback(zhandle_t *zh, log_callback_fn callback)
  4526. {
  4527. // Verify we have a valid handle
  4528. if (zh == NULL) {
  4529. return;
  4530. }
  4531. zh->log_callback = callback;
  4532. }
  4533. void zoo_deterministic_conn_order(int yesOrNo)
  4534. {
  4535. disable_conn_permute=yesOrNo;
  4536. }
  4537. #ifdef THREADED
  4538. static void process_sync_completion(zhandle_t *zh,
  4539. completion_list_t *cptr,
  4540. struct sync_completion *sc,
  4541. struct iarchive *ia)
  4542. {
  4543. LOG_DEBUG(LOGCALLBACK(zh), "Processing sync_completion with type=%d xid=%#x rc=%d",
  4544. cptr->c.type, cptr->xid, sc->rc);
  4545. switch(cptr->c.type) {
  4546. case COMPLETION_DATA:
  4547. if (sc->rc==0) {
  4548. struct GetDataResponse res;
  4549. int len;
  4550. deserialize_GetDataResponse(ia, "reply", &res);
  4551. if (res.data.len <= sc->u.data.buff_len) {
  4552. len = res.data.len;
  4553. } else {
  4554. len = sc->u.data.buff_len;
  4555. }
  4556. sc->u.data.buff_len = len;
  4557. // check if len is negative
  4558. // just of NULL which is -1 int
  4559. if (len == -1) {
  4560. sc->u.data.buffer = NULL;
  4561. } else {
  4562. memcpy(sc->u.data.buffer, res.data.buff, len);
  4563. }
  4564. sc->u.data.stat = res.stat;
  4565. deallocate_GetDataResponse(&res);
  4566. }
  4567. break;
  4568. case COMPLETION_STAT:
  4569. if (sc->rc==0) {
  4570. struct SetDataResponse res;
  4571. deserialize_SetDataResponse(ia, "reply", &res);
  4572. sc->u.stat = res.stat;
  4573. deallocate_SetDataResponse(&res);
  4574. }
  4575. break;
  4576. case COMPLETION_STRINGLIST:
  4577. if (sc->rc==0) {
  4578. struct GetChildrenResponse res;
  4579. deserialize_GetChildrenResponse(ia, "reply", &res);
  4580. sc->u.strs2 = res.children;
  4581. /* We don't deallocate since we are passing it back */
  4582. // deallocate_GetChildrenResponse(&res);
  4583. }
  4584. break;
  4585. case COMPLETION_STRINGLIST_STAT:
  4586. if (sc->rc==0) {
  4587. struct GetChildren2Response res;
  4588. deserialize_GetChildren2Response(ia, "reply", &res);
  4589. sc->u.strs_stat.strs2 = res.children;
  4590. sc->u.strs_stat.stat2 = res.stat;
  4591. /* We don't deallocate since we are passing it back */
  4592. // deallocate_GetChildren2Response(&res);
  4593. }
  4594. break;
  4595. case COMPLETION_STRING:
  4596. if (sc->rc==0) {
  4597. struct CreateResponse res;
  4598. int len;
  4599. const char * client_path;
  4600. deserialize_CreateResponse(ia, "reply", &res);
  4601. //ZOOKEEPER-1027
  4602. client_path = sub_string(zh, res.path);
  4603. len = strlen(client_path) + 1;if (len > sc->u.str.str_len) {
  4604. len = sc->u.str.str_len;
  4605. }
  4606. if (len > 0) {
  4607. memcpy(sc->u.str.str, client_path, len - 1);
  4608. sc->u.str.str[len - 1] = '\0';
  4609. }
  4610. free_duplicate_path(client_path, res.path);
  4611. deallocate_CreateResponse(&res);
  4612. }
  4613. break;
  4614. case COMPLETION_STRING_STAT:
  4615. if (sc->rc==0) {
  4616. struct Create2Response res;
  4617. int len;
  4618. const char * client_path;
  4619. deserialize_Create2Response(ia, "reply", &res);
  4620. client_path = sub_string(zh, res.path);
  4621. len = strlen(client_path) + 1;
  4622. if (len > sc->u.str.str_len) {
  4623. len = sc->u.str.str_len;
  4624. }
  4625. if (len > 0) {
  4626. memcpy(sc->u.str.str, client_path, len - 1);
  4627. sc->u.str.str[len - 1] = '\0';
  4628. }
  4629. free_duplicate_path(client_path, res.path);
  4630. sc->u.stat = res.stat;
  4631. deallocate_Create2Response(&res);
  4632. }
  4633. break;
  4634. case COMPLETION_ACLLIST:
  4635. if (sc->rc==0) {
  4636. struct GetACLResponse res;
  4637. deserialize_GetACLResponse(ia, "reply", &res);
  4638. sc->u.acl.acl = res.acl;
  4639. sc->u.acl.stat = res.stat;
  4640. /* We don't deallocate since we are passing it back */
  4641. //deallocate_GetACLResponse(&res);
  4642. }
  4643. break;
  4644. case COMPLETION_VOID:
  4645. break;
  4646. case COMPLETION_MULTI:
  4647. sc->rc = deserialize_multi(zh, cptr->xid, cptr, ia);
  4648. break;
  4649. default:
  4650. LOG_DEBUG(LOGCALLBACK(zh), "Unsupported completion type=%d", cptr->c.type);
  4651. break;
  4652. }
  4653. }
  4654. /*---------------------------------------------------------------------------*
  4655. * SYNC API
  4656. *---------------------------------------------------------------------------*/
  4657. int zoo_create(zhandle_t *zh, const char *path, const char *value,
  4658. int valuelen, const struct ACL_vector *acl, int mode,
  4659. char *path_buffer, int path_buffer_len)
  4660. {
  4661. return zoo_create_ttl(zh, path, value, valuelen, acl, mode, -1,
  4662. path_buffer, path_buffer_len);
  4663. }
  4664. int zoo_create_ttl(zhandle_t *zh, const char *path, const char *value,
  4665. int valuelen, const struct ACL_vector *acl, int mode, int64_t ttl,
  4666. char *path_buffer, int path_buffer_len)
  4667. {
  4668. struct sync_completion *sc = alloc_sync_completion();
  4669. int rc;
  4670. if (!sc) {
  4671. return ZSYSTEMERROR;
  4672. }
  4673. sc->u.str.str = path_buffer;
  4674. sc->u.str.str_len = path_buffer_len;
  4675. rc=zoo_acreate_ttl(zh, path, value, valuelen, acl, mode, ttl, SYNCHRONOUS_MARKER, sc);
  4676. if(rc==ZOK){
  4677. wait_sync_completion(sc);
  4678. rc = sc->rc;
  4679. }
  4680. free_sync_completion(sc);
  4681. return rc;
  4682. }
  4683. int zoo_create2(zhandle_t *zh, const char *path, const char *value,
  4684. int valuelen, const struct ACL_vector *acl, int mode,
  4685. char *path_buffer, int path_buffer_len, struct Stat *stat)
  4686. {
  4687. return zoo_create2_ttl(zh, path, value, valuelen, acl, mode, -1,
  4688. path_buffer, path_buffer_len, stat);
  4689. }
  4690. int zoo_create2_ttl(zhandle_t *zh, const char *path, const char *value,
  4691. int valuelen, const struct ACL_vector *acl, int mode, int64_t ttl,
  4692. char *path_buffer, int path_buffer_len, struct Stat *stat)
  4693. {
  4694. struct sync_completion *sc = alloc_sync_completion();
  4695. int rc;
  4696. if (!sc) {
  4697. return ZSYSTEMERROR;
  4698. }
  4699. sc->u.str.str = path_buffer;
  4700. sc->u.str.str_len = path_buffer_len;
  4701. rc=zoo_acreate2_ttl(zh, path, value, valuelen, acl, mode, ttl, SYNCHRONOUS_MARKER, sc);
  4702. if(rc==ZOK){
  4703. wait_sync_completion(sc);
  4704. rc = sc->rc;
  4705. if (rc == 0 && stat) {
  4706. *stat = sc->u.stat;
  4707. }
  4708. }
  4709. free_sync_completion(sc);
  4710. return rc;
  4711. }
  4712. int zoo_delete(zhandle_t *zh, const char *path, int version)
  4713. {
  4714. struct sync_completion *sc = alloc_sync_completion();
  4715. int rc;
  4716. if (!sc) {
  4717. return ZSYSTEMERROR;
  4718. }
  4719. rc=zoo_adelete(zh, path, version, SYNCHRONOUS_MARKER, sc);
  4720. if(rc==ZOK){
  4721. wait_sync_completion(sc);
  4722. rc = sc->rc;
  4723. }
  4724. free_sync_completion(sc);
  4725. return rc;
  4726. }
  4727. int zoo_exists(zhandle_t *zh, const char *path, int watch, struct Stat *stat)
  4728. {
  4729. return zoo_wexists(zh,path,watch?zh->watcher:0,zh->context,stat);
  4730. }
  4731. int zoo_wexists(zhandle_t *zh, const char *path,
  4732. watcher_fn watcher, void* watcherCtx, struct Stat *stat)
  4733. {
  4734. struct sync_completion *sc = alloc_sync_completion();
  4735. int rc;
  4736. if (!sc) {
  4737. return ZSYSTEMERROR;
  4738. }
  4739. rc=zoo_awexists(zh,path,watcher,watcherCtx,SYNCHRONOUS_MARKER, sc);
  4740. if(rc==ZOK){
  4741. wait_sync_completion(sc);
  4742. rc = sc->rc;
  4743. if (rc == 0&& stat) {
  4744. *stat = sc->u.stat;
  4745. }
  4746. }
  4747. free_sync_completion(sc);
  4748. return rc;
  4749. }
  4750. int zoo_get(zhandle_t *zh, const char *path, int watch, char *buffer,
  4751. int* buffer_len, struct Stat *stat)
  4752. {
  4753. return zoo_wget(zh,path,watch?zh->watcher:0,zh->context,
  4754. buffer,buffer_len,stat);
  4755. }
  4756. int zoo_wget(zhandle_t *zh, const char *path,
  4757. watcher_fn watcher, void* watcherCtx,
  4758. char *buffer, int* buffer_len, struct Stat *stat)
  4759. {
  4760. struct sync_completion *sc;
  4761. int rc=0;
  4762. if(buffer_len==NULL)
  4763. return ZBADARGUMENTS;
  4764. if((sc=alloc_sync_completion())==NULL)
  4765. return ZSYSTEMERROR;
  4766. sc->u.data.buffer = buffer;
  4767. sc->u.data.buff_len = *buffer_len;
  4768. rc=zoo_awget(zh, path, watcher, watcherCtx, SYNCHRONOUS_MARKER, sc);
  4769. if(rc==ZOK){
  4770. wait_sync_completion(sc);
  4771. rc = sc->rc;
  4772. if (rc == 0) {
  4773. if(stat)
  4774. *stat = sc->u.data.stat;
  4775. *buffer_len = sc->u.data.buff_len;
  4776. }
  4777. }
  4778. free_sync_completion(sc);
  4779. return rc;
  4780. }
  4781. int zoo_getconfig(zhandle_t *zh, int watch, char *buffer,
  4782. int* buffer_len, struct Stat *stat)
  4783. {
  4784. return zoo_wget(zh,ZOO_CONFIG_NODE,watch?zh->watcher:0,zh->context, buffer,buffer_len,stat);
  4785. }
  4786. int zoo_wgetconfig(zhandle_t *zh, watcher_fn watcher, void* watcherCtx,
  4787. char *buffer, int* buffer_len, struct Stat *stat)
  4788. {
  4789. return zoo_wget(zh, ZOO_CONFIG_NODE, watcher, watcherCtx, buffer, buffer_len, stat);
  4790. }
  4791. int zoo_reconfig(zhandle_t *zh, const char *joining, const char *leaving,
  4792. const char *members, int64_t version, char *buffer, int* buffer_len,
  4793. struct Stat *stat)
  4794. {
  4795. struct sync_completion *sc;
  4796. int rc=0;
  4797. if(buffer_len==NULL)
  4798. return ZBADARGUMENTS;
  4799. if((sc=alloc_sync_completion())==NULL)
  4800. return ZSYSTEMERROR;
  4801. sc->u.data.buffer = buffer;
  4802. sc->u.data.buff_len = *buffer_len;
  4803. rc=zoo_areconfig(zh, joining, leaving, members, version, SYNCHRONOUS_MARKER, sc);
  4804. if(rc==ZOK){
  4805. wait_sync_completion(sc);
  4806. rc = sc->rc;
  4807. if (rc == 0) {
  4808. if(stat)
  4809. *stat = sc->u.data.stat;
  4810. *buffer_len = sc->u.data.buff_len;
  4811. }
  4812. }
  4813. free_sync_completion(sc);
  4814. return rc;
  4815. }
  4816. int zoo_set(zhandle_t *zh, const char *path, const char *buffer, int buflen,
  4817. int version)
  4818. {
  4819. return zoo_set2(zh, path, buffer, buflen, version, 0);
  4820. }
  4821. int zoo_set2(zhandle_t *zh, const char *path, const char *buffer, int buflen,
  4822. int version, struct Stat *stat)
  4823. {
  4824. struct sync_completion *sc = alloc_sync_completion();
  4825. int rc;
  4826. if (!sc) {
  4827. return ZSYSTEMERROR;
  4828. }
  4829. rc=zoo_aset(zh, path, buffer, buflen, version, SYNCHRONOUS_MARKER, sc);
  4830. if(rc==ZOK){
  4831. wait_sync_completion(sc);
  4832. rc = sc->rc;
  4833. if (rc == 0 && stat) {
  4834. *stat = sc->u.stat;
  4835. }
  4836. }
  4837. free_sync_completion(sc);
  4838. return rc;
  4839. }
  4840. static int zoo_wget_children_(zhandle_t *zh, const char *path,
  4841. watcher_fn watcher, void* watcherCtx,
  4842. struct String_vector *strings)
  4843. {
  4844. struct sync_completion *sc = alloc_sync_completion();
  4845. int rc;
  4846. if (!sc) {
  4847. return ZSYSTEMERROR;
  4848. }
  4849. rc= zoo_awget_children (zh, path, watcher, watcherCtx, SYNCHRONOUS_MARKER, sc);
  4850. if(rc==ZOK){
  4851. wait_sync_completion(sc);
  4852. rc = sc->rc;
  4853. if (rc == 0) {
  4854. if (strings) {
  4855. *strings = sc->u.strs2;
  4856. } else {
  4857. deallocate_String_vector(&sc->u.strs2);
  4858. }
  4859. }
  4860. }
  4861. free_sync_completion(sc);
  4862. return rc;
  4863. }
  4864. static int zoo_wget_children2_(zhandle_t *zh, const char *path,
  4865. watcher_fn watcher, void* watcherCtx,
  4866. struct String_vector *strings, struct Stat *stat)
  4867. {
  4868. struct sync_completion *sc = alloc_sync_completion();
  4869. int rc;
  4870. if (!sc) {
  4871. return ZSYSTEMERROR;
  4872. }
  4873. rc= zoo_awget_children2(zh, path, watcher, watcherCtx, SYNCHRONOUS_MARKER, sc);
  4874. if(rc==ZOK){
  4875. wait_sync_completion(sc);
  4876. rc = sc->rc;
  4877. if (rc == 0) {
  4878. *stat = sc->u.strs_stat.stat2;
  4879. if (strings) {
  4880. *strings = sc->u.strs_stat.strs2;
  4881. } else {
  4882. deallocate_String_vector(&sc->u.strs_stat.strs2);
  4883. }
  4884. }
  4885. }
  4886. free_sync_completion(sc);
  4887. return rc;
  4888. }
  4889. int zoo_get_children(zhandle_t *zh, const char *path, int watch,
  4890. struct String_vector *strings)
  4891. {
  4892. return zoo_wget_children_(zh,path,watch?zh->watcher:0,zh->context,strings);
  4893. }
  4894. int zoo_wget_children(zhandle_t *zh, const char *path,
  4895. watcher_fn watcher, void* watcherCtx,
  4896. struct String_vector *strings)
  4897. {
  4898. return zoo_wget_children_(zh,path,watcher,watcherCtx,strings);
  4899. }
  4900. int zoo_get_children2(zhandle_t *zh, const char *path, int watch,
  4901. struct String_vector *strings, struct Stat *stat)
  4902. {
  4903. return zoo_wget_children2_(zh,path,watch?zh->watcher:0,zh->context,strings,stat);
  4904. }
  4905. int zoo_wget_children2(zhandle_t *zh, const char *path,
  4906. watcher_fn watcher, void* watcherCtx,
  4907. struct String_vector *strings, struct Stat *stat)
  4908. {
  4909. return zoo_wget_children2_(zh,path,watcher,watcherCtx,strings,stat);
  4910. }
  4911. int zoo_get_acl(zhandle_t *zh, const char *path, struct ACL_vector *acl,
  4912. struct Stat *stat)
  4913. {
  4914. struct sync_completion *sc = alloc_sync_completion();
  4915. int rc;
  4916. if (!sc) {
  4917. return ZSYSTEMERROR;
  4918. }
  4919. rc=zoo_aget_acl(zh, path, SYNCHRONOUS_MARKER, sc);
  4920. if(rc==ZOK){
  4921. wait_sync_completion(sc);
  4922. rc = sc->rc;
  4923. if (rc == 0&& stat) {
  4924. *stat = sc->u.acl.stat;
  4925. }
  4926. if (rc == 0) {
  4927. if (acl) {
  4928. *acl = sc->u.acl.acl;
  4929. } else {
  4930. deallocate_ACL_vector(&sc->u.acl.acl);
  4931. }
  4932. }
  4933. }
  4934. free_sync_completion(sc);
  4935. return rc;
  4936. }
  4937. int zoo_set_acl(zhandle_t *zh, const char *path, int version,
  4938. const struct ACL_vector *acl)
  4939. {
  4940. struct sync_completion *sc = alloc_sync_completion();
  4941. int rc;
  4942. if (!sc) {
  4943. return ZSYSTEMERROR;
  4944. }
  4945. rc=zoo_aset_acl(zh, path, version, (struct ACL_vector*)acl,
  4946. SYNCHRONOUS_MARKER, sc);
  4947. if(rc==ZOK){
  4948. wait_sync_completion(sc);
  4949. rc = sc->rc;
  4950. }
  4951. free_sync_completion(sc);
  4952. return rc;
  4953. }
  4954. static int remove_watches(
  4955. zhandle_t *zh, const char *path, ZooWatcherType wtype,
  4956. watcher_fn watcher, void *wctx, int local, int all)
  4957. {
  4958. int rc = 0;
  4959. struct sync_completion *sc;
  4960. if (!path)
  4961. return ZBADARGUMENTS;
  4962. sc = alloc_sync_completion();
  4963. if (!sc)
  4964. return ZSYSTEMERROR;
  4965. rc = aremove_watches(zh, path, wtype, watcher, wctx, local,
  4966. SYNCHRONOUS_MARKER, sc, all);
  4967. if (rc == ZOK) {
  4968. wait_sync_completion(sc);
  4969. rc = sc->rc;
  4970. }
  4971. free_sync_completion(sc);
  4972. return rc;
  4973. }
  4974. int zoo_multi(zhandle_t *zh, int count, const zoo_op_t *ops, zoo_op_result_t *results)
  4975. {
  4976. int rc;
  4977. struct sync_completion *sc = alloc_sync_completion();
  4978. if (!sc) {
  4979. return ZSYSTEMERROR;
  4980. }
  4981. rc = zoo_amulti(zh, count, ops, results, SYNCHRONOUS_MARKER, sc);
  4982. if (rc == ZOK) {
  4983. wait_sync_completion(sc);
  4984. rc = sc->rc;
  4985. }
  4986. free_sync_completion(sc);
  4987. return rc;
  4988. }
  4989. int zoo_remove_watches(zhandle_t *zh, const char *path, ZooWatcherType wtype,
  4990. watcher_fn watcher, void *watcherCtx, int local)
  4991. {
  4992. return remove_watches(zh, path, wtype, watcher, watcherCtx, local, 0);
  4993. }
  4994. int zoo_remove_all_watches(
  4995. zhandle_t *zh, const char *path, ZooWatcherType wtype, int local)
  4996. {
  4997. return remove_watches(zh, path, wtype, NULL, NULL, local, 1);
  4998. }
  4999. #endif
  5000. int zoo_aremove_watches(zhandle_t *zh, const char *path, ZooWatcherType wtype,
  5001. watcher_fn watcher, void *watcherCtx, int local,
  5002. void_completion_t *completion, const void *data)
  5003. {
  5004. return aremove_watches(
  5005. zh, path, wtype, watcher, watcherCtx, local, completion, data, 0);
  5006. }
  5007. int zoo_aremove_all_watches(zhandle_t *zh, const char *path,
  5008. ZooWatcherType wtype, int local, void_completion_t *completion,
  5009. const void *data)
  5010. {
  5011. return aremove_watches(
  5012. zh, path, wtype, NULL, NULL, local, completion, data, 1);
  5013. }