zookeeper.c 165 KB

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