node.go 27 KB

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