node.go 31 KB

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