node.go 30 KB

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