node.go 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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 darwin LDFLAGS: ${SRCDIR}/../../../build/go/native/libzt_go_native.a ${SRCDIR}/../../../build/node/libzt_core.a ${SRCDIR}/../../../build/osdep/libzt_osdep.a -lc++ -lpthread
  18. //#cgo linux android LDFLAGS: ${SRCDIR}/../../../build/go/native/libzt_go_native.a ${SRCDIR}/../../../build/node/libzt_core.a ${SRCDIR}/../../../build/osdep/libzt_osdep.a -lstdc++ -lpthread -lm
  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. // AFInet is the address family for IPv4
  59. AFInet = C.AF_INET
  60. // AFInet6 is the address family for IPv6
  61. AFInet6 = C.AF_INET6
  62. defaultVirtualNetworkMTU = C.ZT_DEFAULT_MTU
  63. )
  64. var (
  65. // PlatformDefaultHomePath is the default location of ZeroTier's working path on this system
  66. PlatformDefaultHomePath string = C.GoString(C.ZT_PLATFORM_DEFAULT_HOMEPATH)
  67. nodesByUserPtr = make(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 NetworkID, settings *NetworkLocalSettings, tap Tap) (*Network, error) {
  409. n.networksLock.RLock()
  410. if nw, have := n.networks[nwid]; have {
  411. n.log.Printf("join network %.16x ignored: already a member", nwid)
  412. if settings != nil {
  413. nw.SetLocalSettings(settings)
  414. }
  415. return nw, nil
  416. }
  417. n.networksLock.RUnlock()
  418. if tap != nil {
  419. panic("non-native taps not yet implemented")
  420. }
  421. ntap := C.ZT_GoNode_join(n.gn, C.uint64_t(nwid))
  422. if ntap == nil {
  423. n.log.Printf("join network %.16x failed: tap device failed to initialize (check drivers / kernel modules)")
  424. return nil, ErrTapInitFailed
  425. }
  426. nw, err := newNetwork(n, NetworkID(nwid), &nativeTap{tap: unsafe.Pointer(ntap), enabled: 1})
  427. if err != nil {
  428. n.log.Printf("join network %.16x failed: network failed to initialize: %s", nwid, err.Error())
  429. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  430. return nil, err
  431. }
  432. n.networksLock.Lock()
  433. n.networks[nwid] = nw
  434. n.networksLock.Unlock()
  435. if settings != nil {
  436. nw.SetLocalSettings(settings)
  437. }
  438. return nw, nil
  439. }
  440. // Leave leaves a network
  441. func (n *Node) Leave(nwid uint64) error {
  442. n.log.Printf("leaving network %.16x", nwid)
  443. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  444. n.networksLock.Lock()
  445. delete(n.networks, NetworkID(nwid))
  446. n.networksLock.Unlock()
  447. return nil
  448. }
  449. // GetNetwork looks up a network by ID or returns nil if not joined
  450. func (n *Node) GetNetwork(nwid NetworkID) *Network {
  451. n.networksLock.RLock()
  452. nw := n.networks[nwid]
  453. n.networksLock.RUnlock()
  454. return nw
  455. }
  456. // Networks returns a list of networks that this node has joined
  457. func (n *Node) Networks() []*Network {
  458. var nws []*Network
  459. n.networksLock.RLock()
  460. for _, nw := range n.networks {
  461. nws = append(nws, nw)
  462. }
  463. n.networksLock.RUnlock()
  464. return nws
  465. }
  466. // AddStaticRoot adds a statically defined root server to this node.
  467. // If a static root with the given identity already exists this will update its IP and port information.
  468. func (n *Node) AddStaticRoot(id *Identity, addrs []InetAddress) {
  469. var saddrs []C.struct_sockaddr_storage
  470. var straddrs strings.Builder
  471. for _, a := range addrs {
  472. ss := new(C.struct_sockaddr_storage)
  473. if makeSockaddrStorage(a.IP, a.Port, ss) {
  474. saddrs = append(saddrs, *ss)
  475. if straddrs.Len() > 0 {
  476. straddrs.WriteString(",")
  477. }
  478. straddrs.WriteString(a.String())
  479. }
  480. }
  481. if len(saddrs) > 0 {
  482. n.log.Printf("adding or updating static root %s at address(es) %s", id.String(), straddrs)
  483. ids := C.CString(id.String())
  484. C.ZT_Node_setStaticRoot(unsafe.Pointer(n.zn), ids, &saddrs[0], C.uint(len(saddrs)))
  485. C.free(unsafe.Pointer(ids))
  486. }
  487. }
  488. // RemoveStaticRoot removes a statically defined root server from this node.
  489. func (n *Node) RemoveStaticRoot(id *Identity) {
  490. n.log.Printf("removing static root %s", id.String())
  491. ids := C.CString(id.String())
  492. C.ZT_Node_removeStaticRoot(unsafe.Pointer(n.zn), ids)
  493. C.free(unsafe.Pointer(ids))
  494. }
  495. // AddDynamicRoot adds a dynamic root to this node.
  496. // If the locator parameter is non-empty it can contain a binary serialized locator
  497. // to use if (or until) one can be fetched via DNS.
  498. func (n *Node) AddDynamicRoot(dnsName string, locator []byte) {
  499. dn := C.CString(dnsName)
  500. n.log.Printf("adding dynamic root %s", dnsName)
  501. if len(locator) > 0 {
  502. C.ZT_Node_setDynamicRoot(unsafe.Pointer(n.zn), dn, unsafe.Pointer(&locator[0]), C.uint(len(locator)))
  503. } else {
  504. C.ZT_Node_setDynamicRoot(unsafe.Pointer(n.zn), dn, nil, 0)
  505. }
  506. C.free(unsafe.Pointer(dn))
  507. }
  508. // RemoveDynamicRoot removes a dynamic root from this node.
  509. func (n *Node) RemoveDynamicRoot(dnsName string) {
  510. n.log.Printf("removing dynamic root %s", dnsName)
  511. dn := C.CString(dnsName)
  512. C.ZT_Node_removeDynamicRoot(unsafe.Pointer(n.zn), dn)
  513. C.free(unsafe.Pointer(dn))
  514. }
  515. // Roots retrieves a list of root servers on this node and their preferred and online status.
  516. func (n *Node) Roots() []*Root {
  517. var roots []*Root
  518. rl := C.ZT_Node_listRoots(unsafe.Pointer(n.zn), C.int64_t(TimeMs()))
  519. if rl != nil {
  520. for i := 0; i < int(rl.count); i++ {
  521. root := (*C.ZT_Root)(unsafe.Pointer(uintptr(unsafe.Pointer(rl)) + C.sizeof_ZT_RootList))
  522. id, err := NewIdentityFromString(C.GoString(root.identity))
  523. if err == nil {
  524. var addrs []InetAddress
  525. for j := uintptr(0); j < uintptr(root.addressCount); j++ {
  526. a := NewInetAddressFromSockaddr(unsafe.Pointer(uintptr(unsafe.Pointer(root.addresses)) + (j * C.sizeof_struct_sockaddr_storage)))
  527. if a != nil && a.Valid() {
  528. addrs = append(addrs, *a)
  529. }
  530. }
  531. roots = append(roots, &Root{
  532. DNSName: C.GoString(root.dnsName),
  533. Identity: id,
  534. Addresses: addrs,
  535. Preferred: (root.preferred != 0),
  536. Online: (root.online != 0),
  537. })
  538. }
  539. }
  540. C.ZT_Node_freeQueryResult(unsafe.Pointer(n.zn), unsafe.Pointer(rl))
  541. }
  542. return roots
  543. }
  544. // Peers retrieves a list of current peers
  545. func (n *Node) Peers() []*Peer {
  546. var peers []*Peer
  547. pl := C.ZT_Node_peers(unsafe.Pointer(n.zn))
  548. if pl != nil {
  549. for i := uintptr(0); i < uintptr(pl.peerCount); i++ {
  550. p := (*C.ZT_Peer)(unsafe.Pointer(uintptr(unsafe.Pointer(pl.peers)) + (i * C.sizeof_ZT_Peer)))
  551. p2 := new(Peer)
  552. p2.Address = Address(p.address)
  553. p2.Version = [3]int{int(p.versionMajor), int(p.versionMinor), int(p.versionRev)}
  554. p2.Latency = int(p.latency)
  555. p2.Role = int(p.role)
  556. p2.Paths = make([]Path, 0, int(p.pathCount))
  557. usingAllocation := false
  558. for j := uintptr(0); j < uintptr(p.pathCount); j++ {
  559. pt := &p.paths[j]
  560. if pt.alive != 0 {
  561. a := sockaddrStorageToUDPAddr(&pt.address)
  562. if a != nil {
  563. alloc := float32(pt.allocation)
  564. if alloc > 0.0 {
  565. usingAllocation = true
  566. }
  567. p2.Paths = append(p2.Paths, Path{
  568. IP: a.IP,
  569. Port: a.Port,
  570. LastSend: int64(pt.lastSend),
  571. LastReceive: int64(pt.lastReceive),
  572. TrustedPathID: uint64(pt.trustedPathId),
  573. Latency: float32(pt.latency),
  574. PacketDelayVariance: float32(pt.packetDelayVariance),
  575. ThroughputDisturbCoeff: float32(pt.throughputDisturbCoeff),
  576. PacketErrorRatio: float32(pt.packetErrorRatio),
  577. PacketLossRatio: float32(pt.packetLossRatio),
  578. Stability: float32(pt.stability),
  579. Throughput: uint64(pt.throughput),
  580. MaxThroughput: uint64(pt.maxThroughput),
  581. Allocation: alloc,
  582. })
  583. }
  584. }
  585. }
  586. if !usingAllocation { // if all allocations are zero fall back to single path mode that uses the preferred flag
  587. for i, j := 0, uintptr(0); j < uintptr(p.pathCount); j++ {
  588. pt := &p.paths[j]
  589. if pt.alive != 0 {
  590. if pt.preferred == 0 {
  591. p2.Paths[i].Allocation = 0.0
  592. } else {
  593. p2.Paths[i].Allocation = 1.0
  594. }
  595. i++
  596. }
  597. }
  598. }
  599. sort.Slice(p2.Paths, func(a, b int) bool {
  600. pa := &p2.Paths[a]
  601. pb := &p2.Paths[b]
  602. if pb.Allocation < pa.Allocation { // invert order, put highest allocation paths first
  603. return true
  604. }
  605. if pa.Allocation == pb.Allocation {
  606. return pa.LastReceive < pb.LastReceive // then sort by most recent activity
  607. }
  608. return false
  609. })
  610. p2.Clock = TimeMs()
  611. peers = append(peers, p2)
  612. }
  613. C.ZT_Node_freeQueryResult(unsafe.Pointer(n.zn), unsafe.Pointer(pl))
  614. }
  615. sort.Slice(peers, func(a, b int) bool {
  616. return peers[a].Address < peers[b].Address
  617. })
  618. return peers
  619. }
  620. //////////////////////////////////////////////////////////////////////////////
  621. func (n *Node) multicastSubscribe(nwid uint64, mg *MulticastGroup) {
  622. C.ZT_Node_multicastSubscribe(unsafe.Pointer(n.zn), nil, C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  623. }
  624. func (n *Node) multicastUnsubscribe(nwid uint64, mg *MulticastGroup) {
  625. C.ZT_Node_multicastUnsubscribe(unsafe.Pointer(n.zn), C.uint64_t(nwid), C.uint64_t(mg.MAC), C.ulong(mg.ADI))
  626. }
  627. func (n *Node) pathCheck(ztAddress Address, af int, ip net.IP, port int) bool {
  628. n.localConfigLock.RLock()
  629. defer n.localConfigLock.RUnlock()
  630. for cidr, phy := range n.localConfig.Physical {
  631. if phy.Blacklist {
  632. _, ipn, _ := net.ParseCIDR(cidr)
  633. if ipn != nil && ipn.Contains(ip) {
  634. return false
  635. }
  636. }
  637. }
  638. return true
  639. }
  640. func (n *Node) pathLookup(ztAddress Address) (net.IP, int) {
  641. n.localConfigLock.RLock()
  642. defer n.localConfigLock.RUnlock()
  643. virt := n.localConfig.Virtual[ztAddress]
  644. if virt != nil && len(virt.Try) > 0 {
  645. idx := rand.Int() % len(virt.Try)
  646. return virt.Try[idx].IP, virt.Try[idx].Port
  647. }
  648. return nil, 0
  649. }
  650. func (n *Node) makeStateObjectPath(objType int, id [2]uint64) (string, bool) {
  651. var fp string
  652. secret := false
  653. switch objType {
  654. case C.ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  655. fp = path.Join(n.basePath, "identity.public")
  656. case C.ZT_STATE_OBJECT_IDENTITY_SECRET:
  657. fp = path.Join(n.basePath, "identity.secret")
  658. secret = true
  659. case C.ZT_STATE_OBJECT_PEER:
  660. fp = path.Join(n.basePath, "peers.d")
  661. os.Mkdir(fp, 0700)
  662. fp = path.Join(fp, fmt.Sprintf("%.10x.peer", id[0]))
  663. secret = true
  664. case C.ZT_STATE_OBJECT_NETWORK_CONFIG:
  665. fp = path.Join(n.basePath, "networks.d")
  666. os.Mkdir(fp, 0755)
  667. fp = path.Join(fp, fmt.Sprintf("%.16x.conf", id[0]))
  668. case C.ZT_STATE_OBJECT_ROOT_LIST:
  669. fp = path.Join(n.basePath, "roots")
  670. }
  671. return fp, secret
  672. }
  673. func (n *Node) stateObjectPut(objType int, id [2]uint64, data []byte) {
  674. fp, secret := n.makeStateObjectPath(objType, id)
  675. if len(fp) > 0 {
  676. fileMode := os.FileMode(0644)
  677. if secret {
  678. fileMode = os.FileMode(0600)
  679. }
  680. ioutil.WriteFile(fp, data, fileMode)
  681. if secret {
  682. acl.Chmod(fp, 0600) // this emulates Unix chmod on Windows and uses os.Chmod on Unix-type systems
  683. }
  684. }
  685. }
  686. func (n *Node) stateObjectDelete(objType int, id [2]uint64) {
  687. fp, _ := n.makeStateObjectPath(objType, id)
  688. if len(fp) > 0 {
  689. os.Remove(fp)
  690. }
  691. }
  692. func (n *Node) stateObjectGet(objType int, id [2]uint64) ([]byte, bool) {
  693. fp, _ := n.makeStateObjectPath(objType, id)
  694. if len(fp) > 0 {
  695. fd, err := ioutil.ReadFile(fp)
  696. if err != nil {
  697. return nil, false
  698. }
  699. return fd, true
  700. }
  701. return nil, false
  702. }
  703. func (n *Node) handleTrace(traceMessage string) {
  704. if len(traceMessage) > 0 {
  705. n.log.Print("TRACE: " + traceMessage)
  706. }
  707. }
  708. func (n *Node) handleUserMessage(originAddress, messageTypeID uint64, data []byte) {
  709. }
  710. func (n *Node) handleRemoteTrace(originAddress uint64, dictData []byte) {
  711. }
  712. //////////////////////////////////////////////////////////////////////////////
  713. //export goPathCheckFunc
  714. func goPathCheckFunc(gn unsafe.Pointer, ztAddress C.uint64_t, af C.int, ip unsafe.Pointer, port C.int) C.int {
  715. nodesByUserPtrLock.RLock()
  716. node := nodesByUserPtr[uintptr(gn)]
  717. nodesByUserPtrLock.RUnlock()
  718. if node != nil && node.pathCheck(Address(ztAddress), int(af), nil, int(port)) {
  719. return 1
  720. }
  721. return 0
  722. }
  723. //export goPathLookupFunc
  724. func goPathLookupFunc(gn unsafe.Pointer, ztAddress C.uint64_t, desiredAddressFamily int, familyP, ipP, portP unsafe.Pointer) C.int {
  725. nodesByUserPtrLock.RLock()
  726. node := nodesByUserPtr[uintptr(gn)]
  727. nodesByUserPtrLock.RUnlock()
  728. if node == nil {
  729. return 0
  730. }
  731. ip, port := node.pathLookup(Address(ztAddress))
  732. if len(ip) > 0 && port > 0 && port <= 65535 {
  733. ip4 := ip.To4()
  734. if len(ip4) == 4 {
  735. *((*C.int)(familyP)) = C.int(AFInet)
  736. copy((*[4]byte)(ipP)[:], ip4)
  737. *((*C.int)(portP)) = C.int(port)
  738. return 1
  739. } else if len(ip) == 16 {
  740. *((*C.int)(familyP)) = C.int(AFInet6)
  741. copy((*[16]byte)(ipP)[:], ip)
  742. *((*C.int)(portP)) = C.int(port)
  743. return 1
  744. }
  745. }
  746. return 0
  747. }
  748. //export goStateObjectPutFunc
  749. func goStateObjectPutFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, len C.int) {
  750. go func() {
  751. nodesByUserPtrLock.RLock()
  752. node := nodesByUserPtr[uintptr(gn)]
  753. nodesByUserPtrLock.RUnlock()
  754. if node == nil {
  755. return
  756. }
  757. if len < 0 {
  758. node.stateObjectDelete(int(objType), *((*[2]uint64)(id)))
  759. } else {
  760. node.stateObjectPut(int(objType), *((*[2]uint64)(id)), C.GoBytes(data, len))
  761. }
  762. }()
  763. }
  764. //export goStateObjectGetFunc
  765. func goStateObjectGetFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, bufSize C.uint) C.int {
  766. nodesByUserPtrLock.RLock()
  767. node := nodesByUserPtr[uintptr(gn)]
  768. nodesByUserPtrLock.RUnlock()
  769. if node == nil {
  770. return -1
  771. }
  772. tmp, found := node.stateObjectGet(int(objType), *((*[2]uint64)(id)))
  773. if found && len(tmp) < int(bufSize) {
  774. if len(tmp) > 0 {
  775. C.memcpy(data, unsafe.Pointer(&(tmp[0])), C.ulong(len(tmp)))
  776. }
  777. return C.int(len(tmp))
  778. }
  779. return -1
  780. }
  781. //export goDNSResolverFunc
  782. func goDNSResolverFunc(gn unsafe.Pointer, dnsRecordTypes unsafe.Pointer, numDNSRecordTypes C.int, name unsafe.Pointer, requestID C.uintptr_t) {
  783. go func() {
  784. nodesByUserPtrLock.RLock()
  785. node := nodesByUserPtr[uintptr(gn)]
  786. nodesByUserPtrLock.RUnlock()
  787. if node == nil {
  788. return
  789. }
  790. recordTypes := C.GoBytes(dnsRecordTypes, numDNSRecordTypes)
  791. recordName := C.GoString((*C.char)(name))
  792. recordNameCStrCopy := C.CString(recordName)
  793. for _, rt := range recordTypes {
  794. switch rt {
  795. case C.ZT_DNS_RECORD_TXT:
  796. recs, _ := net.LookupTXT(recordName)
  797. for _, rec := range recs {
  798. if len(rec) > 0 {
  799. rnCS := C.CString(rec)
  800. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD_TXT, unsafe.Pointer(rnCS), C.uint(len(rec)), 0)
  801. C.free(unsafe.Pointer(rnCS))
  802. }
  803. }
  804. }
  805. }
  806. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD__END_OF_RESULTS, nil, 0, 0)
  807. C.free(unsafe.Pointer(recordNameCStrCopy))
  808. }()
  809. }
  810. //export goVirtualNetworkConfigFunc
  811. func goVirtualNetworkConfigFunc(gn, tapP unsafe.Pointer, nwid C.uint64_t, op C.int, conf unsafe.Pointer) {
  812. go func() {
  813. nodesByUserPtrLock.RLock()
  814. node := nodesByUserPtr[uintptr(gn)]
  815. nodesByUserPtrLock.RUnlock()
  816. if node == nil {
  817. return
  818. }
  819. node.networksLock.RLock()
  820. network := node.networks[NetworkID(nwid)]
  821. node.networksLock.RUnlock()
  822. if network != nil {
  823. ncc := (*C.ZT_VirtualNetworkConfig)(conf)
  824. if network.networkConfigRevision() > uint64(ncc.netconfRevision) {
  825. return
  826. }
  827. var nc NetworkConfig
  828. nc.ID = NetworkID(ncc.nwid)
  829. nc.MAC = MAC(ncc.mac)
  830. nc.Name = C.GoString(&ncc.name[0])
  831. nc.Status = int(ncc.status)
  832. nc.Type = int(ncc._type)
  833. nc.MTU = int(ncc.mtu)
  834. nc.Bridge = (ncc.bridge != 0)
  835. nc.BroadcastEnabled = (ncc.broadcastEnabled != 0)
  836. nc.NetconfRevision = uint64(ncc.netconfRevision)
  837. for i := 0; i < int(ncc.assignedAddressCount); i++ {
  838. a := sockaddrStorageToIPNet(&ncc.assignedAddresses[i])
  839. if a != nil {
  840. nc.AssignedAddresses = append(nc.AssignedAddresses, *a)
  841. }
  842. }
  843. for i := 0; i < int(ncc.routeCount); i++ {
  844. tgt := sockaddrStorageToIPNet(&ncc.routes[i].target)
  845. viaN := sockaddrStorageToIPNet(&ncc.routes[i].via)
  846. var via net.IP
  847. if viaN != nil {
  848. via = viaN.IP
  849. }
  850. if tgt != nil {
  851. nc.Routes = append(nc.Routes, Route{
  852. Target: *tgt,
  853. Via: via,
  854. Flags: uint16(ncc.routes[i].flags),
  855. Metric: uint16(ncc.routes[i].metric),
  856. })
  857. }
  858. }
  859. network.updateConfig(&nc, nil)
  860. }
  861. }()
  862. }
  863. //export goZtEvent
  864. func goZtEvent(gn unsafe.Pointer, eventType C.int, data unsafe.Pointer) {
  865. go func() {
  866. nodesByUserPtrLock.RLock()
  867. node := nodesByUserPtr[uintptr(gn)]
  868. nodesByUserPtrLock.RUnlock()
  869. if node == nil {
  870. return
  871. }
  872. switch eventType {
  873. case C.ZT_EVENT_OFFLINE:
  874. atomic.StoreUint32(&node.online, 0)
  875. case C.ZT_EVENT_ONLINE:
  876. atomic.StoreUint32(&node.online, 1)
  877. case C.ZT_EVENT_TRACE:
  878. node.handleTrace(C.GoString((*C.char)(data)))
  879. case C.ZT_EVENT_USER_MESSAGE:
  880. um := (*C.ZT_UserMessage)(data)
  881. node.handleUserMessage(uint64(um.origin), uint64(um.typeId), C.GoBytes(um.data, C.int(um.length)))
  882. case C.ZT_EVENT_REMOTE_TRACE:
  883. rt := (*C.ZT_RemoteTrace)(data)
  884. node.handleRemoteTrace(uint64(rt.origin), C.GoBytes(unsafe.Pointer(rt.data), C.int(rt.len)))
  885. }
  886. }()
  887. }
  888. //////////////////////////////////////////////////////////////////////////////
  889. // nativeTap is a Tap implementation that wraps a native C++ interface to a system tun/tap device
  890. type nativeTap struct {
  891. tap unsafe.Pointer
  892. networkStatus uint32
  893. enabled uint32
  894. multicastGroupHandlers []func(bool, *MulticastGroup)
  895. multicastGroupHandlersLock sync.Mutex
  896. }
  897. // Type returns a human-readable description of this tap implementation
  898. func (t *nativeTap) Type() string {
  899. return "native"
  900. }
  901. // Error gets this tap device's error status
  902. func (t *nativeTap) Error() (int, string) {
  903. return 0, ""
  904. }
  905. // SetEnabled sets this tap's enabled state
  906. func (t *nativeTap) SetEnabled(enabled bool) {
  907. if enabled && atomic.SwapUint32(&t.enabled, 1) == 0 {
  908. C.ZT_GoTap_setEnabled(t.tap, 1)
  909. } else if !enabled && atomic.SwapUint32(&t.enabled, 0) == 1 {
  910. C.ZT_GoTap_setEnabled(t.tap, 0)
  911. }
  912. }
  913. // Enabled returns true if this tap is currently processing packets
  914. func (t *nativeTap) Enabled() bool {
  915. return atomic.LoadUint32(&t.enabled) != 0
  916. }
  917. // AddIP adds an IP address (with netmask) to this tap
  918. func (t *nativeTap) AddIP(ip *net.IPNet) error {
  919. bits, _ := ip.Mask.Size()
  920. if len(ip.IP) == 16 {
  921. if bits > 128 || bits < 0 {
  922. return ErrInvalidParameter
  923. }
  924. C.ZT_GoTap_addIp(t.tap, C.int(AFInet6), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  925. } else if len(ip.IP) == 4 {
  926. if bits > 32 || bits < 0 {
  927. return ErrInvalidParameter
  928. }
  929. C.ZT_GoTap_addIp(t.tap, C.int(AFInet), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  930. }
  931. return ErrInvalidParameter
  932. }
  933. // RemoveIP removes this IP address (with netmask) from this tap
  934. func (t *nativeTap) RemoveIP(ip *net.IPNet) error {
  935. bits, _ := ip.Mask.Size()
  936. if len(ip.IP) == 16 {
  937. if bits > 128 || bits < 0 {
  938. return ErrInvalidParameter
  939. }
  940. C.ZT_GoTap_removeIp(t.tap, C.int(AFInet6), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  941. return nil
  942. }
  943. if len(ip.IP) == 4 {
  944. if bits > 32 || bits < 0 {
  945. return ErrInvalidParameter
  946. }
  947. C.ZT_GoTap_removeIp(t.tap, C.int(AFInet), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  948. return nil
  949. }
  950. return ErrInvalidParameter
  951. }
  952. // IPs returns IPs currently assigned to this tap (including externally or system-assigned IPs)
  953. func (t *nativeTap) IPs() (ips []net.IPNet, err error) {
  954. defer func() {
  955. e := recover()
  956. if e != nil {
  957. err = fmt.Errorf("%v", e)
  958. }
  959. }()
  960. var ipbuf [16384]byte
  961. count := int(C.ZT_GoTap_ips(t.tap, unsafe.Pointer(&ipbuf[0]), 16384))
  962. ipptr := 0
  963. for i := 0; i < count; i++ {
  964. af := int(ipbuf[ipptr])
  965. ipptr++
  966. switch af {
  967. case AFInet:
  968. var ip [4]byte
  969. for j := 0; j < 4; j++ {
  970. ip[j] = ipbuf[ipptr]
  971. ipptr++
  972. }
  973. bits := ipbuf[ipptr]
  974. ipptr++
  975. ips = append(ips, net.IPNet{IP: net.IP(ip[:]), Mask: net.CIDRMask(int(bits), 32)})
  976. case AFInet6:
  977. var ip [16]byte
  978. for j := 0; j < 16; j++ {
  979. ip[j] = ipbuf[ipptr]
  980. ipptr++
  981. }
  982. bits := ipbuf[ipptr]
  983. ipptr++
  984. ips = append(ips, net.IPNet{IP: net.IP(ip[:]), Mask: net.CIDRMask(int(bits), 128)})
  985. }
  986. }
  987. return
  988. }
  989. // DeviceName gets this tap's OS-specific device name
  990. func (t *nativeTap) DeviceName() string {
  991. var dn [256]byte
  992. C.ZT_GoTap_deviceName(t.tap, (*C.char)(unsafe.Pointer(&dn[0])))
  993. for i, b := range dn {
  994. if b == 0 {
  995. return string(dn[0:i])
  996. }
  997. }
  998. return ""
  999. }
  1000. // AddMulticastGroupChangeHandler adds a function to be called when the tap subscribes or unsubscribes to a multicast group.
  1001. func (t *nativeTap) AddMulticastGroupChangeHandler(handler func(bool, *MulticastGroup)) {
  1002. t.multicastGroupHandlersLock.Lock()
  1003. t.multicastGroupHandlers = append(t.multicastGroupHandlers, handler)
  1004. t.multicastGroupHandlersLock.Unlock()
  1005. }
  1006. // AddRoute adds or updates a managed route on this tap's interface
  1007. func (t *nativeTap) AddRoute(r *Route) error {
  1008. rc := 0
  1009. if r != nil {
  1010. if len(r.Target.IP) == 4 {
  1011. mask, _ := r.Target.Mask.Size()
  1012. if len(r.Via) == 4 {
  1013. 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)))
  1014. } else {
  1015. rc = int(C.ZT_GoTap_addRoute(t.tap, AFInet, unsafe.Pointer(&r.Target.IP[0]), C.int(mask), 0, nil, C.uint(r.Metric)))
  1016. }
  1017. } else if len(r.Target.IP) == 16 {
  1018. mask, _ := r.Target.Mask.Size()
  1019. if len(r.Via) == 4 {
  1020. 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)))
  1021. } else {
  1022. rc = int(C.ZT_GoTap_addRoute(t.tap, AFInet6, unsafe.Pointer(&r.Target.IP[0]), C.int(mask), 0, nil, C.uint(r.Metric)))
  1023. }
  1024. }
  1025. }
  1026. if rc != 0 {
  1027. return fmt.Errorf("tap device error adding route: %d", rc)
  1028. }
  1029. return nil
  1030. }
  1031. // RemoveRoute removes a managed route on this tap's interface
  1032. func (t *nativeTap) RemoveRoute(r *Route) error {
  1033. rc := 0
  1034. if r != nil {
  1035. if len(r.Target.IP) == 4 {
  1036. mask, _ := r.Target.Mask.Size()
  1037. if len(r.Via) == 4 {
  1038. 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)))
  1039. } else {
  1040. rc = int(C.ZT_GoTap_removeRoute(t.tap, AFInet, unsafe.Pointer(&r.Target.IP[0]), C.int(mask), 0, nil, C.uint(r.Metric)))
  1041. }
  1042. } else if len(r.Target.IP) == 16 {
  1043. mask, _ := r.Target.Mask.Size()
  1044. if len(r.Via) == 4 {
  1045. 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)))
  1046. } else {
  1047. rc = int(C.ZT_GoTap_removeRoute(t.tap, AFInet6, unsafe.Pointer(&r.Target.IP[0]), C.int(mask), 0, nil, C.uint(r.Metric)))
  1048. }
  1049. }
  1050. }
  1051. if rc != 0 {
  1052. return fmt.Errorf("tap device error removing route: %d", rc)
  1053. }
  1054. return nil
  1055. }
  1056. //////////////////////////////////////////////////////////////////////////////
  1057. func handleTapMulticastGroupChange(gn unsafe.Pointer, nwid, mac C.uint64_t, adi C.uint32_t, added bool) {
  1058. go func() {
  1059. nodesByUserPtrLock.RLock()
  1060. node := nodesByUserPtr[uintptr(gn)]
  1061. nodesByUserPtrLock.RUnlock()
  1062. if node == nil {
  1063. return
  1064. }
  1065. node.networksLock.RLock()
  1066. network := node.networks[NetworkID(nwid)]
  1067. node.networksLock.RUnlock()
  1068. if network != nil {
  1069. tap, _ := network.tap.(*nativeTap)
  1070. if tap != nil {
  1071. mg := &MulticastGroup{MAC: MAC(mac), ADI: uint32(adi)}
  1072. tap.multicastGroupHandlersLock.Lock()
  1073. defer tap.multicastGroupHandlersLock.Unlock()
  1074. for _, h := range tap.multicastGroupHandlers {
  1075. h(added, mg)
  1076. }
  1077. }
  1078. }
  1079. }()
  1080. }
  1081. //export goHandleTapAddedMulticastGroup
  1082. func goHandleTapAddedMulticastGroup(gn, tapP unsafe.Pointer, nwid, mac C.uint64_t, adi C.uint32_t) {
  1083. handleTapMulticastGroupChange(gn, nwid, mac, adi, true)
  1084. }
  1085. //export goHandleTapRemovedMulticastGroup
  1086. func goHandleTapRemovedMulticastGroup(gn, tapP unsafe.Pointer, nwid, mac C.uint64_t, adi C.uint32_t) {
  1087. handleTapMulticastGroupChange(gn, nwid, mac, adi, false)
  1088. }