node.go 28 KB

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