node.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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. // Roots retrieves a list of root servers on this node and their preferred and online status.
  529. func (n *Node) Roots() []*Root {
  530. var roots []*Root
  531. rl := C.ZT_Node_listRoots(unsafe.Pointer(n.zn), C.int64_t(TimeMs()))
  532. if rl != nil {
  533. for i := 0; i < int(rl.count); i++ {
  534. root := (*C.ZT_Root)(unsafe.Pointer(uintptr(unsafe.Pointer(rl)) + C.sizeof_ZT_RootList))
  535. loc, _ := NewLocatorFromBytes(C.GoBytes(root.locator, C.int(root.locatorSize)))
  536. if loc != nil {
  537. roots = append(roots, &Root{
  538. Name: C.GoString(root.name),
  539. Locator: loc,
  540. })
  541. }
  542. }
  543. C.ZT_Node_freeQueryResult(unsafe.Pointer(n.zn), unsafe.Pointer(rl))
  544. }
  545. return roots
  546. }
  547. // SetRoot sets or updates a root.
  548. // Name can be a DNS name (preferably secure) for DNS fetched locators or can be
  549. // the empty string for static roots. If the name is empty then the locator must
  550. // be non-nil.
  551. func (n *Node) SetRoot(name string, locator *Locator) error {
  552. if len(name) == 0 {
  553. if locator == nil {
  554. return ErrInvalidParameter
  555. }
  556. name = locator.Identity.address.String()
  557. }
  558. var lb []byte
  559. if locator != nil {
  560. lb = locator.Bytes
  561. }
  562. var lbp unsafe.Pointer
  563. if len(lb) > 0 {
  564. lbp = unsafe.Pointer(&lb[0])
  565. }
  566. cn := C.CString(name)
  567. defer C.free(unsafe.Pointer(cn))
  568. if C.ZT_Node_setRoot(unsafe.Pointer(n.zn), cn, lbp, C.uint(len(lb))) != 0 {
  569. return ErrInternal
  570. }
  571. return nil
  572. }
  573. // RemoveRoot removes a root.
  574. // For static roots the name should be the ZeroTier address.
  575. func (n *Node) RemoveRoot(name string) {
  576. cn := C.CString(name)
  577. defer C.free(unsafe.Pointer(cn))
  578. C.ZT_Node_removeRoot(unsafe.Pointer(n.zn), cn)
  579. return
  580. }
  581. // Peers retrieves a list of current peers
  582. func (n *Node) Peers() []*Peer {
  583. var peers []*Peer
  584. pl := C.ZT_Node_peers(unsafe.Pointer(n.zn))
  585. if pl != nil {
  586. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  587. p := (*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer)))
  588. p2 := new(Peer)
  589. p2.Address = Address(p.address)
  590. p2.Version = [3]int{int(p.versionMajor), int(p.versionMinor), int(p.versionRev)}
  591. p2.Latency = int(p.latency)
  592. p2.Role = int(p.role)
  593. p2.Paths = make([]Path, 0, int(p.pathCount))
  594. usingAllocation := false
  595. for j := uintptr(0); j < uintptr(p.pathCount); j++ {
  596. pt := &p.paths[j]
  597. if pt.alive != 0 {
  598. a := sockaddrStorageToUDPAddr(&pt.address)
  599. if a != nil {
  600. alloc := float32(pt.allocation)
  601. if alloc > 0.0 {
  602. usingAllocation = true
  603. }
  604. p2.Paths = append(p2.Paths, Path{
  605. IP: a.IP,
  606. Port: a.Port,
  607. LastSend: int64(pt.lastSend),
  608. LastReceive: int64(pt.lastReceive),
  609. TrustedPathID: uint64(pt.trustedPathId),
  610. Latency: float32(pt.latency),
  611. PacketDelayVariance: float32(pt.packetDelayVariance),
  612. ThroughputDisturbCoeff: float32(pt.throughputDisturbCoeff),
  613. PacketErrorRatio: float32(pt.packetErrorRatio),
  614. PacketLossRatio: float32(pt.packetLossRatio),
  615. Stability: float32(pt.stability),
  616. Throughput: uint64(pt.throughput),
  617. MaxThroughput: uint64(pt.maxThroughput),
  618. Allocation: alloc,
  619. })
  620. }
  621. }
  622. }
  623. if !usingAllocation { // if all allocations are zero fall back to single path mode that uses the preferred flag
  624. for i, j := 0, uintptr(0); j < uintptr(p.pathCount); j++ {
  625. pt := &p.paths[j]
  626. if pt.alive != 0 {
  627. if pt.preferred == 0 {
  628. p2.Paths[i].Allocation = 0.0
  629. } else {
  630. p2.Paths[i].Allocation = 1.0
  631. }
  632. i++
  633. }
  634. }
  635. }
  636. sort.Slice(p2.Paths, func(a, b int) bool {
  637. pa := &p2.Paths[a]
  638. pb := &p2.Paths[b]
  639. if pb.Allocation < pa.Allocation { // invert order, put highest allocation paths first
  640. return true
  641. }
  642. if pa.Allocation == pb.Allocation {
  643. return pa.LastReceive < pb.LastReceive // then sort by most recent activity
  644. }
  645. return false
  646. })
  647. p2.Clock = TimeMs()
  648. peers = append(peers, p2)
  649. }
  650. C.ZT_Node_freeQueryResult(unsafe.Pointer(n.zn), unsafe.Pointer(pl))
  651. }
  652. sort.Slice(peers, func(a, b int) bool {
  653. return peers[a].Address < peers[b].Address
  654. })
  655. return peers
  656. }
  657. //////////////////////////////////////////////////////////////////////////////
  658. func (n *Node) multicastSubscribe(nwid uint64, mg *MulticastGroup) {
  659. C.ZT_Node_multicastSubscribe(unsafe.Pointer(n.zn), nil, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  660. }
  661. func (n *Node) multicastUnsubscribe(nwid uint64, mg *MulticastGroup) {
  662. C.ZT_Node_multicastUnsubscribe(unsafe.Pointer(n.zn), C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  663. }
  664. func (n *Node) pathCheck(ztAddress Address, af int, ip net.IP, port int) bool {
  665. n.localConfigLock.RLock()
  666. defer n.localConfigLock.RUnlock()
  667. for cidr, phy := range n.localConfig.Physical {
  668. if phy.Blacklist {
  669. _, ipn, _ := net.ParseCIDR(cidr)
  670. if ipn != nil && ipn.Contains(ip) {
  671. return false
  672. }
  673. }
  674. }
  675. return true
  676. }
  677. func (n *Node) pathLookup(ztAddress Address) (net.IP, int) {
  678. n.localConfigLock.RLock()
  679. defer n.localConfigLock.RUnlock()
  680. virt := n.localConfig.Virtual[ztAddress]
  681. if len(virt.Try) > 0 {
  682. idx := rand.Int() % len(virt.Try)
  683. return virt.Try[idx].IP, virt.Try[idx].Port
  684. }
  685. return nil, 0
  686. }
  687. func (n *Node) makeStateObjectPath(objType int, id [2]uint64) (string, bool) {
  688. var fp string
  689. secret := false
  690. switch objType {
  691. case C.ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  692. fp = path.Join(n.basePath, "identity.public")
  693. case C.ZT_STATE_OBJECT_IDENTITY_SECRET:
  694. fp = path.Join(n.basePath, "identity.secret")
  695. secret = true
  696. case C.ZT_STATE_OBJECT_PEER:
  697. fp = path.Join(n.basePath, "peers.d")
  698. _ = os.Mkdir(fp, 0700)
  699. fp = path.Join(fp, fmt.Sprintf("%.10x.peer", id[0]))
  700. secret = true
  701. case C.ZT_STATE_OBJECT_NETWORK_CONFIG:
  702. fp = path.Join(n.basePath, "networks.d")
  703. _ = os.Mkdir(fp, 0755)
  704. fp = path.Join(fp, fmt.Sprintf("%.16x.conf", id[0]))
  705. case C.ZT_STATE_OBJECT_ROOTS:
  706. fp = path.Join(n.basePath, "roots")
  707. }
  708. return fp, secret
  709. }
  710. func (n *Node) stateObjectPut(objType int, id [2]uint64, data []byte) {
  711. fp, secret := n.makeStateObjectPath(objType, id)
  712. if len(fp) > 0 {
  713. fileMode := os.FileMode(0644)
  714. if secret {
  715. fileMode = os.FileMode(0600)
  716. }
  717. _ = ioutil.WriteFile(fp, data, fileMode)
  718. if secret {
  719. _ = acl.Chmod(fp, 0600) // this emulates Unix chmod on Windows and uses os.Chmod on Unix-type systems
  720. }
  721. }
  722. }
  723. func (n *Node) stateObjectDelete(objType int, id [2]uint64) {
  724. fp, _ := n.makeStateObjectPath(objType, id)
  725. if len(fp) > 0 {
  726. _ = os.Remove(fp)
  727. }
  728. }
  729. func (n *Node) stateObjectGet(objType int, id [2]uint64) ([]byte, bool) {
  730. fp, _ := n.makeStateObjectPath(objType, id)
  731. if len(fp) > 0 {
  732. fd, err := ioutil.ReadFile(fp)
  733. if err != nil {
  734. return nil, false
  735. }
  736. return fd, true
  737. }
  738. return nil, false
  739. }
  740. func (n *Node) handleTrace(traceMessage string) {
  741. if len(traceMessage) > 0 {
  742. n.log.Print("TRACE: " + traceMessage)
  743. }
  744. }
  745. func (n *Node) handleUserMessage(originAddress, messageTypeID uint64, data []byte) {
  746. }
  747. func (n *Node) handleRemoteTrace(originAddress uint64, dictData []byte) {
  748. }
  749. //////////////////////////////////////////////////////////////////////////////
  750. // These are callbacks called by the core and GoGlue stuff to talk to the
  751. // service. These launch gorountines to do their work where possible to
  752. // avoid blocking anything in the core.
  753. //export goPathCheckFunc
  754. func goPathCheckFunc(gn unsafe.Pointer, ztAddress C.uint64_t, af C.int, ip unsafe.Pointer, port C.int) C.int {
  755. nodesByUserPtrLock.RLock()
  756. node := nodesByUserPtr[uintptr(gn)]
  757. nodesByUserPtrLock.RUnlock()
  758. var nip net.IP
  759. if af == AFInet {
  760. nip = ((*[4]byte)(ip))[:]
  761. } else if af == AFInet6 {
  762. nip = ((*[16]byte)(ip))[:]
  763. } else {
  764. return 0
  765. }
  766. if node != nil && len(nip) > 0 && node.pathCheck(Address(ztAddress), int(af), nip, int(port)) {
  767. return 1
  768. }
  769. return 0
  770. }
  771. //export goPathLookupFunc
  772. func goPathLookupFunc(gn unsafe.Pointer, ztAddress C.uint64_t, _ int, familyP, ipP, portP unsafe.Pointer) C.int {
  773. nodesByUserPtrLock.RLock()
  774. node := nodesByUserPtr[uintptr(gn)]
  775. nodesByUserPtrLock.RUnlock()
  776. if node == nil {
  777. return 0
  778. }
  779. ip, port := node.pathLookup(Address(ztAddress))
  780. if len(ip) > 0 && port > 0 && port <= 65535 {
  781. ip4 := ip.To4()
  782. if len(ip4) == 4 {
  783. *((*C.int)(familyP)) = C.int(AFInet)
  784. copy((*[4]byte)(ipP)[:], ip4)
  785. *((*C.int)(portP)) = C.int(port)
  786. return 1
  787. } else if len(ip) == 16 {
  788. *((*C.int)(familyP)) = C.int(AFInet6)
  789. copy((*[16]byte)(ipP)[:], ip)
  790. *((*C.int)(portP)) = C.int(port)
  791. return 1
  792. }
  793. }
  794. return 0
  795. }
  796. //export goStateObjectPutFunc
  797. func goStateObjectPutFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, len C.int) {
  798. go func() {
  799. nodesByUserPtrLock.RLock()
  800. node := nodesByUserPtr[uintptr(gn)]
  801. nodesByUserPtrLock.RUnlock()
  802. if node == nil {
  803. return
  804. }
  805. if len < 0 {
  806. node.stateObjectDelete(int(objType), *((*[2]uint64)(id)))
  807. } else {
  808. node.stateObjectPut(int(objType), *((*[2]uint64)(id)), C.GoBytes(data, len))
  809. }
  810. }()
  811. }
  812. //export goStateObjectGetFunc
  813. func goStateObjectGetFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, bufSize C.uint) C.int {
  814. nodesByUserPtrLock.RLock()
  815. node := nodesByUserPtr[uintptr(gn)]
  816. nodesByUserPtrLock.RUnlock()
  817. if node == nil {
  818. return -1
  819. }
  820. tmp, found := node.stateObjectGet(int(objType), *((*[2]uint64)(id)))
  821. if found && len(tmp) < int(bufSize) {
  822. if len(tmp) > 0 {
  823. C.memcpy(data, unsafe.Pointer(&(tmp[0])), C.ulong(len(tmp)))
  824. }
  825. return C.int(len(tmp))
  826. }
  827. return -1
  828. }
  829. //export goDNSResolverFunc
  830. func goDNSResolverFunc(gn unsafe.Pointer, dnsRecordTypes unsafe.Pointer, numDNSRecordTypes C.int, name unsafe.Pointer, requestID C.uintptr_t) {
  831. go func() {
  832. nodesByUserPtrLock.RLock()
  833. node := nodesByUserPtr[uintptr(gn)]
  834. nodesByUserPtrLock.RUnlock()
  835. if node == nil {
  836. return
  837. }
  838. recordTypes := C.GoBytes(dnsRecordTypes, numDNSRecordTypes)
  839. recordName := C.GoString((*C.char)(name))
  840. recordNameCStrCopy := C.CString(recordName)
  841. for _, rt := range recordTypes {
  842. switch rt {
  843. case C.ZT_DNS_RECORD_TXT:
  844. recs, _ := net.LookupTXT(recordName)
  845. for _, rec := range recs {
  846. if len(rec) > 0 {
  847. rnCS := C.CString(rec)
  848. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD_TXT, unsafe.Pointer(rnCS), C.uint(len(rec)), 0)
  849. C.free(unsafe.Pointer(rnCS))
  850. }
  851. }
  852. }
  853. }
  854. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD__END_OF_RESULTS, nil, 0, 0)
  855. C.free(unsafe.Pointer(recordNameCStrCopy))
  856. }()
  857. }
  858. //export goVirtualNetworkConfigFunc
  859. func goVirtualNetworkConfigFunc(gn, _ unsafe.Pointer, nwid C.uint64_t, op C.int, conf unsafe.Pointer) {
  860. go func() {
  861. nodesByUserPtrLock.RLock()
  862. node := nodesByUserPtr[uintptr(gn)]
  863. nodesByUserPtrLock.RUnlock()
  864. if node == nil {
  865. return
  866. }
  867. node.networksLock.RLock()
  868. network := node.networks[NetworkID(nwid)]
  869. node.networksLock.RUnlock()
  870. if network != nil {
  871. switch int(op) {
  872. case networkConfigOpUp, networkConfigOpUpdate:
  873. ncc := (*C.ZT_VirtualNetworkConfig)(conf)
  874. if network.networkConfigRevision() > uint64(ncc.netconfRevision) {
  875. return
  876. }
  877. var nc NetworkConfig
  878. nc.ID = NetworkID(ncc.nwid)
  879. nc.MAC = MAC(ncc.mac)
  880. nc.Name = C.GoString(&ncc.name[0])
  881. nc.Status = int(ncc.status)
  882. nc.Type = int(ncc._type)
  883. nc.MTU = int(ncc.mtu)
  884. nc.Bridge = ncc.bridge != 0
  885. nc.BroadcastEnabled = ncc.broadcastEnabled != 0
  886. nc.NetconfRevision = uint64(ncc.netconfRevision)
  887. for i := 0; i < int(ncc.assignedAddressCount); i++ {
  888. a := sockaddrStorageToIPNet(&ncc.assignedAddresses[i])
  889. if a != nil {
  890. nc.AssignedAddresses = append(nc.AssignedAddresses, *a)
  891. }
  892. }
  893. for i := 0; i < int(ncc.routeCount); i++ {
  894. tgt := sockaddrStorageToIPNet(&ncc.routes[i].target)
  895. viaN := sockaddrStorageToIPNet(&ncc.routes[i].via)
  896. var via *net.IP
  897. if viaN != nil && len(viaN.IP) > 0 {
  898. via = &viaN.IP
  899. }
  900. if tgt != nil {
  901. nc.Routes = append(nc.Routes, Route{
  902. Target: *tgt,
  903. Via: via,
  904. Flags: uint16(ncc.routes[i].flags),
  905. Metric: uint16(ncc.routes[i].metric),
  906. })
  907. }
  908. }
  909. network.updateConfig(&nc, nil)
  910. }
  911. }
  912. }()
  913. }
  914. //export goZtEvent
  915. func goZtEvent(gn unsafe.Pointer, eventType C.int, data unsafe.Pointer) {
  916. go func() {
  917. nodesByUserPtrLock.RLock()
  918. node := nodesByUserPtr[uintptr(gn)]
  919. nodesByUserPtrLock.RUnlock()
  920. if node == nil {
  921. return
  922. }
  923. switch eventType {
  924. case C.ZT_EVENT_OFFLINE:
  925. atomic.StoreUint32(&node.online, 0)
  926. case C.ZT_EVENT_ONLINE:
  927. atomic.StoreUint32(&node.online, 1)
  928. case C.ZT_EVENT_TRACE:
  929. node.handleTrace(C.GoString((*C.char)(data)))
  930. case C.ZT_EVENT_USER_MESSAGE:
  931. um := (*C.ZT_UserMessage)(data)
  932. node.handleUserMessage(uint64(um.origin), uint64(um.typeId), C.GoBytes(um.data, C.int(um.length)))
  933. case C.ZT_EVENT_REMOTE_TRACE:
  934. rt := (*C.ZT_RemoteTrace)(data)
  935. node.handleRemoteTrace(uint64(rt.origin), C.GoBytes(unsafe.Pointer(rt.data), C.int(rt.len)))
  936. }
  937. }()
  938. }