node.go 35 KB

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