node.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  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. rc := C.ZT_Node_addRoot(n.zn, nil, id.cIdentity())
  390. if rc != 0 {
  391. return nil, ErrInvalidParameter
  392. }
  393. p := n.Peer(id.Fingerprint())
  394. if p == nil {
  395. return nil, ErrInvalidParameter
  396. }
  397. return p, nil
  398. }
  399. // RemoveRoot un-designates a peer as root.
  400. func (n *Node) RemoveRoot(address Address) {
  401. C.ZT_Node_removeRoot(n.zn, nil, C.uint64_t(address))
  402. }
  403. // Network looks up a network by ID or returns nil if not joined
  404. func (n *Node) Network(nwid NetworkID) *Network {
  405. n.networksLock.RLock()
  406. nw := n.networks[nwid]
  407. n.networksLock.RUnlock()
  408. return nw
  409. }
  410. // Networks returns a list of networks that this node has joined
  411. func (n *Node) Networks() []*Network {
  412. var nws []*Network
  413. n.networksLock.RLock()
  414. for _, nw := range n.networks {
  415. nws = append(nws, nw)
  416. }
  417. n.networksLock.RUnlock()
  418. return nws
  419. }
  420. // Peers retrieves a list of current peers
  421. func (n *Node) Peers() []*Peer {
  422. var peers []*Peer
  423. pl := C.ZT_Node_peers(n.zn)
  424. if pl != nil {
  425. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  426. p, _ := newPeerFromCPeer((*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer))))
  427. if p != nil {
  428. peers = append(peers, p)
  429. }
  430. }
  431. C.ZT_freeQueryResult(unsafe.Pointer(pl))
  432. }
  433. sort.Slice(peers, func(a, b int) bool {
  434. return peers[a].Address < peers[b].Address
  435. })
  436. return peers
  437. }
  438. // Peer looks up a single peer by address or full fingerprint.
  439. // The fpOrAddress parameter may be either. If it is neither nil is returned.
  440. // A nil pointer is returned if nothing is found.
  441. func (n *Node) Peer(fpOrAddress interface{}) *Peer {
  442. fp, _ := fpOrAddress.(*Fingerprint)
  443. if fp == nil {
  444. a, _ := fpOrAddress.(*Address)
  445. if a == nil {
  446. return nil
  447. }
  448. fp = &Fingerprint{Address: *a}
  449. }
  450. pl := C.ZT_Node_peers(n.zn)
  451. if pl != nil {
  452. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  453. p, _ := newPeerFromCPeer((*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer))))
  454. if p != nil && p.Identity.Fingerprint().BestSpecificityEquals(fp) {
  455. C.ZT_freeQueryResult(unsafe.Pointer(pl))
  456. return p
  457. }
  458. }
  459. C.ZT_freeQueryResult(unsafe.Pointer(pl))
  460. }
  461. return nil
  462. }
  463. // AddPeer adds a peer by explicit identity.
  464. func (n *Node) AddPeer(id *Identity) error {
  465. if id == nil {
  466. return ErrInvalidParameter
  467. }
  468. rc := C.ZT_Node_addPeer(n.zn, nil, id.cIdentity())
  469. if rc != 0 {
  470. return ErrInvalidParameter
  471. }
  472. return nil
  473. }
  474. // TryPeer attempts to contact a peer at a given explicit endpoint.
  475. // The peer may be identified by an Address or a full Fingerprint. Any other
  476. // type for fpOrAddress will return false.
  477. func (n *Node) TryPeer(fpOrAddress interface{}, ep *Endpoint, retries int) bool {
  478. if ep == nil {
  479. return false
  480. }
  481. fp, _ := fpOrAddress.(*Fingerprint)
  482. if fp == nil {
  483. a, _ := fpOrAddress.(*Address)
  484. if a == nil {
  485. return false
  486. }
  487. fp = &Fingerprint{Address: *a}
  488. }
  489. return C.ZT_Node_tryPeer(n.zn, nil, fp.cFingerprint(), &ep.cep, C.int(retries)) != 0
  490. }
  491. // --------------------------------------------------------------------------------------------------------------------
  492. func (n *Node) runMaintenance() {
  493. n.localConfigLock.RLock()
  494. defer n.localConfigLock.RUnlock()
  495. // Get local physical interface addresses, excluding blacklisted and
  496. // ZeroTier-created interfaces.
  497. interfaceAddresses := make(map[string]net.IP)
  498. ifs, _ := net.Interfaces()
  499. if len(ifs) > 0 {
  500. n.networksLock.RLock()
  501. scanInterfaces:
  502. for _, i := range ifs {
  503. for _, bl := range n.localConfig.Settings.InterfacePrefixBlacklist {
  504. if strings.HasPrefix(strings.ToLower(i.Name), strings.ToLower(bl)) {
  505. continue scanInterfaces
  506. }
  507. }
  508. m, _ := NewMACFromBytes(i.HardwareAddr)
  509. if _, isZeroTier := n.networksByMAC[m]; !isZeroTier {
  510. addrs, _ := i.Addrs()
  511. for _, a := range addrs {
  512. ipn, _ := a.(*net.IPNet)
  513. if ipn != nil && len(ipn.IP) > 0 && !ipn.IP.IsLoopback() && !ipn.IP.IsMulticast() && !ipn.IP.IsInterfaceLocalMulticast() && !ipn.IP.IsLinkLocalMulticast() && !ipn.IP.IsLinkLocalUnicast() {
  514. isTemporary := false
  515. if len(ipn.IP) == 16 {
  516. var ss C.struct_sockaddr_storage
  517. if makeSockaddrStorage(ipn.IP, 0, &ss) {
  518. cIfName := C.CString(i.Name)
  519. if C.ZT_isTemporaryV6Address(cIfName, &ss) != 0 {
  520. isTemporary = true
  521. }
  522. C.free(unsafe.Pointer(cIfName))
  523. }
  524. }
  525. if !isTemporary {
  526. interfaceAddresses[ipn.IP.String()] = ipn.IP
  527. }
  528. }
  529. }
  530. }
  531. }
  532. n.networksLock.RUnlock()
  533. }
  534. // Open or close locally bound UDP ports for each local interface address.
  535. // This opens ports if they are not already open and then closes ports if
  536. // they are open but no longer seem to exist.
  537. interfaceAddressesChanged := false
  538. ports := make([]int, 0, 2)
  539. if n.localConfig.Settings.PrimaryPort > 0 && n.localConfig.Settings.PrimaryPort < 65536 {
  540. ports = append(ports, n.localConfig.Settings.PrimaryPort)
  541. }
  542. if n.localConfig.Settings.SecondaryPort > 0 && n.localConfig.Settings.SecondaryPort < 65536 {
  543. ports = append(ports, n.localConfig.Settings.SecondaryPort)
  544. }
  545. n.interfaceAddressesLock.Lock()
  546. for astr, ipn := range interfaceAddresses {
  547. if _, alreadyKnown := n.interfaceAddresses[astr]; !alreadyKnown {
  548. interfaceAddressesChanged = true
  549. ipCstr := C.CString(ipn.String())
  550. for pn, p := range ports {
  551. n.infoLog.Printf("UDP binding to port %d on interface %s", p, astr)
  552. primary := C.int(0)
  553. if pn == 0 {
  554. primary = 1
  555. }
  556. C.ZT_GoNode_phyStartListen(n.gn, nil, ipCstr, C.int(p), primary)
  557. }
  558. C.free(unsafe.Pointer(ipCstr))
  559. }
  560. }
  561. for astr, ipn := range n.interfaceAddresses {
  562. if _, stillPresent := interfaceAddresses[astr]; !stillPresent {
  563. interfaceAddressesChanged = true
  564. ipCstr := C.CString(ipn.String())
  565. for _, p := range ports {
  566. n.infoLog.Printf("UDP closing socket bound to port %d on interface %s", p, astr)
  567. C.ZT_GoNode_phyStopListen(n.gn, nil, ipCstr, C.int(p))
  568. }
  569. C.free(unsafe.Pointer(ipCstr))
  570. }
  571. }
  572. n.interfaceAddresses = interfaceAddresses
  573. n.interfaceAddressesLock.Unlock()
  574. // Update node's interface address list if detected or configured addresses have changed.
  575. if interfaceAddressesChanged || n.previousLocalConfig == nil || !reflect.DeepEqual(n.localConfig.Settings.ExplicitAddresses, n.previousLocalConfig.Settings.ExplicitAddresses) {
  576. var cAddrs []C.ZT_InterfaceAddress
  577. externalAddresses := make(map[[3]uint64]*InetAddress)
  578. for _, a := range n.localConfig.Settings.ExplicitAddresses {
  579. ak := a.key()
  580. if _, have := externalAddresses[ak]; !have {
  581. externalAddresses[ak] = &a
  582. cAddrs = append(cAddrs, C.ZT_InterfaceAddress{})
  583. makeSockaddrStorage(a.IP, a.Port, &(cAddrs[len(cAddrs)-1].address))
  584. cAddrs[len(cAddrs)-1].permanent = 1 // explicit addresses are permanent, meaning they can be put in a locator
  585. }
  586. }
  587. for _, ip := range interfaceAddresses {
  588. for _, p := range ports {
  589. a := InetAddress{IP: ip, Port: p}
  590. ak := a.key()
  591. if _, have := externalAddresses[ak]; !have {
  592. externalAddresses[ak] = &a
  593. cAddrs = append(cAddrs, C.ZT_InterfaceAddress{})
  594. makeSockaddrStorage(a.IP, a.Port, &(cAddrs[len(cAddrs)-1].address))
  595. cAddrs[len(cAddrs)-1].permanent = 0
  596. }
  597. }
  598. }
  599. if len(cAddrs) > 0 {
  600. C.ZT_Node_setInterfaceAddresses(n.zn, &cAddrs[0], C.uint(len(cAddrs)))
  601. } else {
  602. C.ZT_Node_setInterfaceAddresses(n.zn, nil, 0)
  603. }
  604. }
  605. // Trim infoLog if it's gone over its size limit
  606. if n.localConfig.Settings.LogSizeMax > 0 && n.infoLogW != nil {
  607. _ = n.infoLogW.trim(n.localConfig.Settings.LogSizeMax*1024, 0.5, true)
  608. }
  609. }
  610. func (n *Node) multicastSubscribe(nwid uint64, mg *MulticastGroup) {
  611. C.ZT_Node_multicastSubscribe(n.zn, nil, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  612. }
  613. func (n *Node) multicastUnsubscribe(nwid uint64, mg *MulticastGroup) {
  614. C.ZT_Node_multicastUnsubscribe(n.zn, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  615. }
  616. func (n *Node) pathCheck(ip net.IP) bool {
  617. n.localConfigLock.RLock()
  618. defer n.localConfigLock.RUnlock()
  619. for cidr, phy := range n.localConfig.Physical {
  620. if phy.Blacklist {
  621. _, ipn, _ := net.ParseCIDR(cidr)
  622. if ipn != nil && ipn.Contains(ip) {
  623. return false
  624. }
  625. }
  626. }
  627. return true
  628. }
  629. func (n *Node) pathLookup(id *Identity) (net.IP, int) {
  630. n.localConfigLock.RLock()
  631. defer n.localConfigLock.RUnlock()
  632. virt := n.localConfig.Virtual[id.address]
  633. if len(virt.Try) > 0 {
  634. idx := rand.Int() % len(virt.Try)
  635. return virt.Try[idx].IP, virt.Try[idx].Port
  636. }
  637. return nil, 0
  638. }
  639. func (n *Node) makeStateObjectPath(objType int, id []uint64) (string, bool) {
  640. var fp string
  641. secret := false
  642. switch objType {
  643. case C.ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  644. fp = path.Join(n.basePath, "identity.public")
  645. case C.ZT_STATE_OBJECT_IDENTITY_SECRET:
  646. fp = path.Join(n.basePath, "identity.secret")
  647. secret = true
  648. case C.ZT_STATE_OBJECT_LOCATOR:
  649. fp = path.Join(n.basePath, "locator")
  650. case C.ZT_STATE_OBJECT_PEER:
  651. fp = path.Join(n.basePath, "peers.d")
  652. _ = os.Mkdir(fp, 0700)
  653. fp = path.Join(fp, fmt.Sprintf("%.10x.peer", id[0]))
  654. secret = true
  655. case C.ZT_STATE_OBJECT_NETWORK_CONFIG:
  656. fp = path.Join(n.basePath, "networks.d")
  657. _ = os.Mkdir(fp, 0755)
  658. fp = path.Join(fp, fmt.Sprintf("%.16x.conf", id[0]))
  659. case C.ZT_STATE_OBJECT_TRUST_STORE:
  660. fp = path.Join(n.basePath, "truststore")
  661. case C.ZT_STATE_OBJECT_CERT:
  662. fp = path.Join(n.basePath, "certs.d")
  663. _ = os.Mkdir(fp, 0755)
  664. fp = path.Join(fp, Base32StdLowerCase.EncodeToString((*[48]byte)(unsafe.Pointer(&id[0]))[:]))
  665. }
  666. return fp, secret
  667. }
  668. func (n *Node) stateObjectPut(objType int, id []uint64, data []byte) {
  669. fp, secret := n.makeStateObjectPath(objType, id)
  670. if len(fp) > 0 {
  671. fileMode := os.FileMode(0644)
  672. if secret {
  673. fileMode = os.FileMode(0600)
  674. }
  675. _ = ioutil.WriteFile(fp, data, fileMode)
  676. if secret {
  677. _ = acl.Chmod(fp, 0600) // this emulates Unix chmod on Windows and uses os.Chmod on Unix-type systems
  678. }
  679. }
  680. }
  681. func (n *Node) stateObjectDelete(objType int, id []uint64) {
  682. fp, _ := n.makeStateObjectPath(objType, id)
  683. if len(fp) > 0 {
  684. _ = os.Remove(fp)
  685. }
  686. }
  687. func (n *Node) stateObjectGet(objType int, id []uint64) ([]byte, bool) {
  688. fp, _ := n.makeStateObjectPath(objType, id)
  689. if len(fp) > 0 {
  690. fd, err := ioutil.ReadFile(fp)
  691. if err != nil {
  692. return nil, false
  693. }
  694. return fd, true
  695. }
  696. return nil, false
  697. }
  698. func (n *Node) handleTrace(traceMessage string) {
  699. if len(traceMessage) > 0 {
  700. n.infoLog.Print("TRACE: " + traceMessage)
  701. }
  702. }
  703. // These are callbacks called by the core and GoGlue stuff to talk to the
  704. // service. These launch goroutines to do their work where possible to
  705. // avoid blocking anything in the core.
  706. //export goPathCheckFunc
  707. func goPathCheckFunc(gn, _ unsafe.Pointer, af C.int, ip unsafe.Pointer, _ C.int) C.int {
  708. node := cNodeRefs[uintptr(gn)]
  709. if node == nil {
  710. return 0
  711. }
  712. var nip net.IP
  713. if af == syscall.AF_INET {
  714. nip = ((*[4]byte)(ip))[:]
  715. } else if af == syscall.AF_INET6 {
  716. nip = ((*[16]byte)(ip))[:]
  717. } else {
  718. return 0
  719. }
  720. if len(nip) > 0 && node.pathCheck(nip) {
  721. return 1
  722. }
  723. return 0
  724. }
  725. //export goPathLookupFunc
  726. func goPathLookupFunc(gn unsafe.Pointer, _ C.uint64_t, _ int, identity, familyP, ipP, portP unsafe.Pointer) C.int {
  727. node := cNodeRefs[uintptr(gn)]
  728. if node == nil {
  729. return 0
  730. }
  731. id, err := newIdentityFromCIdentity(identity)
  732. if err != nil {
  733. return 0
  734. }
  735. ip, port := node.pathLookup(id)
  736. if len(ip) > 0 && port > 0 && port <= 65535 {
  737. ip4 := ip.To4()
  738. if len(ip4) == 4 {
  739. *((*C.int)(familyP)) = C.int(syscall.AF_INET)
  740. copy((*[4]byte)(ipP)[:], ip4)
  741. *((*C.int)(portP)) = C.int(port)
  742. return 1
  743. } else if len(ip) == 16 {
  744. *((*C.int)(familyP)) = C.int(syscall.AF_INET6)
  745. copy((*[16]byte)(ipP)[:], ip)
  746. *((*C.int)(portP)) = C.int(port)
  747. return 1
  748. }
  749. }
  750. return 0
  751. }
  752. //export goStateObjectPutFunc
  753. func goStateObjectPutFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, len C.int) {
  754. node := cNodeRefs[uintptr(gn)]
  755. if node == nil {
  756. return
  757. }
  758. // NOTE: this is unsafe and depends on node.stateObjectDelete() and node.stateObjectPut()
  759. // not accessing beyond the expected number of elements in the id.
  760. id2 := (*[6]uint64)(id)
  761. var data2 []byte
  762. if len > 0 {
  763. data2 = C.GoBytes(data, len)
  764. }
  765. if len < 0 {
  766. node.stateObjectDelete(int(objType), id2[:])
  767. } else {
  768. node.stateObjectPut(int(objType), id2[:], data2)
  769. }
  770. }
  771. //export goStateObjectGetFunc
  772. func goStateObjectGetFunc(gn unsafe.Pointer, objType C.int, id, dataP unsafe.Pointer) C.int {
  773. node := cNodeRefs[uintptr(gn)]
  774. if node == nil {
  775. return -1
  776. }
  777. *((*uintptr)(dataP)) = 0
  778. tmp, found := node.stateObjectGet(int(objType), ((*[6]uint64)(id))[:])
  779. if found && len(tmp) > 0 {
  780. cData := C.ZT_malloc(C.ulong(len(tmp))) // GoGlue sends free() to the core as the free function
  781. if uintptr(cData) == 0 {
  782. return -1
  783. }
  784. *((*uintptr)(dataP)) = uintptr(cData)
  785. return C.int(len(tmp))
  786. }
  787. return -1
  788. }
  789. //export goVirtualNetworkConfigFunc
  790. func goVirtualNetworkConfigFunc(gn, _ unsafe.Pointer, nwid C.uint64_t, op C.int, conf unsafe.Pointer) {
  791. node := cNodeRefs[uintptr(gn)]
  792. if node == nil {
  793. return
  794. }
  795. node.networksLock.RLock()
  796. network := node.networks[NetworkID(nwid)]
  797. node.networksLock.RUnlock()
  798. if network != nil {
  799. switch int(op) {
  800. case networkConfigOpUp, networkConfigOpUpdate:
  801. ncc := (*C.ZT_VirtualNetworkConfig)(conf)
  802. if network.networkConfigRevision() > uint64(ncc.netconfRevision) {
  803. return
  804. }
  805. var nc NetworkConfig
  806. nc.ID = NetworkID(ncc.nwid)
  807. nc.MAC = MAC(ncc.mac)
  808. nc.Name = C.GoString(&ncc.name[0])
  809. nc.Status = int(ncc.status)
  810. nc.Type = int(ncc._type)
  811. nc.MTU = int(ncc.mtu)
  812. nc.Bridge = ncc.bridge != 0
  813. nc.BroadcastEnabled = ncc.broadcastEnabled != 0
  814. nc.NetconfRevision = uint64(ncc.netconfRevision)
  815. for i := 0; i < int(ncc.assignedAddressCount); i++ {
  816. a := sockaddrStorageToIPNet(&ncc.assignedAddresses[i])
  817. if a != nil {
  818. nc.AssignedAddresses = append(nc.AssignedAddresses, *a)
  819. }
  820. }
  821. for i := 0; i < int(ncc.routeCount); i++ {
  822. tgt := sockaddrStorageToIPNet(&ncc.routes[i].target)
  823. viaN := sockaddrStorageToIPNet(&ncc.routes[i].via)
  824. var via *net.IP
  825. if viaN != nil && len(viaN.IP) > 0 {
  826. via = &viaN.IP
  827. }
  828. if tgt != nil {
  829. nc.Routes = append(nc.Routes, Route{
  830. Target: *tgt,
  831. Via: via,
  832. Flags: uint16(ncc.routes[i].flags),
  833. Metric: uint16(ncc.routes[i].metric),
  834. })
  835. }
  836. }
  837. node.runWaitGroup.Add(1)
  838. go func() {
  839. network.updateConfig(&nc, nil)
  840. node.runWaitGroup.Done()
  841. }()
  842. }
  843. }
  844. }
  845. //export goZtEvent
  846. func goZtEvent(gn unsafe.Pointer, eventType C.int, data unsafe.Pointer) {
  847. node := cNodeRefs[uintptr(gn)]
  848. if node == nil {
  849. return
  850. }
  851. switch eventType {
  852. case C.ZT_EVENT_OFFLINE:
  853. atomic.StoreUint32(&node.online, 0)
  854. case C.ZT_EVENT_ONLINE:
  855. atomic.StoreUint32(&node.online, 1)
  856. }
  857. }