node.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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. "errors"
  21. "fmt"
  22. "io/ioutil"
  23. "net"
  24. "os"
  25. "path"
  26. "sync"
  27. "sync/atomic"
  28. "time"
  29. "unsafe"
  30. acl "github.com/hectane/go-acl"
  31. )
  32. // Network status states
  33. const (
  34. NetworkStatusRequestConfiguration int = C.ZT_NETWORK_STATUS_REQUESTING_CONFIGURATION
  35. NetworkStatusOK int = C.ZT_NETWORK_STATUS_OK
  36. NetworkStatusAccessDenied int = C.ZT_NETWORK_STATUS_ACCESS_DENIED
  37. NetworkStatusNotFound int = C.ZT_NETWORK_STATUS_NOT_FOUND
  38. NetworkStatusPortError int = C.ZT_NETWORK_STATUS_PORT_ERROR
  39. NetworkStatusClientTooOld int = C.ZT_NETWORK_STATUS_CLIENT_TOO_OLD
  40. // CoreVersionMajor is the major version of the ZeroTier core
  41. CoreVersionMajor int = C.ZEROTIER_ONE_VERSION_MAJOR
  42. // CoreVersionMinor is the minor version of the ZeroTier core
  43. CoreVersionMinor int = C.ZEROTIER_ONE_VERSION_MINOR
  44. // CoreVersionRevision is the revision of the ZeroTier core
  45. CoreVersionRevision int = C.ZEROTIER_ONE_VERSION_REVISION
  46. // CoreVersionBuild is the build version of the ZeroTier core
  47. CoreVersionBuild int = C.ZEROTIER_ONE_VERSION_BUILD
  48. afInet int = C.AF_INET
  49. afInet6 int = C.AF_INET6
  50. )
  51. var (
  52. nodesByUserPtr map[uintptr]*Node
  53. nodesByUserPtrLock sync.RWMutex
  54. )
  55. //////////////////////////////////////////////////////////////////////////////
  56. // Node represents an instance of the ZeroTier core node and related C++ I/O code
  57. type Node struct {
  58. path string
  59. networks map[uint64]*Network
  60. networksLock sync.RWMutex
  61. gn *C.ZT_GoNode
  62. zn *C.ZT_Node
  63. online uint32
  64. running uint32
  65. }
  66. // NewNode creates and initializes a new instance of the ZeroTier node service
  67. func NewNode(path string) (*Node, error) {
  68. os.MkdirAll(path, 0755)
  69. if _, err := os.Stat(path); err != nil {
  70. return nil, err
  71. }
  72. n := new(Node)
  73. n.path = path
  74. n.networks = make(map[uint64]*Network)
  75. cpath := C.CString(path)
  76. n.gn = C.ZT_GoNode_new(cpath)
  77. C.free(unsafe.Pointer(cpath))
  78. if n.gn == nil {
  79. return nil, ErrNodeInitFailed
  80. }
  81. n.zn = (*C.ZT_Node)(C.ZT_GoNode_getNode(n.gn))
  82. gnRawAddr := uintptr(unsafe.Pointer(n.gn))
  83. nodesByUserPtrLock.Lock()
  84. nodesByUserPtr[gnRawAddr] = n
  85. nodesByUserPtrLock.Unlock()
  86. n.online = 0
  87. n.running = 1
  88. return n, nil
  89. }
  90. // Close closes this Node and frees its underlying C++ Node structures
  91. func (n *Node) Close() {
  92. if atomic.SwapUint32(&n.running, 0) != 0 {
  93. C.ZT_GoNode_delete(n.gn)
  94. nodesByUserPtrLock.Lock()
  95. delete(nodesByUserPtr, uintptr(unsafe.Pointer(n.gn)))
  96. nodesByUserPtrLock.Unlock()
  97. }
  98. }
  99. // Join joins a network
  100. // If tap is nil, the default system tap for this OS/platform is used (if available).
  101. func (n *Node) Join(nwid uint64, tap Tap) (*Network, error) {
  102. n.networksLock.RLock()
  103. if nw, have := n.networks[nwid]; have {
  104. return nw, nil
  105. }
  106. n.networksLock.RUnlock()
  107. if tap != nil {
  108. return nil, errors.New("non-native taps not implemented yet")
  109. }
  110. ntap := C.ZT_GoNode_join(n.gn, C.uint64_t(nwid))
  111. if ntap == nil {
  112. return nil, ErrTapInitFailed
  113. }
  114. nw := &Network{
  115. id: NetworkID(nwid),
  116. config: NetworkConfig{
  117. ID: NetworkID(nwid),
  118. Status: NetworkStatusRequestConfiguration,
  119. LastUpdated: time.Now(),
  120. Enabled: true,
  121. },
  122. tap: &nativeTap{tap: unsafe.Pointer(ntap), enabled: 1},
  123. }
  124. n.networksLock.Lock()
  125. n.networks[nwid] = nw
  126. n.networksLock.Unlock()
  127. return nw, nil
  128. }
  129. // Leave leaves a network
  130. func (n *Node) Leave(nwid uint64) error {
  131. C.ZT_GoNode_leave(n.gn, C.uint64_t(nwid))
  132. n.networksLock.Lock()
  133. delete(n.networks, nwid)
  134. n.networksLock.Unlock()
  135. return nil
  136. }
  137. //////////////////////////////////////////////////////////////////////////////
  138. func (n *Node) pathCheck(ztAddress uint64, af int, ip net.IP, port int) bool {
  139. return true
  140. }
  141. func (n *Node) pathLookup(ztAddress uint64) (net.IP, int) {
  142. return nil, 0
  143. }
  144. func (n *Node) makeStateObjectPath(objType int, id [2]uint64) (string, bool) {
  145. var fp string
  146. secret := false
  147. switch objType {
  148. case C.ZT_STATE_OBJECT_IDENTITY_PUBLIC:
  149. fp = path.Join(n.path, "identity.public")
  150. case C.ZT_STATE_OBJECT_IDENTITY_SECRET:
  151. fp = path.Join(n.path, "identity.secret")
  152. secret = true
  153. case C.ZT_STATE_OBJECT_PEER:
  154. fp = path.Join(n.path, "peers.d")
  155. os.Mkdir(fp, 0700)
  156. fp = path.Join(fp, fmt.Sprintf("%.10x.peer", id[0]))
  157. secret = true
  158. case C.ZT_STATE_OBJECT_NETWORK_CONFIG:
  159. fp = path.Join(n.path, "networks.d")
  160. os.Mkdir(fp, 0755)
  161. fp = path.Join(fp, fmt.Sprintf("%.16x.conf", id[0]))
  162. case C.ZT_STATE_OBJECT_ROOT_LIST:
  163. fp = path.Join(n.path, "roots")
  164. }
  165. return fp, secret
  166. }
  167. func (n *Node) stateObjectPut(objType int, id [2]uint64, data []byte) {
  168. go func() {
  169. fp, secret := n.makeStateObjectPath(objType, id)
  170. if len(fp) > 0 {
  171. fileMode := os.FileMode(0644)
  172. if secret {
  173. fileMode = os.FileMode(0600)
  174. }
  175. ioutil.WriteFile(fp, data, fileMode)
  176. if secret {
  177. acl.Chmod(fp, 0600) // this emulates Unix chmod on Windows and uses os.Chmod on Unix-type systems
  178. }
  179. }
  180. }()
  181. }
  182. func (n *Node) stateObjectDelete(objType int, id [2]uint64) {
  183. go func() {
  184. fp, _ := n.makeStateObjectPath(objType, id)
  185. if len(fp) > 0 {
  186. os.Remove(fp)
  187. }
  188. }()
  189. }
  190. func (n *Node) stateObjectGet(objType int, id [2]uint64) ([]byte, bool) {
  191. fp, _ := n.makeStateObjectPath(objType, id)
  192. if len(fp) > 0 {
  193. fd, err := ioutil.ReadFile(fp)
  194. if err != nil {
  195. return nil, false
  196. }
  197. return fd, true
  198. }
  199. return nil, false
  200. }
  201. func (n *Node) handleTrace(traceMessage string) {
  202. }
  203. func (n *Node) handleUserMessage(originAddress, messageTypeID uint64, data []byte) {
  204. }
  205. func (n *Node) handleRemoteTrace(originAddress uint64, dictData []byte) {
  206. }
  207. //////////////////////////////////////////////////////////////////////////////
  208. //export goPathCheckFunc
  209. func goPathCheckFunc(gn unsafe.Pointer, ztAddress C.uint64_t, af C.int, ip unsafe.Pointer, port C.int) C.int {
  210. nodesByUserPtrLock.RLock()
  211. node := nodesByUserPtr[uintptr(gn)]
  212. nodesByUserPtrLock.RUnlock()
  213. if node != nil && node.pathCheck(uint64(ztAddress), int(af), nil, int(port)) {
  214. return 1
  215. }
  216. return 0
  217. }
  218. //export goPathLookupFunc
  219. func goPathLookupFunc(gn unsafe.Pointer, ztAddress C.uint64_t, desiredAddressFamily int, familyP, ipP, portP unsafe.Pointer) C.int {
  220. nodesByUserPtrLock.RLock()
  221. node := nodesByUserPtr[uintptr(gn)]
  222. nodesByUserPtrLock.RUnlock()
  223. if node == nil {
  224. return 0
  225. }
  226. ip, port := node.pathLookup(uint64(ztAddress))
  227. if len(ip) > 0 && port > 0 && port <= 65535 {
  228. ip4 := ip.To4()
  229. if len(ip4) == 4 {
  230. *((*C.int)(familyP)) = C.int(afInet)
  231. copy((*[4]byte)(ipP)[:], ip4)
  232. *((*C.int)(portP)) = C.int(port)
  233. return 1
  234. } else if len(ip) == 16 {
  235. *((*C.int)(familyP)) = C.int(afInet6)
  236. copy((*[16]byte)(ipP)[:], ip)
  237. *((*C.int)(portP)) = C.int(port)
  238. return 1
  239. }
  240. }
  241. return 0
  242. }
  243. //export goStateObjectPutFunc
  244. func goStateObjectPutFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, len C.int) {
  245. nodesByUserPtrLock.RLock()
  246. node := nodesByUserPtr[uintptr(gn)]
  247. nodesByUserPtrLock.RUnlock()
  248. if node == nil {
  249. return
  250. }
  251. if len < 0 {
  252. node.stateObjectDelete(int(objType), *((*[2]uint64)(id)))
  253. } else {
  254. node.stateObjectPut(int(objType), *((*[2]uint64)(id)), C.GoBytes(data, len))
  255. }
  256. }
  257. //export goStateObjectGetFunc
  258. func goStateObjectGetFunc(gn unsafe.Pointer, objType C.int, id, data unsafe.Pointer, bufSize C.uint) C.int {
  259. nodesByUserPtrLock.RLock()
  260. node := nodesByUserPtr[uintptr(gn)]
  261. nodesByUserPtrLock.RUnlock()
  262. if node == nil {
  263. return -1
  264. }
  265. tmp, found := node.stateObjectGet(int(objType), *((*[2]uint64)(id)))
  266. if found && len(tmp) < int(bufSize) {
  267. if len(tmp) > 0 {
  268. C.memcpy(data, unsafe.Pointer(&(tmp[0])), C.ulong(len(tmp)))
  269. }
  270. return C.int(len(tmp))
  271. }
  272. return -1
  273. }
  274. //export goDNSResolverFunc
  275. func goDNSResolverFunc(gn unsafe.Pointer, dnsRecordTypes unsafe.Pointer, numDNSRecordTypes C.int, name unsafe.Pointer, requestID C.uintptr_t) {
  276. nodesByUserPtrLock.RLock()
  277. node := nodesByUserPtr[uintptr(gn)]
  278. nodesByUserPtrLock.RUnlock()
  279. if node == nil {
  280. return
  281. }
  282. recordTypes := C.GoBytes(dnsRecordTypes, numDNSRecordTypes)
  283. recordName := C.GoString((*C.char)(name))
  284. go func() {
  285. recordNameCStrCopy := C.CString(recordName)
  286. for _, rt := range recordTypes {
  287. switch rt {
  288. case C.ZT_DNS_RECORD_TXT:
  289. recs, _ := net.LookupTXT(recordName)
  290. for _, rec := range recs {
  291. if len(rec) > 0 {
  292. rnCS := C.CString(rec)
  293. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD_TXT, unsafe.Pointer(rnCS), C.uint(len(rec)), 0)
  294. C.free(unsafe.Pointer(rnCS))
  295. }
  296. }
  297. }
  298. }
  299. C.ZT_Node_processDNSResult(unsafe.Pointer(node.zn), nil, requestID, recordNameCStrCopy, C.ZT_DNS_RECORD__END_OF_RESULTS, nil, 0, 0)
  300. C.free(unsafe.Pointer(recordNameCStrCopy))
  301. }()
  302. }
  303. //export goVirtualNetworkConfigFunc
  304. func goVirtualNetworkConfigFunc(gn, tapP unsafe.Pointer, nwid C.uint64_t, op C.int, conf unsafe.Pointer) C.int {
  305. nodesByUserPtrLock.RLock()
  306. node := nodesByUserPtr[uintptr(gn)]
  307. nodesByUserPtrLock.RUnlock()
  308. if node == nil {
  309. return 255
  310. }
  311. node.networksLock.RLock()
  312. network := node.networks[uint64(nwid)]
  313. node.networksLock.RUnlock()
  314. if network != nil {
  315. }
  316. //return C.int(node.handleNetworkConfigUpdate(uint64(nwid), int(op), (*C.ZT_VirtualNetworkConfig)(conf)))
  317. }
  318. //export goZtEvent
  319. func goZtEvent(gn unsafe.Pointer, eventType C.int, data unsafe.Pointer) {
  320. nodesByUserPtrLock.RLock()
  321. node := nodesByUserPtr[uintptr(gn)]
  322. nodesByUserPtrLock.RUnlock()
  323. if node == nil {
  324. return
  325. }
  326. switch eventType {
  327. case C.ZT_EVENT_OFFLINE:
  328. atomic.StoreUint32(&node.online, 0)
  329. case C.ZT_EVENT_ONLINE:
  330. atomic.StoreUint32(&node.online, 1)
  331. case C.ZT_EVENT_TRACE:
  332. node.handleTrace(C.GoString((*C.char)(data)))
  333. case C.ZT_EVENT_USER_MESSAGE:
  334. um := (*C.ZT_UserMessage)(data)
  335. node.handleUserMessage(uint64(um.origin), uint64(um.typeId), C.GoBytes(um.data, C.int(um.length)))
  336. case C.ZT_EVENT_REMOTE_TRACE:
  337. rt := (*C.ZT_RemoteTrace)(data)
  338. node.handleRemoteTrace(uint64(rt.origin), C.GoBytes(unsafe.Pointer(rt.data), C.int(rt.len)))
  339. }
  340. }
  341. // These are really part of nativeTap
  342. func handleTapMulticastGroupChange(gn unsafe.Pointer, nwid, mac C.uint64_t, adi C.uint32_t, added bool) {
  343. nodesByUserPtrLock.RLock()
  344. node := nodesByUserPtr[uintptr(gn)]
  345. nodesByUserPtrLock.RUnlock()
  346. if node == nil {
  347. return
  348. }
  349. node.networksLock.RLock()
  350. network := node.networks[uint64(nwid)]
  351. node.networksLock.RUnlock()
  352. network.tapLock.Lock()
  353. tap, _ := network.tap.(*nativeTap)
  354. network.tapLock.Unlock()
  355. if tap != nil {
  356. mg := &MulticastGroup{MAC: MAC(mac), ADI: uint32(adi)}
  357. tap.multicastGroupHandlersLock.Lock()
  358. defer tap.multicastGroupHandlersLock.Unlock()
  359. for _, h := range tap.multicastGroupHandlers {
  360. h(added, mg)
  361. }
  362. }
  363. }
  364. //export goHandleTapAddedMulticastGroup
  365. func goHandleTapAddedMulticastGroup(gn, tapP unsafe.Pointer, nwid, mac C.uint64_t, adi C.uint32_t) {
  366. handleTapMulticastGroupChange(gn, nwid, mac, adi, true)
  367. }
  368. //export goHandleTapRemovedMulticastGroup
  369. func goHandleTapRemovedMulticastGroup(gn, tapP unsafe.Pointer, nwid, mac C.uint64_t, adi C.uint32_t) {
  370. handleTapMulticastGroupChange(gn, nwid, mac, adi, false)
  371. }
  372. //////////////////////////////////////////////////////////////////////////////
  373. // nativeTap is a Tap implementation that wraps a native C++ interface to a system tun/tap device
  374. type nativeTap struct {
  375. tap unsafe.Pointer
  376. networkStatus uint32
  377. enabled uint32
  378. multicastGroupHandlers []func(bool, *MulticastGroup)
  379. multicastGroupHandlersLock sync.Mutex
  380. }
  381. // Type returns a human-readable description of this tap implementation
  382. func (t *nativeTap) Type() string {
  383. return "native"
  384. }
  385. // Error gets this tap device's error status
  386. func (t *nativeTap) Error() (int, string) {
  387. return 0, ""
  388. }
  389. // SetEnabled sets this tap's enabled state
  390. func (t *nativeTap) SetEnabled(enabled bool) {
  391. if enabled && atomic.SwapUint32(&t.enabled, 1) == 0 {
  392. C.ZT_GoTap_setEnabled(t.tap, 1)
  393. } else if !enabled && atomic.SwapUint32(&t.enabled, 0) == 1 {
  394. C.ZT_GoTap_setEnabled(t.tap, 0)
  395. }
  396. }
  397. // Enabled returns true if this tap is currently processing packets
  398. func (t *nativeTap) Enabled() bool {
  399. return atomic.LoadUint32(&t.enabled) != 0
  400. }
  401. // AddIP adds an IP address (with netmask) to this tap
  402. func (t *nativeTap) AddIP(ip net.IPNet) error {
  403. bits, _ := ip.Mask.Size()
  404. if len(ip.IP) == 16 {
  405. if bits > 128 || bits < 0 {
  406. return ErrInvalidParameter
  407. }
  408. C.ZT_GoTap_addIp(t.tap, C.int(afInet6), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  409. } else if len(ip.IP) == 4 {
  410. if bits > 32 || bits < 0 {
  411. return ErrInvalidParameter
  412. }
  413. C.ZT_GoTap_addIp(t.tap, C.int(afInet), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  414. }
  415. return ErrInvalidParameter
  416. }
  417. // RemoveIP removes this IP address (with netmask) from this tap
  418. func (t *nativeTap) RemoveIP(ip net.IPNet) error {
  419. bits, _ := ip.Mask.Size()
  420. if len(ip.IP) == 16 {
  421. if bits > 128 || bits < 0 {
  422. return ErrInvalidParameter
  423. }
  424. C.ZT_GoTap_removeIp(t.tap, C.int(afInet6), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  425. return nil
  426. }
  427. if len(ip.IP) == 4 {
  428. if bits > 32 || bits < 0 {
  429. return ErrInvalidParameter
  430. }
  431. C.ZT_GoTap_removeIp(t.tap, C.int(afInet), unsafe.Pointer(&ip.IP[0]), C.int(bits))
  432. return nil
  433. }
  434. return ErrInvalidParameter
  435. }
  436. // IPs returns IPs currently assigned to this tap (including externally or system-assigned IPs)
  437. func (t *nativeTap) IPs() (ips []net.IPNet, err error) {
  438. defer func() {
  439. e := recover()
  440. if e != nil {
  441. err = fmt.Errorf("%v", e)
  442. }
  443. }()
  444. var ipbuf [16384]byte
  445. count := int(C.ZT_GoTap_ips(t.tap, unsafe.Pointer(&ipbuf[0]), 16384))
  446. ipptr := 0
  447. for i := 0; i < count; i++ {
  448. af := int(ipbuf[ipptr])
  449. ipptr++
  450. switch af {
  451. case afInet:
  452. var ip [4]byte
  453. for j := 0; j < 4; j++ {
  454. ip[j] = ipbuf[ipptr]
  455. ipptr++
  456. }
  457. bits := ipbuf[ipptr]
  458. ipptr++
  459. ips = append(ips, net.IPNet{IP: net.IP(ip[:]), Mask: net.CIDRMask(int(bits), 32)})
  460. case afInet6:
  461. var ip [16]byte
  462. for j := 0; j < 16; j++ {
  463. ip[j] = ipbuf[ipptr]
  464. ipptr++
  465. }
  466. bits := ipbuf[ipptr]
  467. ipptr++
  468. ips = append(ips, net.IPNet{IP: net.IP(ip[:]), Mask: net.CIDRMask(int(bits), 128)})
  469. }
  470. }
  471. return
  472. }
  473. // DeviceName gets this tap's OS-specific device name
  474. func (t *nativeTap) DeviceName() string {
  475. var dn [256]byte
  476. C.ZT_GoTap_deviceName(t.tap, (*C.char)(unsafe.Pointer(&dn[0])))
  477. for i, b := range dn {
  478. if b == 0 {
  479. return string(dn[0:i])
  480. }
  481. }
  482. return ""
  483. }
  484. // AddMulticastGroupChangeHandler adds a function to be called when the tap subscribes or unsubscribes to a multicast group.
  485. func (t *nativeTap) AddMulticastGroupChangeHandler(handler func(bool, *MulticastGroup)) {
  486. t.multicastGroupHandlersLock.Lock()
  487. t.multicastGroupHandlers = append(t.multicastGroupHandlers, handler)
  488. t.multicastGroupHandlersLock.Unlock()
  489. }