node.go 30 KB

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