node.go 27 KB

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