api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. /*
  2. * Copyright (c)2013-2020 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: 2024-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. import (
  15. "bytes"
  16. secrand "crypto/rand"
  17. "encoding/json"
  18. "fmt"
  19. "io/ioutil"
  20. "net"
  21. "net/http"
  22. "path"
  23. "runtime"
  24. "strconv"
  25. "strings"
  26. "time"
  27. "github.com/hectane/go-acl"
  28. )
  29. // APISocketName is the default socket name for accessing the API
  30. const APISocketName = "apisocket"
  31. var startTime = TimeMs()
  32. // APIGet makes a query to the API via a Unix domain or windows pipe socket
  33. func APIGet(basePath, socketName, authToken, queryPath string, obj interface{}) (int, int64, error) {
  34. client, err := createNamedSocketHTTPClient(basePath, socketName)
  35. if err != nil {
  36. return http.StatusTeapot, 0, err
  37. }
  38. req, err := http.NewRequest("GET", "http://socket"+queryPath, nil)
  39. if err != nil {
  40. return http.StatusTeapot, 0, err
  41. }
  42. req.Header.Add("Authorization", "bearer "+authToken)
  43. resp, err := client.Do(req)
  44. if err != nil {
  45. return http.StatusTeapot, 0, err
  46. }
  47. err = json.NewDecoder(resp.Body).Decode(obj)
  48. ts := resp.Header.Get("X-ZT-Clock")
  49. t := int64(0)
  50. if len(ts) > 0 {
  51. t, _ = strconv.ParseInt(ts, 10, 64)
  52. }
  53. return resp.StatusCode, t, err
  54. }
  55. // APIPost posts a JSON object to the API via a Unix domain or windows pipe socket and reads a response
  56. func APIPost(basePath, socketName, authToken, queryPath string, post, result interface{}) (int, int64, error) {
  57. client, err := createNamedSocketHTTPClient(basePath, socketName)
  58. if err != nil {
  59. return http.StatusTeapot, 0, err
  60. }
  61. var data []byte
  62. if post != nil {
  63. data, err = json.Marshal(post)
  64. if err != nil {
  65. return http.StatusTeapot, 0, err
  66. }
  67. } else {
  68. data = []byte("null")
  69. }
  70. req, err := http.NewRequest("POST", "http://socket"+queryPath, bytes.NewReader(data))
  71. if err != nil {
  72. return http.StatusTeapot, 0, err
  73. }
  74. req.Header.Add("Content-Type", "application/json")
  75. req.Header.Add("Authorization", "bearer "+authToken)
  76. resp, err := client.Do(req)
  77. if err != nil {
  78. return http.StatusTeapot, 0, err
  79. }
  80. ts := resp.Header.Get("X-ZT-Clock")
  81. t := int64(0)
  82. if len(ts) > 0 {
  83. t, _ = strconv.ParseInt(ts, 10, 64)
  84. }
  85. if result != nil {
  86. err = json.NewDecoder(resp.Body).Decode(result)
  87. return resp.StatusCode, t, err
  88. }
  89. return resp.StatusCode, t, nil
  90. }
  91. // APIDelete posts DELETE to a path and fills result with the outcome (if any) if result is non-nil
  92. func APIDelete(basePath, socketName, authToken, queryPath string, result interface{}) (int, int64, error) {
  93. client, err := createNamedSocketHTTPClient(basePath, socketName)
  94. if err != nil {
  95. return http.StatusTeapot, 0, err
  96. }
  97. req, err := http.NewRequest("DELETE", "http://socket"+queryPath, nil)
  98. if err != nil {
  99. return http.StatusTeapot, 0, err
  100. }
  101. req.Header.Add("Authorization", "bearer "+authToken)
  102. resp, err := client.Do(req)
  103. if err != nil {
  104. return http.StatusTeapot, 0, err
  105. }
  106. ts := resp.Header.Get("X-ZT-Clock")
  107. t := int64(0)
  108. if len(ts) > 0 {
  109. t, _ = strconv.ParseInt(ts, 10, 64)
  110. }
  111. if result != nil {
  112. err = json.NewDecoder(resp.Body).Decode(result)
  113. return resp.StatusCode, t, err
  114. }
  115. return resp.StatusCode, t, nil
  116. }
  117. // APIStatus is the object returned by API status inquiries
  118. type APIStatus struct {
  119. Address Address `json:"address"`
  120. Clock int64 `json:"clock"`
  121. StartupTime int64 `json:"startupTime"`
  122. Config LocalConfig `json:"config"`
  123. Online bool `json:"online"`
  124. PeerCount int `json:"peerCount"`
  125. PathCount int `json:"pathCount"`
  126. Identity *Identity `json:"identity"`
  127. InterfaceAddresses []net.IP `json:"interfaceAddresses,omitempty"`
  128. MappedExternalAddresses []*InetAddress `json:"mappedExternalAddresses,omitempty"`
  129. Version string `json:"version"`
  130. VersionMajor int `json:"versionMajor"`
  131. VersionMinor int `json:"versionMinor"`
  132. VersionRevision int `json:"versionRevision"`
  133. VersionBuild int `json:"versionBuild"`
  134. OS string `json:"os"`
  135. Architecture string `json:"architecture"`
  136. Concurrency int `json:"concurrency"`
  137. Runtime string `json:"runtimeVersion"`
  138. }
  139. // APINetwork is the object returned by API network inquiries
  140. type APINetwork struct {
  141. ID NetworkID `json:"id"`
  142. Config NetworkConfig `json:"config"`
  143. Settings *NetworkLocalSettings `json:"settings,omitempty"`
  144. MulticastSubscriptions []*MulticastGroup `json:"multicastSubscriptions,omitempty"`
  145. PortType string `json:"portType"`
  146. PortName string `json:"portName"`
  147. PortEnabled bool `json:"portEnabled"`
  148. PortErrorCode int `json:"portErrorCode"`
  149. PortError string `json:"portError"`
  150. }
  151. func apiNetworkFromNetwork(n *Network) *APINetwork {
  152. var nn APINetwork
  153. nn.ID = n.ID()
  154. nn.Config = n.Config()
  155. ls := n.LocalSettings()
  156. nn.Settings = &ls
  157. nn.MulticastSubscriptions = n.MulticastSubscriptions()
  158. nn.PortType = n.Tap().Type()
  159. nn.PortName = n.Tap().DeviceName()
  160. nn.PortEnabled = n.Tap().Enabled()
  161. ec, errStr := n.Tap().Error()
  162. nn.PortErrorCode = ec
  163. nn.PortError = errStr
  164. return &nn
  165. }
  166. func apiSetStandardHeaders(out http.ResponseWriter) {
  167. h := out.Header()
  168. h.Set("Cache-Control", "no-cache, no-store, must-revalidate")
  169. h.Set("Expires", "0")
  170. h.Set("Pragma", "no-cache")
  171. t := time.Now().UTC()
  172. h.Set("Date", t.Format(time.RFC1123))
  173. h.Set("X-ZT-Clock", strconv.FormatInt(t.UnixNano()/int64(1000000), 10))
  174. }
  175. func apiSendObj(out http.ResponseWriter, req *http.Request, httpStatusCode int, obj interface{}) error {
  176. h := out.Header()
  177. h.Set("Content-Type", "application/json")
  178. if req.Method == http.MethodHead {
  179. out.WriteHeader(httpStatusCode)
  180. return nil
  181. }
  182. var j []byte
  183. var err error
  184. if obj != nil {
  185. j, err = json.Marshal(obj)
  186. if err != nil {
  187. return err
  188. }
  189. }
  190. out.WriteHeader(httpStatusCode)
  191. _, err = out.Write(j)
  192. return err
  193. }
  194. func apiReadObj(out http.ResponseWriter, req *http.Request, dest interface{}) (err error) {
  195. err = json.NewDecoder(req.Body).Decode(&dest)
  196. if err != nil {
  197. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"invalid JSON: " + err.Error()})
  198. }
  199. return
  200. }
  201. func apiCheckAuth(out http.ResponseWriter, req *http.Request, token string) bool {
  202. ah := req.Header.Get("Authorization")
  203. if len(ah) > 0 && strings.TrimSpace(ah) == ("bearer "+token) {
  204. return true
  205. }
  206. ah = req.Header.Get("X-ZT1-Auth")
  207. if len(ah) > 0 && strings.TrimSpace(ah) == token {
  208. return true
  209. }
  210. _ = apiSendObj(out, req, http.StatusUnauthorized, &APIErr{"authorization token not found or incorrect (checked X-ZT1-Auth and Authorization headers)"})
  211. return false
  212. }
  213. type peerMutableFields struct {
  214. Identity *Identity `json:"identity"`
  215. Role *int `json:"role"`
  216. Bootstrap *InetAddress `json:"bootstrap,omitempty"`
  217. }
  218. // createAPIServer creates and starts an HTTP server for a given node
  219. func createAPIServer(basePath string, node *Node) (*http.Server, *http.Server, error) {
  220. // Read authorization token, automatically generating one if it's missing
  221. var authToken string
  222. authTokenFile := path.Join(basePath, "authtoken.secret")
  223. authTokenB, err := ioutil.ReadFile(authTokenFile)
  224. if err != nil {
  225. var atb [20]byte
  226. _, err = secrand.Read(atb[:])
  227. if err != nil {
  228. return nil, nil, err
  229. }
  230. for i := 0; i < 20; i++ {
  231. atb[i] = "abcdefghijklmnopqrstuvwxyz0123456789"[atb[i]%36]
  232. }
  233. err = ioutil.WriteFile(authTokenFile, atb[:], 0600)
  234. if err != nil {
  235. return nil, nil, err
  236. }
  237. _ = acl.Chmod(authTokenFile, 0600)
  238. authToken = string(atb[:])
  239. } else {
  240. authToken = strings.TrimSpace(string(authTokenB))
  241. }
  242. smux := http.NewServeMux()
  243. ////////////////////////////////////////////////////////////////////////////
  244. smux.HandleFunc("/status", func(out http.ResponseWriter, req *http.Request) {
  245. defer func() {
  246. e := recover()
  247. if e != nil {
  248. _ = apiSendObj(out, req, http.StatusInternalServerError, nil)
  249. }
  250. }()
  251. if !apiCheckAuth(out, req, authToken) {
  252. return
  253. }
  254. apiSetStandardHeaders(out)
  255. if req.Method == http.MethodGet || req.Method == http.MethodHead {
  256. pathCount := 0
  257. peers := node.Peers()
  258. for _, p := range peers {
  259. pathCount += len(p.Paths)
  260. }
  261. _ = apiSendObj(out, req, http.StatusOK, &APIStatus{
  262. Address: node.Address(),
  263. Clock: TimeMs(),
  264. StartupTime: startTime,
  265. Config: node.LocalConfig(),
  266. Online: node.Online(),
  267. PeerCount: len(peers),
  268. PathCount: pathCount,
  269. Identity: node.Identity(),
  270. InterfaceAddresses: node.InterfaceAddresses(),
  271. MappedExternalAddresses: nil,
  272. Version: fmt.Sprintf("%d.%d.%d", CoreVersionMajor, CoreVersionMinor, CoreVersionRevision),
  273. VersionMajor: CoreVersionMajor,
  274. VersionMinor: CoreVersionMinor,
  275. VersionRevision: CoreVersionRevision,
  276. VersionBuild: CoreVersionBuild,
  277. OS: runtime.GOOS,
  278. Architecture: runtime.GOARCH,
  279. Concurrency: runtime.NumCPU(),
  280. Runtime: runtime.Version(),
  281. })
  282. } else {
  283. out.Header().Set("Allow", "GET, HEAD")
  284. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"/status is read-only"})
  285. }
  286. })
  287. ////////////////////////////////////////////////////////////////////////////
  288. smux.HandleFunc("/config", func(out http.ResponseWriter, req *http.Request) {
  289. defer func() {
  290. e := recover()
  291. if e != nil {
  292. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  293. }
  294. }()
  295. if !apiCheckAuth(out, req, authToken) {
  296. return
  297. }
  298. apiSetStandardHeaders(out)
  299. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  300. var c LocalConfig
  301. if apiReadObj(out, req, &c) == nil {
  302. _, err := node.SetLocalConfig(&c)
  303. if err != nil {
  304. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"error applying local config: " + err.Error()})
  305. } else {
  306. lc := node.LocalConfig()
  307. _ = apiSendObj(out, req, http.StatusOK, &lc)
  308. }
  309. }
  310. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  311. _ = apiSendObj(out, req, http.StatusOK, node.LocalConfig())
  312. } else {
  313. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  314. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method: " + req.Method})
  315. }
  316. })
  317. ////////////////////////////////////////////////////////////////////////////
  318. smux.HandleFunc("/peer/", func(out http.ResponseWriter, req *http.Request) {
  319. defer func() {
  320. e := recover()
  321. if e != nil {
  322. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  323. }
  324. }()
  325. if !apiCheckAuth(out, req, authToken) {
  326. return
  327. }
  328. apiSetStandardHeaders(out)
  329. var queriedID Address
  330. if len(req.URL.Path) > 6 {
  331. var err error
  332. queriedID, err = NewAddressFromString(req.URL.Path[6:])
  333. if err != nil {
  334. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  335. return
  336. }
  337. }
  338. // Right now POST/PUT is only used with peers to add or remove root servers.
  339. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  340. if queriedID == 0 {
  341. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  342. return
  343. }
  344. var peerChanges peerMutableFields
  345. if apiReadObj(out, req, &peerChanges) == nil {
  346. if peerChanges.Role != nil || peerChanges.Bootstrap != nil {
  347. peers := node.Peers()
  348. for _, p := range peers {
  349. if p.Address == queriedID && (peerChanges.Identity == nil || peerChanges.Identity.Equals(p.Identity)) {
  350. if peerChanges.Role != nil && *peerChanges.Role != p.Role {
  351. if *peerChanges.Role == PeerRoleRoot {
  352. _ = node.AddRoot(p.Identity, peerChanges.Bootstrap)
  353. } else {
  354. node.RemoveRoot(p.Identity)
  355. }
  356. }
  357. break
  358. }
  359. }
  360. }
  361. } else {
  362. return
  363. }
  364. }
  365. if req.Method == http.MethodGet || req.Method == http.MethodHead || req.Method == http.MethodPost || req.Method == http.MethodPut {
  366. peers := node.Peers()
  367. if queriedID != 0 {
  368. for _, p := range peers {
  369. if p.Address == queriedID {
  370. _ = apiSendObj(out, req, http.StatusOK, p)
  371. return
  372. }
  373. }
  374. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  375. } else {
  376. _ = apiSendObj(out, req, http.StatusOK, peers)
  377. }
  378. } else {
  379. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  380. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"peers are read only"})
  381. }
  382. })
  383. ////////////////////////////////////////////////////////////////////////////
  384. smux.HandleFunc("/network/", func(out http.ResponseWriter, req *http.Request) {
  385. defer func() {
  386. e := recover()
  387. if e != nil {
  388. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  389. }
  390. }()
  391. if !apiCheckAuth(out, req, authToken) {
  392. return
  393. }
  394. apiSetStandardHeaders(out)
  395. var queriedID NetworkID
  396. if len(req.URL.Path) > 9 {
  397. var err error
  398. queriedID, err = NewNetworkIDFromString(req.URL.Path[9:])
  399. if err != nil {
  400. _ = apiSendObj(out, req, http.StatusNotFound, nil)
  401. return
  402. }
  403. }
  404. if req.Method == http.MethodDelete {
  405. if queriedID == 0 {
  406. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only specific networks can be deleted"})
  407. return
  408. }
  409. networks := node.Networks()
  410. for _, nw := range networks {
  411. if nw.id == queriedID {
  412. _ = node.Leave(queriedID)
  413. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  414. return
  415. }
  416. }
  417. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  418. } else if req.Method == http.MethodPost || req.Method == http.MethodPut {
  419. if queriedID == 0 {
  420. _ = apiSendObj(out, req, http.StatusBadRequest, nil)
  421. return
  422. }
  423. var nw APINetwork
  424. if apiReadObj(out, req, &nw) == nil {
  425. n := node.GetNetwork(nw.ID)
  426. if n == nil {
  427. n, err := node.Join(nw.ID, nw.Settings, nil)
  428. if err != nil {
  429. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only individual networks can be added or modified with POST/PUT"})
  430. } else {
  431. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  432. }
  433. } else {
  434. if nw.Settings != nil {
  435. n.SetLocalSettings(nw.Settings)
  436. }
  437. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  438. }
  439. }
  440. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  441. networks := node.Networks()
  442. if queriedID == 0 { // no queried ID lists all networks
  443. nws := make([]*APINetwork, 0, len(networks))
  444. for _, nw := range networks {
  445. nws = append(nws, apiNetworkFromNetwork(nw))
  446. }
  447. _ = apiSendObj(out, req, http.StatusOK, nws)
  448. return
  449. }
  450. for _, nw := range networks {
  451. if nw.ID() == queriedID {
  452. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  453. return
  454. }
  455. }
  456. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  457. } else {
  458. out.Header().Set("Allow", "GET, HEAD, PUT, POST, DELETE")
  459. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method " + req.Method})
  460. }
  461. })
  462. ////////////////////////////////////////////////////////////////////////////
  463. listener, err := createNamedSocketListener(basePath, APISocketName)
  464. if err != nil {
  465. return nil, nil, err
  466. }
  467. httpServer := &http.Server{
  468. MaxHeaderBytes: 4096,
  469. Handler: smux,
  470. IdleTimeout: 10 * time.Second,
  471. ReadTimeout: 10 * time.Second,
  472. WriteTimeout: 600 * time.Second,
  473. }
  474. httpServer.SetKeepAlivesEnabled(true)
  475. go func() {
  476. _ = httpServer.Serve(listener)
  477. _ = listener.Close()
  478. }()
  479. var tcpHttpServer *http.Server
  480. tcpBindAddr := node.LocalConfig().Settings.APITCPBindAddress
  481. if tcpBindAddr != nil {
  482. tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
  483. IP: tcpBindAddr.IP,
  484. Port: tcpBindAddr.Port,
  485. })
  486. if err != nil {
  487. node.infoLog.Printf("ERROR: unable to start API HTTP server at TCP bind address %s: %s (named socket listener startd, continuing anyway)", tcpBindAddr.String(), err.Error())
  488. } else {
  489. tcpHttpServer = &http.Server{
  490. MaxHeaderBytes: 4096,
  491. Handler: smux,
  492. IdleTimeout: 10 * time.Second,
  493. ReadTimeout: 10 * time.Second,
  494. WriteTimeout: 600 * time.Second,
  495. }
  496. tcpHttpServer.SetKeepAlivesEnabled(true)
  497. go func() {
  498. _ = tcpHttpServer.Serve(tcpListener)
  499. _ = tcpListener.Close()
  500. }()
  501. }
  502. }
  503. return httpServer, tcpHttpServer, nil
  504. }