node.go 29 KB

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