node.go 27 KB

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