node.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. /*
  2. * Copyright (c)2013-2020 ZeroTier, Inc.
  3. *
  4. * Use of this software is governed by the Business Source License included
  5. * in the LICENSE.TXT file in the project's root directory.
  6. *
  7. * Change Date: 2024-01-01
  8. *
  9. * On the date above, in accordance with the Business Source License, use
  10. * of this software will be governed by version 2.0 of the Apache License.
  11. */
  12. /****/
  13. package zerotier
  14. // #cgo CFLAGS: -O3
  15. // #cgo darwin,!central LDFLAGS: ${SRCDIR}/../../build/serviceiocore/libzt_service_io_core.a ${SRCDIR}/../../build/core/libzt_core.a ${SRCDIR}/../../build/osdep/libzt_osdep.a ${SRCDIR}/../../build/controller/libzt_controller.a -lc++ -lpthread
  16. // #cgo darwin,central LDFLAGS: ${SRCDIR}/../../build/serviceiocore/libzt_service_io_core.a ${SRCDIR}/../../build/core/libzt_core.a ${SRCDIR}/../../build/osdep/libzt_osdep.a ${SRCDIR}/../../build/controller/libzt_controller.a ${SRCDIR}/../../build/lib/libredis++.a -lhiredis -lpq -lc++ -lpthread
  17. // #cgo linux,!central android,!central LDFLAGS: ${SRCDIR}/../../build/serviceiocore/libzt_service_io_core.a ${SRCDIR}/../../build/core/libzt_core.a ${SRCDIR}/../../build/osdep/libzt_osdep.a ${SRCDIR}/../../build/controller/libzt_controller.a -lstdc++ -lpthread -lm
  18. // #cgo linux,central android,central LDFLAGS: ${SRCDIR}/../../build/serviceiocore/libzt_service_io_core.a ${SRCDIR}/../../build/core/libzt_core.a ${SRCDIR}/../../build/osdep/libzt_osdep.a ${SRCDIR}/../../build/controller/libzt_controller.a ${SRCDIR}/../../build/lib/libredis++.a -lhiredis -lpq -lstdc++ -lpthread -lm
  19. // #include "../../serviceiocore/GoGlue.h"
  20. import "C"
  21. import (
  22. "bytes"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "io/ioutil"
  27. "log"
  28. "math/rand"
  29. "net"
  30. "net/http"
  31. "os"
  32. "path"
  33. "reflect"
  34. "sort"
  35. "strings"
  36. "sync"
  37. "sync/atomic"
  38. "syscall"
  39. "time"
  40. "unsafe"
  41. "github.com/hectane/go-acl"
  42. )
  43. var nullLogger = log.New(ioutil.Discard, "", 0)
  44. const (
  45. NetworkIDStringLength = 16
  46. NEtworkIDLength = 8
  47. AddressStringLength = 10
  48. AddressLength = 5
  49. NetworkStatusRequestingConfiguration int = C.ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION
  50. NetworkStatusOK int = C.ZT_NETWORK_STATUS_OK
  51. NetworkStatusAccessDenied int = C.ZT_NETWORK_STATUS_ACCESS_DENIED
  52. NetworkStatusNotFound int = C.ZT_NETWORK_STATUS_NOT_FOUND
  53. NetworkTypePrivate int = C.ZT_NETWORK_TYPE_PRIVATE
  54. NetworkTypePublic int = C.ZT_NETWORK_TYPE_PUBLIC
  55. networkConfigOpUp int = C.ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP
  56. networkConfigOpUpdate int = C.ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_CONFIG_UPDATE
  57. defaultVirtualNetworkMTU = C.ZT_DEFAULT_MTU
  58. // maxCNodeRefs is the maximum number of Node instances that can be created in this process.
  59. // This is perfectly fine to increase.
  60. maxCNodeRefs = 8
  61. )
  62. var (
  63. PlatformDefaultHomePath string
  64. CoreVersionMajor int
  65. CoreVersionMinor int
  66. CoreVersionRevision int
  67. CoreVersionBuild int
  68. // cNodeRefs maps an index to a *Node
  69. cNodeRefs [maxCNodeRefs]*Node
  70. // cNodeRefsUsed maps an index to whether or not the corresponding cNodeRefs[] entry is used.
  71. cNodeRefUsed [maxCNodeRefs]uint32
  72. )
  73. func init() {
  74. PlatformDefaultHomePath = C.GoString(C.ZT_PLATFORM_DEFAULT_HOMEPATH)
  75. var vMaj, vMin, vRev, vBuild C.int
  76. C.ZT_version(&vMaj, &vMin, &vRev, &vBuild)
  77. CoreVersionMajor = int(vMaj)
  78. CoreVersionMinor = int(vMin)
  79. CoreVersionRevision = int(vRev)
  80. CoreVersionBuild = int(vBuild)
  81. }
  82. // Node is an instance of a virtual port on the global switch.
  83. type Node struct {
  84. // Time this node was created
  85. startupTime int64
  86. // an arbitrary uintptr given to the core as its pointer back to Go's Node instance.
  87. // This is an index in the cNodeRefs array, which is synchronized by way of a set of
  88. // used/free booleans accessed atomically.
  89. cPtr uintptr
  90. // networks contains networks we have joined, and networksByMAC by their local MAC address
  91. networks map[NetworkID]*Network
  92. networksByMAC map[MAC]*Network // locked by networksLock
  93. networksLock sync.RWMutex
  94. // interfaceAddresses are physical IPs assigned to the local machine.
  95. // These are the detected IPs, not those configured explicitly. They include
  96. // both private and global IPs.
  97. interfaceAddresses map[string]net.IP
  98. interfaceAddressesLock sync.Mutex
  99. running uint32
  100. online uint32
  101. basePath string
  102. peersPath string
  103. networksPath string
  104. localConfigPath string
  105. infoLogPath string
  106. errorLogPath string
  107. // localConfig is the current state of local.conf.
  108. localConfig *LocalConfig
  109. previousLocalConfig *LocalConfig
  110. localConfigLock sync.RWMutex
  111. infoLogW *sizeLimitWriter
  112. errLogW *sizeLimitWriter
  113. traceLogW io.Writer
  114. infoLog *log.Logger
  115. errLog *log.Logger
  116. traceLog *log.Logger
  117. // gn is the GoNode instance, see go/native/GoNode.hpp
  118. gn *C.ZT_GoNode
  119. // zn is the underlying ZT_Node (ZeroTier::Node) instance
  120. zn unsafe.Pointer
  121. // id is the identity of this node (includes private key)
  122. id *Identity
  123. namedSocketAPIServer *http.Server
  124. tcpAPIServer *http.Server
  125. // runWaitGroup is used to wait for all node goroutines on shutdown.
  126. // Any new goroutine is tracked via this wait group so node shutdown can
  127. // itself wait until all goroutines have exited.
  128. runWaitGroup sync.WaitGroup
  129. }
  130. // NewNode creates and initializes a new instance of the ZeroTier node service
  131. func NewNode(basePath string) (n *Node, err error) {
  132. n = new(Node)
  133. n.startupTime = TimeMs()
  134. // Register this with the cNodeRefs lookup array and set up a deferred function
  135. // to unregister this if we exit before the end of the constructor such as by
  136. // returning an error.
  137. cPtr := -1
  138. for i := 0; i < maxCNodeRefs; i++ {
  139. if atomic.CompareAndSwapUint32(&cNodeRefUsed[i], 0, 1) {
  140. cNodeRefs[i] = n
  141. cPtr = i
  142. n.cPtr = uintptr(i)
  143. break
  144. }
  145. }
  146. if cPtr < 0 {
  147. return nil, ErrInternal
  148. }
  149. // Check and delete node reference pointer if it's non-negative. This helps
  150. // with error handling cleanup. At the end we set cPtr to -1 to disable.
  151. defer func() {
  152. if cPtr >= 0 {
  153. atomic.StoreUint32(&cNodeRefUsed[cPtr], 0)
  154. cNodeRefs[cPtr] = nil
  155. }
  156. }()
  157. n.networks = make(map[NetworkID]*Network)
  158. n.networksByMAC = make(map[MAC]*Network)
  159. n.interfaceAddresses = make(map[string]net.IP)
  160. n.running = 1
  161. _ = os.MkdirAll(basePath, 0755)
  162. if _, err = os.Stat(basePath); err != nil {
  163. return
  164. }
  165. n.basePath = basePath
  166. n.peersPath = path.Join(basePath, "peers.d")
  167. _ = os.MkdirAll(n.peersPath, 0700)
  168. _ = acl.Chmod(n.peersPath, 0700)
  169. if _, err = os.Stat(n.peersPath); err != nil {
  170. return
  171. }
  172. n.networksPath = path.Join(basePath, "networks.d")
  173. _ = os.MkdirAll(n.networksPath, 0755)
  174. if _, err = os.Stat(n.networksPath); err != nil {
  175. return
  176. }
  177. n.localConfigPath = path.Join(basePath, "local.conf")
  178. // Read local configuration, initializing with defaults if not found. We
  179. // check for identity.secret's existence to determine if this is a new
  180. // node or one that already existed. This influences some of the defaults.
  181. _, isTotallyNewNode := os.Stat(path.Join(basePath, "identity.secret"))
  182. n.localConfig = new(LocalConfig)
  183. err = n.localConfig.Read(n.localConfigPath, true, isTotallyNewNode != nil)
  184. if err != nil {
  185. return
  186. }
  187. n.infoLogPath = path.Join(basePath, "info.log")
  188. n.errorLogPath = path.Join(basePath, "error.log")
  189. if n.localConfig.Settings.LogSizeMax >= 0 {
  190. n.infoLogW, err = sizeLimitWriterOpen(n.infoLogPath)
  191. if err != nil {
  192. return
  193. }
  194. n.errLogW, err = sizeLimitWriterOpen(n.errorLogPath)
  195. if err != nil {
  196. return
  197. }
  198. n.infoLog = log.New(n.infoLogW, "", log.LstdFlags)
  199. n.errLog = log.New(n.errLogW, "", log.LstdFlags)
  200. } else {
  201. n.infoLog = nullLogger
  202. n.errLog = nullLogger
  203. }
  204. portsChanged := false
  205. portCheckCount := 0
  206. origPort := n.localConfig.Settings.PrimaryPort
  207. for portCheckCount < 256 {
  208. portCheckCount++
  209. if checkPort(n.localConfig.Settings.PrimaryPort) {
  210. if n.localConfig.Settings.PrimaryPort != origPort {
  211. n.infoLog.Printf("primary port %d unavailable, found port %d and saved in local.conf", origPort, n.localConfig.Settings.PrimaryPort)
  212. }
  213. break
  214. }
  215. n.localConfig.Settings.PrimaryPort = int(4096 + (randomUInt() % 16384))
  216. portsChanged = true
  217. }
  218. if portCheckCount == 256 {
  219. return nil, errors.New("unable to bind to primary port: tried configured port and 256 other random ports")
  220. }
  221. if n.localConfig.Settings.SecondaryPort > 0 {
  222. portCheckCount = 0
  223. origPort = n.localConfig.Settings.SecondaryPort
  224. for portCheckCount < 256 {
  225. portCheckCount++
  226. if checkPort(n.localConfig.Settings.SecondaryPort) {
  227. if n.localConfig.Settings.SecondaryPort != origPort {
  228. n.infoLog.Printf("secondary port %d unavailable, found port %d (port search enabled)", origPort, n.localConfig.Settings.SecondaryPort)
  229. }
  230. break
  231. }
  232. n.infoLog.Printf("secondary port %d unavailable, trying a random port (port search enabled)", n.localConfig.Settings.SecondaryPort)
  233. if portCheckCount <= 64 {
  234. n.localConfig.Settings.SecondaryPort = unassignedPrivilegedPorts[randomUInt()%uint(len(unassignedPrivilegedPorts))]
  235. } else {
  236. n.localConfig.Settings.SecondaryPort = int(16384 + (randomUInt() % 16384))
  237. }
  238. portsChanged = true
  239. }
  240. }
  241. if portsChanged {
  242. _ = n.localConfig.Write(n.localConfigPath)
  243. }
  244. n.namedSocketAPIServer, n.tcpAPIServer, err = createAPIServer(basePath, n)
  245. if err != nil {
  246. n.infoLog.Printf("FATAL: unable to start API server: %s", err.Error())
  247. return nil, err
  248. }
  249. cPath := C.CString(basePath)
  250. n.gn = C.ZT_GoNode_new(cPath, C.uintptr_t(n.cPtr))
  251. C.free(unsafe.Pointer(cPath))
  252. if n.gn == nil {
  253. n.infoLog.Println("FATAL: node initialization failed")
  254. return nil, ErrNodeInitFailed
  255. }
  256. n.zn = unsafe.Pointer(C.ZT_GoNode_getNode(n.gn))
  257. n.id, err = newIdentityFromCIdentity(C.ZT_Node_identity(n.zn))
  258. if err != nil {
  259. n.infoLog.Printf("FATAL: error obtaining node's identity")
  260. C.ZT_GoNode_delete(n.gn)
  261. return nil, err
  262. }
  263. // Background maintenance goroutine that handles polling for local network changes, cleaning internal data
  264. // structures, syncing local config changes, and numerous other things that must happen from time to time.
  265. n.runWaitGroup.Add(1)
  266. go func() {
  267. defer n.runWaitGroup.Done()
  268. lastMaintenanceRun := int64(0)
  269. for atomic.LoadUint32(&n.running) != 0 {
  270. time.Sleep(250 * time.Millisecond)
  271. nowS := time.Now().Unix()
  272. if (nowS - lastMaintenanceRun) >= 30 {
  273. lastMaintenanceRun = nowS
  274. n.runMaintenance()
  275. }
  276. time.Sleep(250 * time.Millisecond)
  277. }
  278. }()
  279. // Stop deferred cPtr table cleanup function from deregistering this instance
  280. cPtr = -1
  281. return n, nil
  282. }
  283. // Close closes this Node and frees its underlying C++ Node structures
  284. func (n *Node) Close() {
  285. if atomic.SwapUint32(&n.running, 0) != 0 {
  286. if n.namedSocketAPIServer != nil {
  287. _ = n.namedSocketAPIServer.Close()
  288. }
  289. if n.tcpAPIServer != nil {
  290. _ = n.tcpAPIServer.Close()
  291. }
  292. C.ZT_GoNode_delete(n.gn)
  293. n.runWaitGroup.Wait()
  294. cNodeRefs[n.cPtr] = nil
  295. atomic.StoreUint32(&cNodeRefUsed[n.cPtr], 0)
  296. }
  297. }
  298. // Address returns this node's address
  299. func (n *Node) Address() Address { return n.id.address }
  300. // Identity returns this node's identity (including secret portion)
  301. func (n *Node) Identity() *Identity { return n.id }
  302. // Online returns true if this node can reach something
  303. func (n *Node) Online() bool { return atomic.LoadUint32(&n.online) != 0 }
  304. // InterfaceAddresses are external IPs belonging to physical interfaces on this machine
  305. func (n *Node) InterfaceAddresses() []net.IP {
  306. var ea []net.IP
  307. n.interfaceAddressesLock.Lock()
  308. for _, a := range n.interfaceAddresses {
  309. ea = append(ea, a)
  310. }
  311. n.interfaceAddressesLock.Unlock()
  312. sort.Slice(ea, func(a, b int) bool { return bytes.Compare(ea[a], ea[b]) < 0 })
  313. return ea
  314. }
  315. // LocalConfig gets this node's local configuration
  316. func (n *Node) LocalConfig() *LocalConfig {
  317. n.localConfigLock.RLock()
  318. defer n.localConfigLock.RUnlock()
  319. return n.localConfig
  320. }
  321. // SetLocalConfig updates this node's local configuration
  322. func (n *Node) SetLocalConfig(lc *LocalConfig) (restartRequired bool, err error) {
  323. n.networksLock.RLock()
  324. n.localConfigLock.Lock()
  325. defer n.localConfigLock.Unlock()
  326. defer n.networksLock.RUnlock()
  327. for nid, nc := range lc.Network {
  328. nw := n.networks[nid]
  329. if nw != nil {
  330. nw.SetLocalSettings(&nc)
  331. }
  332. }
  333. if n.localConfig.Settings.PrimaryPort != lc.Settings.PrimaryPort || n.localConfig.Settings.SecondaryPort != lc.Settings.SecondaryPort || n.localConfig.Settings.LogSizeMax != lc.Settings.LogSizeMax {
  334. restartRequired = true
  335. }
  336. n.previousLocalConfig = n.localConfig
  337. n.localConfig = lc
  338. return
  339. }
  340. // Join a network.
  341. // If tap is nil, the default system tap for this OS/platform is used (if available).
  342. func (n *Node) Join(nwid NetworkID, controllerFingerprint *Fingerprint, settings *NetworkLocalSettings, tap Tap) (*Network, error) {
  343. n.networksLock.RLock()
  344. if nw, have := n.networks[nwid]; have {
  345. n.infoLog.Printf("join network %.16x ignored: already a member", nwid)
  346. if settings != nil {
  347. nw.SetLocalSettings(settings)
  348. }
  349. return nw, nil
  350. }
  351. n.networksLock.RUnlock()
  352. if tap != nil {
  353. panic("non-native taps not yet implemented")
  354. }
  355. var fp *C.ZT_Fingerprint
  356. if controllerFingerprint != nil {
  357. fp = controllerFingerprint.cFingerprint()
  358. }
  359. ntap := C.ZT_GoNode_join(n.gn, C.uint64_t(nwid), fp)
  360. if ntap == nil {
  361. n.infoLog.Printf("join network %.16x failed: tap device failed to initialize (check drivers / kernel modules)", uint64(nwid))
  362. return nil, ErrTapInitFailed
  363. }
  364. nw, err := newNetwork(n, nwid, &nativeTap{tap: unsafe.Pointer(ntap), enabled: 1})
  365. if err != nil {
  366. n.infoLog.Printf("join network %.16x failed: network failed to initialize: %s", nwid, err.Error())
  367. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  368. return nil, err
  369. }
  370. n.networksLock.Lock()
  371. n.networks[nwid] = nw
  372. n.networksLock.Unlock()
  373. if settings != nil {
  374. nw.SetLocalSettings(settings)
  375. }
  376. return nw, nil
  377. }
  378. // Leave a network.
  379. func (n *Node) Leave(nwid NetworkID) error {
  380. n.networksLock.Lock()
  381. nw := n.networks[nwid]
  382. delete(n.networks, nwid)
  383. n.networksLock.Unlock()
  384. if nw != nil {
  385. n.infoLog.Printf("leaving network %.16x", nwid)
  386. nw.leaving()
  387. }
  388. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  389. return nil
  390. }
  391. // AddRoot designates a peer as root, adding it if missing.
  392. func (n *Node) AddRoot(id *Identity) (*Peer, error) {
  393. if !id.initCIdentityPtr() {
  394. return nil, ErrInvalidKey
  395. }
  396. rc := C.ZT_Node_addRoot(n.zn, nil, id.cid)
  397. if rc != 0 {
  398. return nil, ErrInvalidParameter
  399. }
  400. p := n.Peer(id.Fingerprint())
  401. if p == nil {
  402. return nil, ErrInvalidParameter
  403. }
  404. return p, nil
  405. }
  406. // RemoveRoot un-designates a peer as root.
  407. func (n *Node) RemoveRoot(address Address) {
  408. C.ZT_Node_removeRoot(n.zn, nil, C.uint64_t(address))
  409. }
  410. // Network looks up a network by ID or returns nil if not joined
  411. func (n *Node) Network(nwid NetworkID) *Network {
  412. n.networksLock.RLock()
  413. nw := n.networks[nwid]
  414. n.networksLock.RUnlock()
  415. return nw
  416. }
  417. // Networks returns a list of networks that this node has joined
  418. func (n *Node) Networks() []*Network {
  419. var nws []*Network
  420. n.networksLock.RLock()
  421. for _, nw := range n.networks {
  422. nws = append(nws, nw)
  423. }
  424. n.networksLock.RUnlock()
  425. return nws
  426. }
  427. // Peers retrieves a list of current peers
  428. func (n *Node) Peers() []*Peer {
  429. var peers []*Peer
  430. pl := C.ZT_Node_peers(n.zn)
  431. if pl != nil {
  432. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  433. p, _ := newPeerFromCPeer((*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer))))
  434. if p != nil {
  435. peers = append(peers, p)
  436. }
  437. }
  438. C.ZT_freeQueryResult(unsafe.Pointer(pl))
  439. }
  440. sort.Slice(peers, func(a, b int) bool {
  441. return peers[a].Address < peers[b].Address
  442. })
  443. return peers
  444. }
  445. // Peer looks up a single peer by address or full fingerprint.
  446. // The fpOrAddress parameter may be either. If it is neither nil is returned.
  447. // A nil pointer is returned if nothing is found.
  448. func (n *Node) Peer(fpOrAddress interface{}) *Peer {
  449. fp, _ := fpOrAddress.(*Fingerprint)
  450. if fp == nil {
  451. a, _ := fpOrAddress.(*Address)
  452. if a == nil {
  453. return nil
  454. }
  455. fp = &Fingerprint{Address: *a}
  456. }
  457. pl := C.ZT_Node_peers(n.zn)
  458. if pl != nil {
  459. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  460. p, _ := newPeerFromCPeer((*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer))))
  461. if p != nil && p.Identity.Fingerprint().BestSpecificityEquals(fp) {
  462. C.ZT_freeQueryResult(unsafe.Pointer(pl))
  463. return p
  464. }
  465. }
  466. C.ZT_freeQueryResult(unsafe.Pointer(pl))
  467. }
  468. return nil
  469. }
  470. // AddPeer adds a peer by explicit identity.
  471. func (n *Node) AddPeer(id *Identity) error {
  472. if id == nil {
  473. return ErrInvalidParameter
  474. }
  475. if !id.initCIdentityPtr() {
  476. return ErrInvalidKey
  477. }
  478. rc := C.ZT_Node_addPeer(n.zn, nil, id.cid)
  479. if rc != 0 {
  480. return ErrInvalidParameter
  481. }
  482. return nil
  483. }
  484. // TryPeer attempts to contact a peer at a given explicit endpoint.
  485. // The peer may be identified by an Address or a full Fingerprint. Any other
  486. // type for fpOrAddress will return false.
  487. func (n *Node) TryPeer(fpOrAddress interface{}, ep *Endpoint, retries int) bool {
  488. if ep == nil {
  489. return false
  490. }
  491. fp, _ := fpOrAddress.(*Fingerprint)
  492. if fp == nil {
  493. a, _ := fpOrAddress.(*Address)
  494. if a == nil {
  495. return false
  496. }
  497. fp = &Fingerprint{Address: *a}
  498. }
  499. return C.ZT_Node_tryPeer(n.zn, nil, fp.cFingerprint(), &ep.cep, C.int(retries)) != 0
  500. }
  501. // --------------------------------------------------------------------------------------------------------------------
  502. func (n *Node) runMaintenance() {
  503. n.localConfigLock.RLock()
  504. defer n.localConfigLock.RUnlock()
  505. // Get local physical interface addresses, excluding blacklisted and
  506. // ZeroTier-created interfaces.
  507. interfaceAddresses := make(map[string]net.IP)
  508. ifs, _ := net.Interfaces()
  509. if len(ifs) > 0 {
  510. n.networksLock.RLock()
  511. scanInterfaces:
  512. for _, i := range ifs {
  513. for _, bl := range n.localConfig.Settings.InterfacePrefixBlacklist {
  514. if strings.HasPrefix(strings.ToLower(i.Name), strings.ToLower(bl)) {
  515. continue scanInterfaces
  516. }
  517. }
  518. m, _ := NewMACFromBytes(i.HardwareAddr)
  519. if _, isZeroTier := n.networksByMAC[m]; !isZeroTier {
  520. addrs, _ := i.Addrs()
  521. for _, a := range addrs {
  522. ipn, _ := a.(*net.IPNet)
  523. if ipn != nil && len(ipn.IP) > 0 && !ipn.IP.IsLoopback() && !ipn.IP.IsMulticast() && !ipn.IP.IsInterfaceLocalMulticast() && !ipn.IP.IsLinkLocalMulticast() && !ipn.IP.IsLinkLocalUnicast() {
  524. isTemporary := false
  525. if len(ipn.IP) == 16 {
  526. var ss C.struct_sockaddr_storage
  527. if makeSockaddrStorage(ipn.IP, 0, &ss) {
  528. cIfName := C.CString(i.Name)
  529. if C.ZT_isTemporaryV6Address(cIfName, &ss) != 0 {
  530. isTemporary = true
  531. }
  532. C.free(unsafe.Pointer(cIfName))
  533. }
  534. }
  535. if !isTemporary {
  536. interfaceAddresses[ipn.IP.String()] = ipn.IP
  537. }
  538. }
  539. }
  540. }
  541. }
  542. n.networksLock.RUnlock()
  543. }
  544. // Open or close locally bound UDP ports for each local interface address.
  545. // This opens ports if they are not already open and then closes ports if
  546. // they are open but no longer seem to exist.
  547. interfaceAddressesChanged := false
  548. ports := make([]int, 0, 2)
  549. if n.localConfig.Settings.PrimaryPort > 0 && n.localConfig.Settings.PrimaryPort < 65536 {
  550. ports = append(ports, n.localConfig.Settings.PrimaryPort)
  551. }
  552. if n.localConfig.Settings.SecondaryPort > 0 && n.localConfig.Settings.SecondaryPort < 65536 {
  553. ports = append(ports, n.localConfig.Settings.SecondaryPort)
  554. }
  555. n.interfaceAddressesLock.Lock()
  556. for astr, ipn := range interfaceAddresses {
  557. if _, alreadyKnown := n.interfaceAddresses[astr]; !alreadyKnown {
  558. interfaceAddressesChanged = true
  559. ipCstr := C.CString(ipn.String())
  560. for pn, p := range ports {
  561. n.infoLog.Printf("UDP binding to port %d on interface %s", p, astr)
  562. primary := C.int(0)
  563. if pn == 0 {
  564. primary = 1
  565. }
  566. C.ZT_GoNode_phyStartListen(n.gn, nil, ipCstr, C.int(p), primary)
  567. }
  568. C.free(unsafe.Pointer(ipCstr))
  569. }
  570. }
  571. for astr, ipn := range n.interfaceAddresses {
  572. if _, stillPresent := interfaceAddresses[astr]; !stillPresent {
  573. interfaceAddressesChanged = true
  574. ipCstr := C.CString(ipn.String())
  575. for _, p := range ports {
  576. n.infoLog.Printf("UDP closing socket bound to port %d on interface %s", p, astr)
  577. C.ZT_GoNode_phyStopListen(n.gn, nil, ipCstr, C.int(p))
  578. }
  579. C.free(unsafe.Pointer(ipCstr))
  580. }
  581. }
  582. n.interfaceAddresses = interfaceAddresses
  583. n.interfaceAddressesLock.Unlock()
  584. // Update node's interface address list if detected or configured addresses have changed.
  585. if interfaceAddressesChanged || n.previousLocalConfig == nil || !reflect.DeepEqual(n.localConfig.Settings.ExplicitAddresses, n.previousLocalConfig.Settings.ExplicitAddresses) {
  586. var cAddrs []C.ZT_InterfaceAddress
  587. externalAddresses := make(map[[3]uint64]*InetAddress)
  588. for _, a := range n.localConfig.Settings.ExplicitAddresses {
  589. ak := a.key()
  590. if _, have := externalAddresses[ak]; !have {
  591. externalAddresses[ak] = &a
  592. cAddrs = append(cAddrs, C.ZT_InterfaceAddress{})
  593. makeSockaddrStorage(a.IP, a.Port, &(cAddrs[len(cAddrs)-1].address))
  594. cAddrs[len(cAddrs)-1].permanent = 1 // explicit addresses are permanent, meaning they can be put in a locator
  595. }
  596. }
  597. for _, ip := range interfaceAddresses {
  598. for _, p := range ports {
  599. a := InetAddress{IP: ip, Port: p}
  600. ak := a.key()
  601. if _, have := externalAddresses[ak]; !have {
  602. externalAddresses[ak] = &a
  603. cAddrs = append(cAddrs, C.ZT_InterfaceAddress{})
  604. makeSockaddrStorage(a.IP, a.Port, &(cAddrs[len(cAddrs)-1].address))
  605. cAddrs[len(cAddrs)-1].permanent = 0
  606. }
  607. }
  608. }
  609. if len(cAddrs) > 0 {
  610. C.ZT_Node_setInterfaceAddresses(n.zn, &cAddrs[0], C.uint(len(cAddrs)))
  611. } else {
  612. C.ZT_Node_setInterfaceAddresses(n.zn, nil, 0)
  613. }
  614. }
  615. // Trim infoLog if it's gone over its size limit
  616. if n.localConfig.Settings.LogSizeMax > 0 && n.infoLogW != nil {
  617. _ = n.infoLogW.trim(n.localConfig.Settings.LogSizeMax*1024, 0.5, true)
  618. }
  619. }
  620. func (n *Node) multicastSubscribe(nwid uint64, mg *MulticastGroup) {
  621. C.ZT_Node_multicastSubscribe(n.zn, nil, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  622. }
  623. func (n *Node) multicastUnsubscribe(nwid uint64, mg *MulticastGroup) {
  624. C.ZT_Node_multicastUnsubscribe(n.zn, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  625. }
  626. func (n *Node) pathCheck(ip net.IP) bool {
  627. n.localConfigLock.RLock()
  628. defer n.localConfigLock.RUnlock()
  629. for cidr, phy := range n.localConfig.Physical {
  630. if phy.Blacklist {
  631. _, ipn, _ := net.ParseCIDR(cidr)
  632. if ipn != nil && ipn.Contains(ip) {
  633. return false
  634. }
  635. }
  636. }
  637. return true
  638. }
  639. func (n *Node) pathLookup(id *Identity) (net.IP, int) {
  640. n.localConfigLock.RLock()
  641. defer n.localConfigLock.RUnlock()
  642. virt := n.localConfig.Virtual[id.address]
  643. if len(virt.Try) > 0 {
  644. idx := rand.Int() % len(virt.Try)
  645. return virt.Try[idx].IP, virt.Try[idx].Port
  646. }
  647. return nil, 0
  648. }
  649. func (n *Node) makeStateObjectPath(objType int, id [2]uint64) (string, bool) {
  650. var fp string
  651. secret := false
  652. switch objType {
  653. case C.ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  654. fp = path.Join(n.basePath, "identity.public")
  655. case C.ZT_STATE_OBJECT_IDENTITY_SECRET:
  656. fp = path.Join(n.basePath, "identity.secret")
  657. secret = true
  658. case C.ZT_STATE_OBJECT_LOCATOR:
  659. fp = path.Join(n.basePath, "locator")
  660. case C.ZT_STATE_OBJECT_PEER:
  661. fp = path.Join(n.basePath, "peers.d")
  662. _ = os.Mkdir(fp, 0700)
  663. fp = path.Join(fp, fmt.Sprintf("%.10x.peer", id[0]))
  664. secret = true
  665. case C.ZT_STATE_OBJECT_NETWORK_CONFIG:
  666. fp = path.Join(n.basePath, "networks.d")
  667. _ = os.Mkdir(fp, 0755)
  668. fp = path.Join(fp, fmt.Sprintf("%.16x.conf", id[0]))
  669. case C.ZT_STATE_OBJECT_ROOTS:
  670. fp = path.Join(n.basePath, "roots")
  671. }
  672. return fp, secret
  673. }
  674. func (n *Node) stateObjectPut(objType int, id [2]uint64, data []byte) {
  675. fp, secret := n.makeStateObjectPath(objType, id)
  676. if len(fp) > 0 {
  677. fileMode := os.FileMode(0644)
  678. if secret {
  679. fileMode = os.FileMode(0600)
  680. }
  681. _ = ioutil.WriteFile(fp, data, fileMode)
  682. if secret {
  683. _ = acl.Chmod(fp, 0600) // this emulates Unix chmod on Windows and uses os.Chmod on Unix-type systems
  684. }
  685. }
  686. }
  687. func (n *Node) stateObjectDelete(objType int, id [2]uint64) {
  688. fp, _ := n.makeStateObjectPath(objType, id)
  689. if len(fp) > 0 {
  690. _ = os.Remove(fp)
  691. }
  692. }
  693. func (n *Node) stateObjectGet(objType int, id [2]uint64) ([]byte, bool) {
  694. fp, _ := n.makeStateObjectPath(objType, id)
  695. if len(fp) > 0 {
  696. fd, err := ioutil.ReadFile(fp)
  697. if err != nil {
  698. return nil, false
  699. }
  700. return fd, true
  701. }
  702. return nil, false
  703. }
  704. func (n *Node) handleTrace(traceMessage string) {
  705. if len(traceMessage) > 0 {
  706. n.infoLog.Print("TRACE: " + traceMessage)
  707. }
  708. }
  709. // These are callbacks called by the core and GoGlue stuff to talk to the
  710. // service. These launch goroutines to do their work where possible to
  711. // avoid blocking anything in the core.
  712. //export goPathCheckFunc
  713. func goPathCheckFunc(gn, _ unsafe.Pointer, af C.int, ip unsafe.Pointer, _ C.int) C.int {
  714. node := cNodeRefs[uintptr(gn)]
  715. if node == nil {
  716. return 0
  717. }
  718. var nip net.IP
  719. if af == syscall.AF_INET {
  720. nip = ((*[4]byte)(ip))[:]
  721. } else if af == syscall.AF_INET6 {
  722. nip = ((*[16]byte)(ip))[:]
  723. } else {
  724. return 0
  725. }
  726. if len(nip) > 0 && node.pathCheck(nip) {
  727. return 1
  728. }
  729. return 0
  730. }
  731. //export goPathLookupFunc
  732. func goPathLookupFunc(gn unsafe.Pointer, _ C.uint64_t, _ int, identity, familyP, ipP, portP unsafe.Pointer) C.int {
  733. node := cNodeRefs[uintptr(gn)]
  734. if node == nil {
  735. return 0
  736. }
  737. id, err := newIdentityFromCIdentity(identity)
  738. if err != nil {
  739. return 0
  740. }
  741. ip, port := node.pathLookup(id)
  742. if len(ip) > 0 && port > 0 && port <= 65535 {
  743. ip4 := ip.To4()
  744. if len(ip4) == 4 {
  745. *((*C.int)(familyP)) = C.int(syscall.AF_INET)
  746. copy((*[4]byte)(ipP)[:], ip4)
  747. *((*C.int)(portP)) = C.int(port)
  748. return 1
  749. } else if len(ip) == 16 {
  750. *((*C.int)(familyP)) = C.int(syscall.AF_INET6)
  751. copy((*[16]byte)(ipP)[:], ip)
  752. *((*C.int)(portP)) = C.int(port)
  753. return 1
  754. }
  755. }
  756. return 0
  757. }
  758. //export goStateObjectPutFunc
  759. func goStateObjectPutFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, len C.int) {
  760. node := cNodeRefs[uintptr(gn)]
  761. if node == nil {
  762. return
  763. }
  764. id2 := *((*[2]uint64)(id))
  765. var data2 []byte
  766. if len > 0 {
  767. data2 = C.GoBytes(data, len)
  768. }
  769. node.runWaitGroup.Add(1)
  770. go func() {
  771. if len < 0 {
  772. node.stateObjectDelete(int(objType), id2)
  773. } else {
  774. node.stateObjectPut(int(objType), id2, data2)
  775. }
  776. node.runWaitGroup.Done()
  777. }()
  778. }
  779. //export goStateObjectGetFunc
  780. func goStateObjectGetFunc(gn unsafe.Pointer, objType C.int, id, dataP unsafe.Pointer) C.int {
  781. node := cNodeRefs[uintptr(gn)]
  782. if node == nil {
  783. return -1
  784. }
  785. *((*uintptr)(dataP)) = 0
  786. tmp, found := node.stateObjectGet(int(objType), *((*[2]uint64)(id)))
  787. if found && len(tmp) > 0 {
  788. cData := C.malloc(C.ulong(len(tmp))) // GoGlue sends free() to the core as the free function
  789. if uintptr(cData) == 0 {
  790. return -1
  791. }
  792. *((*uintptr)(dataP)) = uintptr(cData)
  793. return C.int(len(tmp))
  794. }
  795. return -1
  796. }
  797. //export goVirtualNetworkConfigFunc
  798. func goVirtualNetworkConfigFunc(gn, _ unsafe.Pointer, nwid C.uint64_t, op C.int, conf unsafe.Pointer) {
  799. node := cNodeRefs[uintptr(gn)]
  800. if node == nil {
  801. return
  802. }
  803. node.networksLock.RLock()
  804. network := node.networks[NetworkID(nwid)]
  805. node.networksLock.RUnlock()
  806. if network != nil {
  807. switch int(op) {
  808. case networkConfigOpUp, networkConfigOpUpdate:
  809. ncc := (*C.ZT_VirtualNetworkConfig)(conf)
  810. if network.networkConfigRevision() > uint64(ncc.netconfRevision) {
  811. return
  812. }
  813. var nc NetworkConfig
  814. nc.ID = NetworkID(ncc.nwid)
  815. nc.MAC = MAC(ncc.mac)
  816. nc.Name = C.GoString(&ncc.name[0])
  817. nc.Status = int(ncc.status)
  818. nc.Type = int(ncc._type)
  819. nc.MTU = int(ncc.mtu)
  820. nc.Bridge = ncc.bridge != 0
  821. nc.BroadcastEnabled = ncc.broadcastEnabled != 0
  822. nc.NetconfRevision = uint64(ncc.netconfRevision)
  823. for i := 0; i < int(ncc.assignedAddressCount); i++ {
  824. a := sockaddrStorageToIPNet(&ncc.assignedAddresses[i])
  825. if a != nil {
  826. nc.AssignedAddresses = append(nc.AssignedAddresses, *a)
  827. }
  828. }
  829. for i := 0; i < int(ncc.routeCount); i++ {
  830. tgt := sockaddrStorageToIPNet(&ncc.routes[i].target)
  831. viaN := sockaddrStorageToIPNet(&ncc.routes[i].via)
  832. var via *net.IP
  833. if viaN != nil && len(viaN.IP) > 0 {
  834. via = &viaN.IP
  835. }
  836. if tgt != nil {
  837. nc.Routes = append(nc.Routes, Route{
  838. Target: *tgt,
  839. Via: via,
  840. Flags: uint16(ncc.routes[i].flags),
  841. Metric: uint16(ncc.routes[i].metric),
  842. })
  843. }
  844. }
  845. node.runWaitGroup.Add(1)
  846. go func() {
  847. network.updateConfig(&nc, nil)
  848. node.runWaitGroup.Done()
  849. }()
  850. }
  851. }
  852. }
  853. //export goZtEvent
  854. func goZtEvent(gn unsafe.Pointer, eventType C.int, data unsafe.Pointer) {
  855. node := cNodeRefs[uintptr(gn)]
  856. if node == nil {
  857. return
  858. }
  859. switch eventType {
  860. case C.ZT_EVENT_OFFLINE:
  861. atomic.StoreUint32(&node.online, 0)
  862. case C.ZT_EVENT_ONLINE:
  863. atomic.StoreUint32(&node.online, 1)
  864. }
  865. }