zerotier.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. package ganserv
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net/http"
  9. "os"
  10. "strconv"
  11. "strings"
  12. )
  13. /*
  14. zerotier.go
  15. This hold the functions that required to communicate with
  16. a zerotier instance
  17. See more on
  18. https://docs.zerotier.com/self-hosting/network-controllers/
  19. */
  20. type NodeInfo struct {
  21. Address string `json:"address"`
  22. Clock int64 `json:"clock"`
  23. Config struct {
  24. Settings struct {
  25. AllowTCPFallbackRelay bool `json:"allowTcpFallbackRelay"`
  26. PortMappingEnabled bool `json:"portMappingEnabled"`
  27. PrimaryPort int `json:"primaryPort"`
  28. SoftwareUpdate string `json:"softwareUpdate"`
  29. SoftwareUpdateChannel string `json:"softwareUpdateChannel"`
  30. } `json:"settings"`
  31. } `json:"config"`
  32. Online bool `json:"online"`
  33. PlanetWorldID int `json:"planetWorldId"`
  34. PlanetWorldTimestamp int64 `json:"planetWorldTimestamp"`
  35. PublicIdentity string `json:"publicIdentity"`
  36. TCPFallbackActive bool `json:"tcpFallbackActive"`
  37. Version string `json:"version"`
  38. VersionBuild int `json:"versionBuild"`
  39. VersionMajor int `json:"versionMajor"`
  40. VersionMinor int `json:"versionMinor"`
  41. VersionRev int `json:"versionRev"`
  42. }
  43. type ErrResp struct {
  44. Message string `json:"message"`
  45. }
  46. type NetworkInfo struct {
  47. AuthTokens []interface{} `json:"authTokens"`
  48. AuthorizationEndpoint string `json:"authorizationEndpoint"`
  49. Capabilities []interface{} `json:"capabilities"`
  50. ClientID string `json:"clientId"`
  51. CreationTime int64 `json:"creationTime"`
  52. DNS []interface{} `json:"dns"`
  53. EnableBroadcast bool `json:"enableBroadcast"`
  54. ID string `json:"id"`
  55. IPAssignmentPools []interface{} `json:"ipAssignmentPools"`
  56. Mtu int `json:"mtu"`
  57. MulticastLimit int `json:"multicastLimit"`
  58. Name string `json:"name"`
  59. Nwid string `json:"nwid"`
  60. Objtype string `json:"objtype"`
  61. Private bool `json:"private"`
  62. RemoteTraceLevel int `json:"remoteTraceLevel"`
  63. RemoteTraceTarget interface{} `json:"remoteTraceTarget"`
  64. Revision int `json:"revision"`
  65. Routes []interface{} `json:"routes"`
  66. Rules []struct {
  67. Not bool `json:"not"`
  68. Or bool `json:"or"`
  69. Type string `json:"type"`
  70. } `json:"rules"`
  71. RulesSource string `json:"rulesSource"`
  72. SsoEnabled bool `json:"ssoEnabled"`
  73. Tags []interface{} `json:"tags"`
  74. V4AssignMode struct {
  75. Zt bool `json:"zt"`
  76. } `json:"v4AssignMode"`
  77. V6AssignMode struct {
  78. SixPlane bool `json:"6plane"`
  79. Rfc4193 bool `json:"rfc4193"`
  80. Zt bool `json:"zt"`
  81. } `json:"v6AssignMode"`
  82. }
  83. //Get the zerotier node info from local service
  84. func getControllerInfo(token string, apiPort int) (*NodeInfo, error) {
  85. url := "http://localhost:" + strconv.Itoa(apiPort) + "/status"
  86. req, err := http.NewRequest("GET", url, nil)
  87. if err != nil {
  88. return nil, err
  89. }
  90. req.Header.Set("X-ZT1-AUTH", token)
  91. client := &http.Client{}
  92. resp, err := client.Do(req)
  93. if err != nil {
  94. return nil, err
  95. }
  96. //Read from zerotier service instance
  97. defer resp.Body.Close()
  98. payload, err := io.ReadAll(resp.Body)
  99. if err != nil {
  100. return nil, err
  101. }
  102. //Parse the payload into struct
  103. thisInstanceInfo := NodeInfo{}
  104. err = json.Unmarshal(payload, &thisInstanceInfo)
  105. if err != nil {
  106. return nil, err
  107. }
  108. return &thisInstanceInfo, nil
  109. }
  110. /*
  111. Network Functions
  112. */
  113. //Create a zerotier network
  114. func (m *NetworkManager) createNetwork() (*NetworkInfo, error) {
  115. url := fmt.Sprintf("http://localhost:"+strconv.Itoa(m.apiPort)+"/controller/network/%s______", m.ControllerID)
  116. data := []byte(`{}`)
  117. req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
  118. if err != nil {
  119. return nil, err
  120. }
  121. req.Header.Set("X-ZT1-AUTH", m.authToken)
  122. client := &http.Client{}
  123. resp, err := client.Do(req)
  124. if err != nil {
  125. return nil, err
  126. }
  127. defer resp.Body.Close()
  128. payload, err := io.ReadAll(resp.Body)
  129. if err != nil {
  130. return nil, err
  131. }
  132. networkInfo := NetworkInfo{}
  133. err = json.Unmarshal(payload, &networkInfo)
  134. if err != nil {
  135. return nil, err
  136. }
  137. return &networkInfo, nil
  138. }
  139. //List network details
  140. func (m *NetworkManager) getNetworkInfoById(networkId string) (*NetworkInfo, error) {
  141. req, err := http.NewRequest("GET", os.ExpandEnv("http://localhost:"+strconv.Itoa(m.apiPort)+"/controller/network/"+networkId+"/"), nil)
  142. if err != nil {
  143. return nil, err
  144. }
  145. req.Header.Set("X-Zt1-Auth", m.authToken)
  146. resp, err := http.DefaultClient.Do(req)
  147. if err != nil {
  148. return nil, err
  149. }
  150. defer resp.Body.Close()
  151. if resp.StatusCode != 200 {
  152. return nil, errors.New("network error. Status code: " + strconv.Itoa(resp.StatusCode))
  153. }
  154. thisNetworkInfo := NetworkInfo{}
  155. payload, err := io.ReadAll(resp.Body)
  156. if err != nil {
  157. return nil, err
  158. }
  159. err = json.Unmarshal(payload, &thisNetworkInfo)
  160. if err != nil {
  161. return nil, err
  162. }
  163. return &thisNetworkInfo, nil
  164. }
  165. func (m *NetworkManager) setNetworkInfoByID(networkId string, newNetworkInfo *NetworkInfo) error {
  166. payloadBytes, err := json.Marshal(newNetworkInfo)
  167. if err != nil {
  168. return err
  169. }
  170. payloadBuffer := bytes.NewBuffer(payloadBytes)
  171. // Create the HTTP request
  172. url := "http://localhost:" + strconv.Itoa(m.apiPort) + "/controller/network/" + networkId + "/"
  173. req, err := http.NewRequest("POST", url, payloadBuffer)
  174. if err != nil {
  175. return err
  176. }
  177. req.Header.Set("X-Zt1-Auth", m.authToken)
  178. req.Header.Set("Content-Type", "application/json")
  179. // Send the HTTP request
  180. resp, err := http.DefaultClient.Do(req)
  181. if err != nil {
  182. return err
  183. }
  184. defer resp.Body.Close()
  185. // Print the response status code
  186. if resp.StatusCode != 200 {
  187. return errors.New("network error. status code: " + strconv.Itoa(resp.StatusCode))
  188. }
  189. return nil
  190. }
  191. //List network IDs
  192. func (m *NetworkManager) listNetworkIds() ([]string, error) {
  193. req, err := http.NewRequest("GET", "http://localhost:"+strconv.Itoa(m.apiPort)+"/controller/network/", nil)
  194. if err != nil {
  195. return []string{}, err
  196. }
  197. req.Header.Set("X-Zt1-Auth", m.authToken)
  198. resp, err := http.DefaultClient.Do(req)
  199. if err != nil {
  200. return []string{}, err
  201. }
  202. defer resp.Body.Close()
  203. if resp.StatusCode != 200 {
  204. return []string{}, errors.New("network error")
  205. }
  206. networkIds := []string{}
  207. payload, err := io.ReadAll(resp.Body)
  208. if err != nil {
  209. return []string{}, err
  210. }
  211. err = json.Unmarshal(payload, &networkIds)
  212. if err != nil {
  213. return []string{}, err
  214. }
  215. return networkIds, nil
  216. }
  217. //wrapper for checking if a network id exists
  218. func (m *NetworkManager) networkExists(networkId string) bool {
  219. networkIds, err := m.listNetworkIds()
  220. if err != nil {
  221. return false
  222. }
  223. for _, thisid := range networkIds {
  224. if thisid == networkId {
  225. return true
  226. }
  227. }
  228. return false
  229. }
  230. //delete a network
  231. func (m *NetworkManager) deleteNetwork(networkID string) error {
  232. url := "http://localhost:" + strconv.Itoa(m.apiPort) + "/controller/network/" + networkID + "/"
  233. client := &http.Client{}
  234. // Create a new DELETE request
  235. req, err := http.NewRequest("DELETE", url, nil)
  236. if err != nil {
  237. return err
  238. }
  239. // Add the required authorization header
  240. req.Header.Set("X-Zt1-Auth", m.authToken)
  241. // Send the request and get the response
  242. resp, err := client.Do(req)
  243. if err != nil {
  244. return err
  245. }
  246. // Close the response body when we're done
  247. defer resp.Body.Close()
  248. s, err := io.ReadAll(resp.Body)
  249. fmt.Println(string(s), err, resp.StatusCode)
  250. // Print the response status code
  251. if resp.StatusCode != 200 {
  252. return errors.New("network error. status code: " + strconv.Itoa(resp.StatusCode))
  253. }
  254. return nil
  255. }
  256. //Configure network
  257. //Example: configureNetwork(netid, "192.168.192.1", "192.168.192.254", "192.168.192.0/24")
  258. func (m *NetworkManager) configureNetwork(networkID string, ipRangeStart string, ipRangeEnd string, routeTarget string) error {
  259. url := "http://localhost:" + strconv.Itoa(m.apiPort) + "/controller/network/" + networkID + "/"
  260. data := map[string]interface{}{
  261. "ipAssignmentPools": []map[string]string{
  262. {
  263. "ipRangeStart": ipRangeStart,
  264. "ipRangeEnd": ipRangeEnd,
  265. },
  266. },
  267. "routes": []map[string]interface{}{
  268. {
  269. "target": routeTarget,
  270. "via": nil,
  271. },
  272. },
  273. "v4AssignMode": "zt",
  274. "private": true,
  275. }
  276. payload, err := json.Marshal(data)
  277. if err != nil {
  278. return err
  279. }
  280. req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
  281. if err != nil {
  282. return err
  283. }
  284. req.Header.Set("Content-Type", "application/json")
  285. req.Header.Set("X-ZT1-AUTH", m.authToken)
  286. client := &http.Client{}
  287. resp, err := client.Do(req)
  288. if err != nil {
  289. return err
  290. }
  291. defer resp.Body.Close()
  292. // Print the response status code
  293. if resp.StatusCode != 200 {
  294. return errors.New("network error. status code: " + strconv.Itoa(resp.StatusCode))
  295. }
  296. return nil
  297. }
  298. func (m *NetworkManager) setNetworkNameAndDescription(netid string, name string, desc string) error {
  299. // Convert string to rune slice
  300. r := []rune(name)
  301. // Loop over runes and remove non-ASCII characters
  302. for i, v := range r {
  303. if v > 127 {
  304. r[i] = ' '
  305. }
  306. }
  307. // Convert back to string and trim whitespace
  308. name = strings.TrimSpace(string(r))
  309. url := "http://localhost:" + strconv.Itoa(m.apiPort) + "/controller/network/" + netid + "/"
  310. data := map[string]interface{}{
  311. "name": name,
  312. }
  313. payload, err := json.Marshal(data)
  314. if err != nil {
  315. return err
  316. }
  317. req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
  318. if err != nil {
  319. return err
  320. }
  321. req.Header.Set("Content-Type", "application/json")
  322. req.Header.Set("X-ZT1-AUTH", m.authToken)
  323. client := &http.Client{}
  324. resp, err := client.Do(req)
  325. if err != nil {
  326. return err
  327. }
  328. defer resp.Body.Close()
  329. // Print the response status code
  330. if resp.StatusCode != 200 {
  331. return errors.New("network error. status code: " + strconv.Itoa(resp.StatusCode))
  332. }
  333. meta := m.GetNetworkMetaData(netid)
  334. if meta != nil {
  335. meta.Desc = desc
  336. m.WriteNetworkMetaData(netid, meta)
  337. }
  338. return nil
  339. }
  340. func (m *NetworkManager) getNetworkNameAndDescription(netid string) (string, string, error) {
  341. //Get name from network info
  342. netinfo, err := m.getNetworkInfoById(netid)
  343. if err != nil {
  344. return "", "", err
  345. }
  346. name := netinfo.Name
  347. //Get description from meta
  348. desc := ""
  349. networkMeta := m.GetNetworkMetaData(netid)
  350. if networkMeta != nil {
  351. desc = networkMeta.Desc
  352. }
  353. return name, desc, nil
  354. }
  355. /*
  356. Member functions
  357. */
  358. func (m *NetworkManager) getNetworkMembers(networkId string) ([]string, error) {
  359. url := "http://localhost:" + strconv.Itoa(m.apiPort) + "/controller/network/" + networkId + "/member"
  360. reqBody := bytes.NewBuffer([]byte{})
  361. req, err := http.NewRequest("GET", url, reqBody)
  362. if err != nil {
  363. return nil, err
  364. }
  365. req.Header.Set("X-ZT1-AUTH", m.authToken)
  366. client := &http.Client{}
  367. resp, err := client.Do(req)
  368. if err != nil {
  369. return nil, err
  370. }
  371. defer resp.Body.Close()
  372. if resp.StatusCode != http.StatusOK {
  373. return nil, errors.New("failed to get network members")
  374. }
  375. memberList := map[string]int{}
  376. payload, err := io.ReadAll(resp.Body)
  377. if err != nil {
  378. return nil, err
  379. }
  380. err = json.Unmarshal(payload, &memberList)
  381. if err != nil {
  382. return nil, err
  383. }
  384. members := make([]string, 0, len(memberList))
  385. for k := range memberList {
  386. members = append(members, k)
  387. }
  388. return members, nil
  389. }