node.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. /*
  2. * Copyright (c)2019 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: 2023-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. "encoding/binary"
  22. "errors"
  23. "fmt"
  24. "io/ioutil"
  25. "log"
  26. "math/rand"
  27. "net"
  28. "net/http"
  29. "os"
  30. "path"
  31. "sort"
  32. "strings"
  33. "sync"
  34. "sync/atomic"
  35. "time"
  36. "unsafe"
  37. "github.com/hectane/go-acl"
  38. )
  39. var nullLogger = log.New(ioutil.Discard, "", 0)
  40. // Network status states
  41. const (
  42. NetworkStatusRequestConfiguration int = C.ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION
  43. NetworkStatusOK int = C.ZT_NETWORK_STATUS_OK
  44. NetworkStatusAccessDenied int = C.ZT_NETWORK_STATUS_ACCESS_DENIED
  45. NetworkStatusNotFound int = C.ZT_NETWORK_STATUS_NOT_FOUND
  46. NetworkTypePrivate int = C.ZT_NETWORK_TYPE_PRIVATE
  47. NetworkTypePublic int = C.ZT_NETWORK_TYPE_PUBLIC
  48. // CoreVersionMajor is the major version of the ZeroTier core
  49. CoreVersionMajor int = C.ZEROTIER_ONE_VERSION_MAJOR
  50. // CoreVersionMinor is the minor version of the ZeroTier core
  51. CoreVersionMinor int = C.ZEROTIER_ONE_VERSION_MINOR
  52. // CoreVersionRevision is the revision of the ZeroTier core
  53. CoreVersionRevision int = C.ZEROTIER_ONE_VERSION_REVISION
  54. // CoreVersionBuild is the build version of the ZeroTier core
  55. CoreVersionBuild int = C.ZEROTIER_ONE_VERSION_BUILD
  56. // AFInet is the address family for IPv4
  57. AFInet = C.AF_INET
  58. // AFInet6 is the address family for IPv6
  59. AFInet6 = C.AF_INET6
  60. defaultVirtualNetworkMTU = C.ZT_DEFAULT_MTU
  61. )
  62. var (
  63. // PlatformDefaultHomePath is the default location of ZeroTier's working path on this system
  64. PlatformDefaultHomePath string = C.GoString(C.ZT_PLATFORM_DEFAULT_HOMEPATH)
  65. // This map is used to get the Go Node object from a pointer passed back in via C callbacks
  66. nodesByUserPtr = make(map[uintptr]*Node)
  67. nodesByUserPtrLock sync.RWMutex
  68. )
  69. func sockaddrStorageToIPNet(ss *C.struct_sockaddr_storage) *net.IPNet {
  70. var a net.IPNet
  71. switch ss.ss_family {
  72. case AFInet:
  73. sa4 := (*C.struct_sockaddr_in)(unsafe.Pointer(ss))
  74. var ip4 [4]byte
  75. copy(ip4[:], (*[4]byte)(unsafe.Pointer(&sa4.sin_addr))[:])
  76. a.IP = ip4[:]
  77. a.Mask = net.CIDRMask(int(binary.BigEndian.Uint16(((*[2]byte)(unsafe.Pointer(&sa4.sin_port)))[:])), 32)
  78. return &a
  79. case AFInet6:
  80. sa6 := (*C.struct_sockaddr_in6)(unsafe.Pointer(ss))
  81. var ip6 [16]byte
  82. copy(ip6[:], (*[16]byte)(unsafe.Pointer(&sa6.sin6_addr))[:])
  83. a.IP = ip6[:]
  84. a.Mask = net.CIDRMask(int(binary.BigEndian.Uint16(((*[2]byte)(unsafe.Pointer(&sa6.sin6_port)))[:])), 128)
  85. return &a
  86. }
  87. return nil
  88. }
  89. func sockaddrStorageToUDPAddr(ss *C.struct_sockaddr_storage) *net.UDPAddr {
  90. var a net.UDPAddr
  91. switch ss.ss_family {
  92. case AFInet:
  93. sa4 := (*C.struct_sockaddr_in)(unsafe.Pointer(ss))
  94. var ip4 [4]byte
  95. copy(ip4[:], (*[4]byte)(unsafe.Pointer(&sa4.sin_addr))[:])
  96. a.IP = ip4[:]
  97. a.Port = int(binary.BigEndian.Uint16(((*[2]byte)(unsafe.Pointer(&sa4.sin_port)))[:]))
  98. return &a
  99. case AFInet6:
  100. sa6 := (*C.struct_sockaddr_in6)(unsafe.Pointer(ss))
  101. var ip6 [16]byte
  102. copy(ip6[:], (*[16]byte)(unsafe.Pointer(&sa6.sin6_addr))[:])
  103. a.IP = ip6[:]
  104. a.Port = int(binary.BigEndian.Uint16(((*[2]byte)(unsafe.Pointer(&sa6.sin6_port)))[:]))
  105. return &a
  106. }
  107. return nil
  108. }
  109. func sockaddrStorageToUDPAddr2(ss unsafe.Pointer) *net.UDPAddr {
  110. return sockaddrStorageToUDPAddr((*C.struct_sockaddr_storage)(ss))
  111. }
  112. func makeSockaddrStorage(ip net.IP, port int, ss *C.struct_sockaddr_storage) bool {
  113. C.memset(unsafe.Pointer(ss), 0, C.sizeof_struct_sockaddr_storage)
  114. if len(ip) == 4 {
  115. sa4 := (*C.struct_sockaddr_in)(unsafe.Pointer(ss))
  116. sa4.sin_family = AFInet
  117. copy(((*[4]byte)(unsafe.Pointer(&sa4.sin_addr)))[:], ip)
  118. binary.BigEndian.PutUint16(((*[2]byte)(unsafe.Pointer(&sa4.sin_port)))[:], uint16(port))
  119. return true
  120. }
  121. if len(ip) == 16 {
  122. sa6 := (*C.struct_sockaddr_in6)(unsafe.Pointer(ss))
  123. sa6.sin6_family = AFInet6
  124. copy(((*[16]byte)(unsafe.Pointer(&sa6.sin6_addr)))[:], ip)
  125. binary.BigEndian.PutUint16(((*[2]byte)(unsafe.Pointer(&sa6.sin6_port)))[:], uint16(port))
  126. return true
  127. }
  128. return false
  129. }
  130. //////////////////////////////////////////////////////////////////////////////
  131. // Node is an instance of the ZeroTier core node and related C++ I/O code
  132. type Node struct {
  133. networks map[NetworkID]*Network
  134. networksByMAC map[MAC]*Network // locked by networksLock
  135. interfaceAddresses map[string]net.IP // physical external IPs on the machine
  136. basePath string
  137. localConfigPath string
  138. localConfig LocalConfig
  139. localConfigLock sync.RWMutex
  140. networksLock sync.RWMutex
  141. interfaceAddressesLock sync.Mutex
  142. logW *sizeLimitWriter
  143. log *log.Logger
  144. gn *C.ZT_GoNode
  145. zn *C.ZT_Node
  146. id *Identity
  147. apiServer *http.Server
  148. online uint32
  149. running uint32
  150. runLock sync.Mutex
  151. }
  152. // NewNode creates and initializes a new instance of the ZeroTier node service
  153. func NewNode(basePath string) (*Node, error) {
  154. var err error
  155. _ = os.MkdirAll(basePath, 0755)
  156. if _, err := os.Stat(basePath); err != nil {
  157. return nil, err
  158. }
  159. n := new(Node)
  160. n.networks = make(map[NetworkID]*Network)
  161. n.networksByMAC = make(map[MAC]*Network)
  162. n.interfaceAddresses = make(map[string]net.IP)
  163. n.basePath = basePath
  164. n.localConfigPath = path.Join(basePath, "local.conf")
  165. err = n.localConfig.Read(n.localConfigPath, true)
  166. if err != nil {
  167. return nil, err
  168. }
  169. if n.localConfig.Settings.LogSizeMax >= 0 {
  170. n.logW, err = sizeLimitWriterOpen(path.Join(basePath, "service.log"))
  171. if err != nil {
  172. return nil, err
  173. }
  174. n.log = log.New(n.logW, "", log.LstdFlags)
  175. } else {
  176. n.log = nullLogger
  177. }
  178. if n.localConfig.Settings.PortSearch {
  179. portsChanged := false
  180. portCheckCount := 0
  181. for portCheckCount < 2048 {
  182. portCheckCount++
  183. if checkPort(n.localConfig.Settings.PrimaryPort) {
  184. break
  185. }
  186. n.log.Printf("primary port %d unavailable, trying next port (port search enabled)", n.localConfig.Settings.PrimaryPort)
  187. n.localConfig.Settings.PrimaryPort++
  188. n.localConfig.Settings.PrimaryPort &= 0xffff
  189. portsChanged = true
  190. }
  191. if portCheckCount == 2048 {
  192. return nil, errors.New("unable to bind to primary port, tried 2048 later ports")
  193. }
  194. if n.localConfig.Settings.SecondaryPort > 0 {
  195. portCheckCount = 0
  196. for portCheckCount < 2048 {
  197. portCheckCount++
  198. if checkPort(n.localConfig.Settings.SecondaryPort) {
  199. break
  200. }
  201. n.log.Printf("secondary port %d unavailable, trying next port (port search enabled)", n.localConfig.Settings.SecondaryPort)
  202. n.localConfig.Settings.SecondaryPort++
  203. n.localConfig.Settings.SecondaryPort &= 0xffff
  204. portsChanged = true
  205. }
  206. if portCheckCount == 2048 {
  207. n.localConfig.Settings.SecondaryPort = 0
  208. }
  209. }
  210. if n.localConfig.Settings.TertiaryPort > 0 {
  211. portCheckCount = 0
  212. for portCheckCount < 2048 {
  213. portCheckCount++
  214. if checkPort(n.localConfig.Settings.TertiaryPort) {
  215. break
  216. }
  217. n.log.Printf("tertiary port %d unavailable, trying next port (port search enabled)", n.localConfig.Settings.TertiaryPort)
  218. n.localConfig.Settings.TertiaryPort++
  219. n.localConfig.Settings.TertiaryPort &= 0xffff
  220. portsChanged = true
  221. }
  222. if portCheckCount == 2048 {
  223. n.localConfig.Settings.TertiaryPort = 0
  224. }
  225. }
  226. if portsChanged {
  227. _ = n.localConfig.Write(n.localConfigPath)
  228. }
  229. } else if !checkPort(n.localConfig.Settings.PrimaryPort) {
  230. return nil, errors.New("unable to bind to primary port")
  231. }
  232. cPath := C.CString(basePath)
  233. n.gn = C.ZT_GoNode_new(cPath)
  234. C.free(unsafe.Pointer(cPath))
  235. if n.gn == nil {
  236. n.log.Println("FATAL: node initialization failed")
  237. return nil, ErrNodeInitFailed
  238. }
  239. n.zn = (*C.ZT_Node)(C.ZT_GoNode_getNode(n.gn))
  240. var ns C.ZT_NodeStatus
  241. C.ZT_Node_status(unsafe.Pointer(n.zn), &ns)
  242. idString := C.GoString(ns.secretIdentity)
  243. n.id, err = NewIdentityFromString(idString)
  244. if err != nil {
  245. n.log.Printf("FATAL: node's identity does not seem valid (%s)", string(idString))
  246. C.ZT_GoNode_delete(n.gn)
  247. return nil, err
  248. }
  249. n.apiServer, err = createAPIServer(basePath, n)
  250. if err != nil {
  251. n.log.Printf("FATAL: unable to start API server: %s", err.Error())
  252. C.ZT_GoNode_delete(n.gn)
  253. return nil, err
  254. }
  255. gnRawAddr := uintptr(unsafe.Pointer(n.gn))
  256. nodesByUserPtrLock.Lock()
  257. nodesByUserPtr[gnRawAddr] = n
  258. nodesByUserPtrLock.Unlock()
  259. n.online = 0
  260. n.running = 1
  261. n.runLock.Lock() // used to block Close() until below gorountine exits
  262. go func() {
  263. lastMaintenanceRun := int64(0)
  264. for atomic.LoadUint32(&n.running) != 0 {
  265. time.Sleep(1 * time.Second)
  266. now := TimeMs()
  267. if (now - lastMaintenanceRun) >= 30000 {
  268. lastMaintenanceRun = now
  269. n.localConfigLock.RLock()
  270. // Get local physical interface addresses, excluding blacklisted and ZeroTier-created interfaces
  271. interfaceAddresses := make(map[string]net.IP)
  272. ifs, _ := net.Interfaces()
  273. if len(ifs) > 0 {
  274. n.networksLock.RLock()
  275. scanInterfaces:
  276. for _, i := range ifs {
  277. for _, bl := range n.localConfig.Settings.InterfacePrefixBlacklist {
  278. if strings.HasPrefix(strings.ToLower(i.Name), strings.ToLower(bl)) {
  279. continue scanInterfaces
  280. }
  281. }
  282. m, _ := NewMACFromBytes(i.HardwareAddr)
  283. if _, isZeroTier := n.networksByMAC[m]; !isZeroTier {
  284. addrs, _ := i.Addrs()
  285. if len(addrs) > 0 {
  286. for _, a := range addrs {
  287. ipn, _ := a.(*net.IPNet)
  288. if ipn != nil {
  289. interfaceAddresses[ipn.IP.String()] = ipn.IP
  290. }
  291. }
  292. }
  293. }
  294. }
  295. n.networksLock.RUnlock()
  296. }
  297. // Open or close locally bound UDP ports for each local interface address.
  298. // This opens ports if they are not already open and then closes ports if
  299. // they are open but no longer seem to exist.
  300. n.interfaceAddressesLock.Lock()
  301. for astr, ipn := range interfaceAddresses {
  302. if _, alreadyKnown := n.interfaceAddresses[astr]; !alreadyKnown {
  303. ipCstr := C.CString(ipn.String())
  304. if n.localConfig.Settings.PrimaryPort > 0 && n.localConfig.Settings.PrimaryPort < 65536 {
  305. n.log.Printf("UDP binding to port %d on interface %s", n.localConfig.Settings.PrimaryPort, astr)
  306. C.ZT_GoNode_phyStartListen(n.gn, nil, ipCstr, C.int(n.localConfig.Settings.PrimaryPort))
  307. }
  308. if n.localConfig.Settings.SecondaryPort > 0 && n.localConfig.Settings.SecondaryPort < 65536 {
  309. n.log.Printf("UDP binding to port %d on interface %s", n.localConfig.Settings.SecondaryPort, astr)
  310. C.ZT_GoNode_phyStartListen(n.gn, nil, ipCstr, C.int(n.localConfig.Settings.SecondaryPort))
  311. }
  312. if n.localConfig.Settings.TertiaryPort > 0 && n.localConfig.Settings.TertiaryPort < 65536 {
  313. n.log.Printf("UDP binding to port %d on interface %s", n.localConfig.Settings.TertiaryPort, astr)
  314. C.ZT_GoNode_phyStartListen(n.gn, nil, ipCstr, C.int(n.localConfig.Settings.TertiaryPort))
  315. }
  316. C.free(unsafe.Pointer(ipCstr))
  317. }
  318. }
  319. for astr, ipn := range n.interfaceAddresses {
  320. if _, stillPresent := interfaceAddresses[astr]; !stillPresent {
  321. ipCstr := C.CString(ipn.String())
  322. if n.localConfig.Settings.PrimaryPort > 0 && n.localConfig.Settings.PrimaryPort < 65536 {
  323. n.log.Printf("UDP closing socket bound to port %d on interface %s", n.localConfig.Settings.PrimaryPort, astr)
  324. C.ZT_GoNode_phyStopListen(n.gn, nil, ipCstr, C.int(n.localConfig.Settings.PrimaryPort))
  325. }
  326. if n.localConfig.Settings.SecondaryPort > 0 && n.localConfig.Settings.SecondaryPort < 65536 {
  327. n.log.Printf("UDP closing socket bound to port %d on interface %s", n.localConfig.Settings.SecondaryPort, astr)
  328. C.ZT_GoNode_phyStopListen(n.gn, nil, ipCstr, C.int(n.localConfig.Settings.SecondaryPort))
  329. }
  330. if n.localConfig.Settings.TertiaryPort > 0 && n.localConfig.Settings.TertiaryPort < 65536 {
  331. n.log.Printf("UDP closing socket bound to port %d on interface %s", n.localConfig.Settings.TertiaryPort, astr)
  332. C.ZT_GoNode_phyStopListen(n.gn, nil, ipCstr, C.int(n.localConfig.Settings.TertiaryPort))
  333. }
  334. C.free(unsafe.Pointer(ipCstr))
  335. }
  336. }
  337. n.interfaceAddresses = interfaceAddresses
  338. n.interfaceAddressesLock.Unlock()
  339. // Trim log if it's gone over its size limit
  340. if n.localConfig.Settings.LogSizeMax > 0 && n.logW != nil {
  341. _ = n.logW.trim(n.localConfig.Settings.LogSizeMax*1024, 0.5, true)
  342. }
  343. n.localConfigLock.RUnlock()
  344. }
  345. }
  346. n.runLock.Unlock() // signal Close() that maintenance goroutine is done
  347. }()
  348. return n, nil
  349. }
  350. // Close closes this Node and frees its underlying C++ Node structures
  351. func (n *Node) Close() {
  352. if atomic.SwapUint32(&n.running, 0) != 0 {
  353. _ = n.apiServer.Close()
  354. C.ZT_GoNode_delete(n.gn)
  355. nodesByUserPtrLock.Lock()
  356. delete(nodesByUserPtr, uintptr(unsafe.Pointer(n.gn)))
  357. nodesByUserPtrLock.Unlock()
  358. n.runLock.Lock() // wait for maintenance gorountine to die
  359. n.runLock.Unlock()
  360. }
  361. }
  362. // Address returns this node's address
  363. func (n *Node) Address() Address { return n.id.address }
  364. // Identity returns this node's identity (including secret portion)
  365. func (n *Node) Identity() *Identity { return n.id }
  366. // Online returns true if this node can reach something
  367. func (n *Node) Online() bool { return atomic.LoadUint32(&n.online) != 0 }
  368. // InterfaceAddresses are external IPs belonging to physical interfaces on this machine
  369. func (n *Node) InterfaceAddresses() []net.IP {
  370. var ea []net.IP
  371. n.interfaceAddressesLock.Lock()
  372. for _, a := range n.interfaceAddresses {
  373. ea = append(ea, a)
  374. }
  375. n.interfaceAddressesLock.Unlock()
  376. sort.Slice(ea, func(a, b int) bool { return bytes.Compare(ea[a], ea[b]) < 0 })
  377. return ea
  378. }
  379. // LocalConfig gets this node's local configuration
  380. func (n *Node) LocalConfig() LocalConfig {
  381. n.localConfigLock.RLock()
  382. defer n.localConfigLock.RUnlock()
  383. return n.localConfig
  384. }
  385. // SetLocalConfig updates this node's local configuration
  386. func (n *Node) SetLocalConfig(lc *LocalConfig) (restartRequired bool, err error) {
  387. n.networksLock.RLock()
  388. n.localConfigLock.Lock()
  389. defer n.localConfigLock.Unlock()
  390. defer n.networksLock.RUnlock()
  391. for nid, nc := range lc.Network {
  392. nw := n.networks[nid]
  393. if nw != nil {
  394. nw.SetLocalSettings(nc)
  395. }
  396. }
  397. if n.localConfig.Settings.PrimaryPort != lc.Settings.PrimaryPort || n.localConfig.Settings.SecondaryPort != lc.Settings.SecondaryPort || n.localConfig.Settings.TertiaryPort != lc.Settings.TertiaryPort {
  398. restartRequired = true
  399. }
  400. if lc.Settings.LogSizeMax < 0 {
  401. n.log = nullLogger
  402. _ = n.logW.Close()
  403. n.logW = nil
  404. } else if n.logW != nil {
  405. n.logW, err = sizeLimitWriterOpen(path.Join(n.basePath, "service.log"))
  406. if err == nil {
  407. n.log = log.New(n.logW, "", log.LstdFlags)
  408. } else {
  409. n.log = nullLogger
  410. n.logW = nil
  411. }
  412. }
  413. n.localConfig = *lc
  414. return
  415. }
  416. // Join joins a network
  417. // If tap is nil, the default system tap for this OS/platform is used (if available).
  418. func (n *Node) Join(nwid NetworkID, settings *NetworkLocalSettings, tap Tap) (*Network, error) {
  419. n.networksLock.RLock()
  420. if nw, have := n.networks[nwid]; have {
  421. n.log.Printf("join network %.16x ignored: already a member", nwid)
  422. if settings != nil {
  423. nw.SetLocalSettings(settings)
  424. }
  425. return nw, nil
  426. }
  427. n.networksLock.RUnlock()
  428. if tap != nil {
  429. panic("non-native taps not yet implemented")
  430. }
  431. ntap := C.ZT_GoNode_join(n.gn, C.uint64_t(nwid))
  432. if ntap == nil {
  433. n.log.Printf("join network %.16x failed: tap device failed to initialize (check drivers / kernel modules)", uint64(nwid))
  434. return nil, ErrTapInitFailed
  435. }
  436. nw, err := newNetwork(n, nwid, &nativeTap{tap: unsafe.Pointer(ntap), enabled: 1})
  437. if err != nil {
  438. n.log.Printf("join network %.16x failed: network failed to initialize: %s", nwid, err.Error())
  439. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  440. return nil, err
  441. }
  442. n.networksLock.Lock()
  443. n.networks[nwid] = nw
  444. n.networksLock.Unlock()
  445. if settings != nil {
  446. nw.SetLocalSettings(settings)
  447. }
  448. return nw, nil
  449. }
  450. // Leave leaves a network
  451. func (n *Node) Leave(nwid NetworkID) error {
  452. n.log.Printf("leaving network %.16x", nwid)
  453. n.networksLock.Lock()
  454. nw := n.networks[nwid]
  455. delete(n.networks, nwid)
  456. n.networksLock.Unlock()
  457. if nw != nil {
  458. nw.leaving()
  459. }
  460. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  461. return nil
  462. }
  463. // GetNetwork looks up a network by ID or returns nil if not joined
  464. func (n *Node) GetNetwork(nwid NetworkID) *Network {
  465. n.networksLock.RLock()
  466. nw := n.networks[nwid]
  467. n.networksLock.RUnlock()
  468. return nw
  469. }
  470. // Networks returns a list of networks that this node has joined
  471. func (n *Node) Networks() []*Network {
  472. var nws []*Network
  473. n.networksLock.RLock()
  474. for _, nw := range n.networks {
  475. nws = append(nws, nw)
  476. }
  477. n.networksLock.RUnlock()
  478. return nws
  479. }
  480. // Roots retrieves a list of root servers on this node and their preferred and online status.
  481. func (n *Node) Roots() []*Root {
  482. var roots []*Root
  483. rl := C.ZT_Node_listRoots(unsafe.Pointer(n.zn), C.int64_t(TimeMs()))
  484. if rl != nil {
  485. for i := 0; i < int(rl.count); i++ {
  486. root := (*C.ZT_Root)(unsafe.Pointer(uintptr(unsafe.Pointer(rl)) + C.sizeof_ZT_RootList))
  487. id, err := NewIdentityFromString(C.GoString(root.identity))
  488. if err == nil {
  489. var addrs []InetAddress
  490. for j := uintptr(0); j < uintptr(root.addressCount); j++ {
  491. a := NewInetAddressFromSockaddr(unsafe.Pointer(uintptr(unsafe.Pointer(root.addresses)) + (j * C.sizeof_struct_sockaddr_storage)))
  492. if a != nil && a.Valid() {
  493. addrs = append(addrs, *a)
  494. }
  495. }
  496. roots = append(roots, &Root{
  497. Name: C.GoString(root.name),
  498. Identity: id,
  499. Addresses: addrs,
  500. Preferred: root.preferred != 0,
  501. Online: root.online != 0,
  502. })
  503. }
  504. }
  505. C.ZT_Node_freeQueryResult(unsafe.Pointer(n.zn), unsafe.Pointer(rl))
  506. }
  507. return roots
  508. }
  509. // SetRoot sets or updates a root.
  510. // Name can be a DNS name (preferably secure) for DNS fetched locators or can be
  511. // the empty string for static roots. If the name is empty then the locator must
  512. // be non-nil.
  513. func (n *Node) SetRoot(name string, locator *Locator) error {
  514. if len(name) == 0 {
  515. if locator == nil {
  516. return ErrInvalidParameter
  517. }
  518. name = locator.Identity.address.String()
  519. }
  520. var lb []byte
  521. if locator != nil {
  522. lb = locator.Bytes()
  523. }
  524. var lbp unsafe.Pointer
  525. if len(lb) > 0 {
  526. lbp = &lb[0]
  527. }
  528. cn := C.CString(name)
  529. defer C.free(unsafe.Pointer(cn))
  530. if C.ZT_Node_setRoot(unsafe.Pointer(n.zn), cn, lbp, C.uint(len(lb))) != 0 {
  531. return ErrInternal
  532. }
  533. return nil
  534. }
  535. // RemoveRoot removes a root.
  536. // For static roots the name should be the ZeroTier address.
  537. func (n *Node) RemoveRoot(name string) {
  538. cn := C.CString(name)
  539. defer C.free(unsafe.Pointer(cn))
  540. C.ZT_Node_removeRoot(unsafe.Pointer(n.zn), cn)
  541. return
  542. }
  543. // Peers retrieves a list of current peers
  544. func (n *Node) Peers() []*Peer {
  545. var peers []*Peer
  546. pl := C.ZT_Node_peers(unsafe.Pointer(n.zn))
  547. if pl != nil {
  548. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  549. p := (*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer)))
  550. p2 := new(Peer)
  551. p2.Address = Address(p.address)
  552. p2.Version = [3]int{int(p.versionMajor), int(p.versionMinor), int(p.versionRev)}
  553. p2.Latency = int(p.latency)
  554. p2.Role = int(p.role)
  555. p2.Paths = make([]Path, 0, int(p.pathCount))
  556. usingAllocation := false
  557. for j := uintptr(0); j < uintptr(p.pathCount); j++ {
  558. pt := &p.paths[j]
  559. if pt.alive != 0 {
  560. a := sockaddrStorageToUDPAddr(&pt.address)
  561. if a != nil {
  562. alloc := float32(pt.allocation)
  563. if alloc > 0.0 {
  564. usingAllocation = true
  565. }
  566. p2.Paths = append(p2.Paths, Path{
  567. IP: a.IP,
  568. Port: a.Port,
  569. LastSend: int64(pt.lastSend),
  570. LastReceive: int64(pt.lastReceive),
  571. TrustedPathID: uint64(pt.trustedPathId),
  572. Latency: float32(pt.latency),
  573. PacketDelayVariance: float32(pt.packetDelayVariance),
  574. ThroughputDisturbCoeff: float32(pt.throughputDisturbCoeff),
  575. PacketErrorRatio: float32(pt.packetErrorRatio),
  576. PacketLossRatio: float32(pt.packetLossRatio),
  577. Stability: float32(pt.stability),
  578. Throughput: uint64(pt.throughput),
  579. MaxThroughput: uint64(pt.maxThroughput),
  580. Allocation: alloc,
  581. })
  582. }
  583. }
  584. }
  585. if !usingAllocation { // if all allocations are zero fall back to single path mode that uses the preferred flag
  586. for i, j := 0, uintptr(0); j < uintptr(p.pathCount); j++ {
  587. pt := &p.paths[j]
  588. if pt.alive != 0 {
  589. if pt.preferred == 0 {
  590. p2.Paths[i].Allocation = 0.0
  591. } else {
  592. p2.Paths[i].Allocation = 1.0
  593. }
  594. i++
  595. }
  596. }
  597. }
  598. sort.Slice(p2.Paths, func(a, b int) bool {
  599. pa := &p2.Paths[a]
  600. pb := &p2.Paths[b]
  601. if pb.Allocation < pa.Allocation { // invert order, put highest allocation paths first
  602. return true
  603. }
  604. if pa.Allocation == pb.Allocation {
  605. return pa.LastReceive < pb.LastReceive // then sort by most recent activity
  606. }
  607. return false
  608. })
  609. p2.Clock = TimeMs()
  610. peers = append(peers, p2)
  611. }
  612. C.ZT_Node_freeQueryResult(unsafe.Pointer(n.zn), unsafe.Pointer(pl))
  613. }
  614. sort.Slice(peers, func(a, b int) bool {
  615. return peers[a].Address < peers[b].Address
  616. })
  617. return peers
  618. }
  619. //////////////////////////////////////////////////////////////////////////////
  620. func (n *Node) multicastSubscribe(nwid uint64, mg *MulticastGroup) {
  621. C.ZT_Node_multicastSubscribe(unsafe.Pointer(n.zn), nil, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  622. }
  623. func (n *Node) multicastUnsubscribe(nwid uint64, mg *MulticastGroup) {
  624. C.ZT_Node_multicastUnsubscribe(unsafe.Pointer(n.zn), C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  625. }
  626. func (n *Node) pathCheck(ztAddress Address, af int, ip net.IP, port int) bool {
  627. n.localConfigLock.RLock()
  628. defer n.localConfigLock.RUnlock()
  629. for cidr, phy := range n.localConfig.Physical {
  630. if phy.Blacklist {
  631. _, ipn, _ := net.ParseCIDR(cidr)
  632. if ipn != nil && ipn.Contains(ip) {
  633. return false
  634. }
  635. }
  636. }
  637. return true
  638. }
  639. func (n *Node) pathLookup(ztAddress Address) (net.IP, int) {
  640. n.localConfigLock.RLock()
  641. defer n.localConfigLock.RUnlock()
  642. virt := n.localConfig.Virtual[ztAddress]
  643. if virt != nil && len(virt.Try) > 0 {
  644. idx := rand.Int() % len(virt.Try)
  645. return virt.Try[idx].IP, virt.Try[idx].Port
  646. }
  647. return nil, 0
  648. }
  649. func (n *Node) makeStateObjectPath(objType int, id [2]uint64) (string, bool) {
  650. var fp string
  651. secret := false
  652. switch objType {
  653. case C.ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  654. fp = path.Join(n.basePath, "identity.public")
  655. case C.ZT_STATE_OBJECT_IDENTITY_SECRET:
  656. fp = path.Join(n.basePath, "identity.secret")
  657. secret = true
  658. case C.ZT_STATE_OBJECT_PEER:
  659. fp = path.Join(n.basePath, "peers.d")
  660. _ = os.Mkdir(fp, 0700)
  661. fp = path.Join(fp, fmt.Sprintf("%.10x.peer", id[0]))
  662. secret = true
  663. case C.ZT_STATE_OBJECT_NETWORK_CONFIG:
  664. fp = path.Join(n.basePath, "networks.d")
  665. _ = os.Mkdir(fp, 0755)
  666. fp = path.Join(fp, fmt.Sprintf("%.16x.conf", id[0]))
  667. case C.ZT_STATE_OBJECT_ROOT_LIST:
  668. fp = path.Join(n.basePath, "roots")
  669. }
  670. return fp, secret
  671. }
  672. func (n *Node) stateObjectPut(objType int, id [2]uint64, data []byte) {
  673. fp, secret := n.makeStateObjectPath(objType, id)
  674. if len(fp) > 0 {
  675. fileMode := os.FileMode(0644)
  676. if secret {
  677. fileMode = os.FileMode(0600)
  678. }
  679. _ = ioutil.WriteFile(fp, data, fileMode)
  680. if secret {
  681. _ = acl.Chmod(fp, 0600) // this emulates Unix chmod on Windows and uses os.Chmod on Unix-type systems
  682. }
  683. }
  684. }
  685. func (n *Node) stateObjectDelete(objType int, id [2]uint64) {
  686. fp, _ := n.makeStateObjectPath(objType, id)
  687. if len(fp) > 0 {
  688. _ = os.Remove(fp)
  689. }
  690. }
  691. func (n *Node) stateObjectGet(objType int, id [2]uint64) ([]byte, bool) {
  692. fp, _ := n.makeStateObjectPath(objType, id)
  693. if len(fp) > 0 {
  694. fd, err := ioutil.ReadFile(fp)
  695. if err != nil {
  696. return nil, false
  697. }
  698. return fd, true
  699. }
  700. return nil, false
  701. }
  702. func (n *Node) handleTrace(traceMessage string) {
  703. if len(traceMessage) > 0 {
  704. n.log.Print("TRACE: " + traceMessage)
  705. }
  706. }
  707. func (n *Node) handleUserMessage(originAddress, messageTypeID uint64, data []byte) {
  708. }
  709. func (n *Node) handleRemoteTrace(originAddress uint64, dictData []byte) {
  710. }
  711. //////////////////////////////////////////////////////////////////////////////
  712. // These are callbacks called by the core and GoGlue stuff to talk to the
  713. // service. These launch gorountines to do their work where possible to
  714. // avoid blocking anything in the core.
  715. //export goPathCheckFunc
  716. func goPathCheckFunc(gn unsafe.Pointer, ztAddress C.uint64_t, af C.int, ip unsafe.Pointer, port C.int) C.int {
  717. nodesByUserPtrLock.RLock()
  718. node := nodesByUserPtr[uintptr(gn)]
  719. nodesByUserPtrLock.RUnlock()
  720. var nip net.IP
  721. if af == AFInet {
  722. nip = ((*[4]byte)(ip))[:]
  723. } else if af == AFInet6 {
  724. nip = ((*[16]byte)(ip))[:]
  725. } else {
  726. return 0
  727. }
  728. if node != nil && len(nip) > 0 && node.pathCheck(Address(ztAddress), int(af), nip, int(port)) {
  729. return 1
  730. }
  731. return 0
  732. }
  733. //export goPathLookupFunc
  734. func goPathLookupFunc(gn unsafe.Pointer, ztAddress C.uint64_t, _ int, familyP, ipP, portP unsafe.Pointer) C.int {
  735. nodesByUserPtrLock.RLock()
  736. node := nodesByUserPtr[uintptr(gn)]
  737. nodesByUserPtrLock.RUnlock()
  738. if node == nil {
  739. return 0
  740. }
  741. ip, port := node.pathLookup(Address(ztAddress))
  742. if len(ip) > 0 && port > 0 && port <= 65535 {
  743. ip4 := ip.To4()
  744. if len(ip4) == 4 {
  745. *((*C.int)(familyP)) = C.int(AFInet)
  746. copy((*[4]byte)(ipP)[:], ip4)
  747. *((*C.int)(portP)) = C.int(port)
  748. return 1
  749. } else if len(ip) == 16 {
  750. *((*C.int)(familyP)) = C.int(AFInet6)
  751. copy((*[16]byte)(ipP)[:], ip)
  752. *((*C.int)(portP)) = C.int(port)
  753. return 1
  754. }
  755. }
  756. return 0
  757. }
  758. //export goStateObjectPutFunc
  759. func goStateObjectPutFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, len C.int) {
  760. go func() {
  761. nodesByUserPtrLock.RLock()
  762. node := nodesByUserPtr[uintptr(gn)]
  763. nodesByUserPtrLock.RUnlock()
  764. if node == nil {
  765. return
  766. }
  767. if len < 0 {
  768. node.stateObjectDelete(int(objType), *((*[2]uint64)(id)))
  769. } else {
  770. node.stateObjectPut(int(objType), *((*[2]uint64)(id)), C.GoBytes(data, len))
  771. }
  772. }()
  773. }
  774. //export goStateObjectGetFunc
  775. func goStateObjectGetFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, bufSize C.uint) C.int {
  776. nodesByUserPtrLock.RLock()
  777. node := nodesByUserPtr[uintptr(gn)]
  778. nodesByUserPtrLock.RUnlock()
  779. if node == nil {
  780. return -1
  781. }
  782. tmp, found := node.stateObjectGet(int(objType), *((*[2]uint64)(id)))
  783. if found && len(tmp) < int(bufSize) {
  784. if len(tmp) > 0 {
  785. C.memcpy(data, unsafe.Pointer(&(tmp[0])), C.ulong(len(tmp)))
  786. }
  787. return C.int(len(tmp))
  788. }
  789. return -1
  790. }
  791. //export goDNSResolverFunc
  792. func goDNSResolverFunc(gn unsafe.Pointer, dnsRecordTypes unsafe.Pointer, numDNSRecordTypes C.int, name unsafe.Pointer, requestID C.uintptr_t) {
  793. go func() {
  794. nodesByUserPtrLock.RLock()
  795. node := nodesByUserPtr[uintptr(gn)]
  796. nodesByUserPtrLock.RUnlock()
  797. if node == nil {
  798. return
  799. }
  800. recordTypes := C.GoBytes(dnsRecordTypes, numDNSRecordTypes)
  801. recordName := C.GoString((*C.char)(name))
  802. recordNameCStrCopy := C.CString(recordName)
  803. for _, rt := range recordTypes {
  804. switch rt {
  805. case C.ZT_DNS_RECORD_TXT:
  806. recs, _ := net.LookupTXT(recordName)
  807. for _, rec := range recs {
  808. if len(rec) > 0 {
  809. rnCS := C.CString(rec)
  810. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD_TXT, unsafe.Pointer(rnCS), C.uint(len(rec)), 0)
  811. C.free(unsafe.Pointer(rnCS))
  812. }
  813. }
  814. }
  815. }
  816. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD__END_OF_RESULTS, nil, 0, 0)
  817. C.free(unsafe.Pointer(recordNameCStrCopy))
  818. }()
  819. }
  820. //export goVirtualNetworkConfigFunc
  821. func goVirtualNetworkConfigFunc(gn, _ unsafe.Pointer, nwid C.uint64_t, op C.int, conf unsafe.Pointer) {
  822. go func() {
  823. nodesByUserPtrLock.RLock()
  824. node := nodesByUserPtr[uintptr(gn)]
  825. nodesByUserPtrLock.RUnlock()
  826. if node == nil {
  827. return
  828. }
  829. node.networksLock.RLock()
  830. network := node.networks[NetworkID(nwid)]
  831. node.networksLock.RUnlock()
  832. if network != nil {
  833. switch op {
  834. case C.ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP, C.ZT_VIRTUAL_NETWORK_CONFIG_OPERATION_UP:
  835. ncc := (*C.ZT_VirtualNetworkConfig)(conf)
  836. if network.networkConfigRevision() > uint64(ncc.netconfRevision) {
  837. return
  838. }
  839. var nc NetworkConfig
  840. nc.ID = NetworkID(ncc.nwid)
  841. nc.MAC = MAC(ncc.mac)
  842. nc.Name = C.GoString(&ncc.name[0])
  843. nc.Status = int(ncc.status)
  844. nc.Type = int(ncc._type)
  845. nc.MTU = int(ncc.mtu)
  846. nc.Bridge = ncc.bridge != 0
  847. nc.BroadcastEnabled = ncc.broadcastEnabled != 0
  848. nc.NetconfRevision = uint64(ncc.netconfRevision)
  849. for i := 0; i < int(ncc.assignedAddressCount); i++ {
  850. a := sockaddrStorageToIPNet(&ncc.assignedAddresses[i])
  851. if a != nil {
  852. nc.AssignedAddresses = append(nc.AssignedAddresses, *a)
  853. }
  854. }
  855. for i := 0; i < int(ncc.routeCount); i++ {
  856. tgt := sockaddrStorageToIPNet(&ncc.routes[i].target)
  857. viaN := sockaddrStorageToIPNet(&ncc.routes[i].via)
  858. var via net.IP
  859. if viaN != nil {
  860. via = viaN.IP
  861. }
  862. if tgt != nil {
  863. nc.Routes = append(nc.Routes, Route{
  864. Target: *tgt,
  865. Via: via,
  866. Flags: uint16(ncc.routes[i].flags),
  867. Metric: uint16(ncc.routes[i].metric),
  868. })
  869. }
  870. }
  871. network.updateConfig(&nc, nil)
  872. }
  873. }
  874. }()
  875. }
  876. //export goZtEvent
  877. func goZtEvent(gn unsafe.Pointer, eventType C.int, data unsafe.Pointer) {
  878. go func() {
  879. nodesByUserPtrLock.RLock()
  880. node := nodesByUserPtr[uintptr(gn)]
  881. nodesByUserPtrLock.RUnlock()
  882. if node == nil {
  883. return
  884. }
  885. switch eventType {
  886. case C.ZT_EVENT_OFFLINE:
  887. atomic.StoreUint32(&node.online, 0)
  888. case C.ZT_EVENT_ONLINE:
  889. atomic.StoreUint32(&node.online, 1)
  890. case C.ZT_EVENT_TRACE:
  891. node.handleTrace(C.GoString((*C.char)(data)))
  892. case C.ZT_EVENT_USER_MESSAGE:
  893. um := (*C.ZT_UserMessage)(data)
  894. node.handleUserMessage(uint64(um.origin), uint64(um.typeId), C.GoBytes(um.data, C.int(um.length)))
  895. case C.ZT_EVENT_REMOTE_TRACE:
  896. rt := (*C.ZT_RemoteTrace)(data)
  897. node.handleRemoteTrace(uint64(rt.origin), C.GoBytes(unsafe.Pointer(rt.data), C.int(rt.len)))
  898. }
  899. }()
  900. }