node.go 26 KB

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