zookeeper.c 176 KB

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