api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. ControllerFingerprint *Fingerprint `json:"controllerFingerprint,omitempty"`
  145. MulticastSubscriptions []*MulticastGroup `json:"multicastSubscriptions,omitempty"`
  146. PortType string `json:"portType"`
  147. PortName string `json:"portName"`
  148. PortEnabled bool `json:"portEnabled"`
  149. PortErrorCode int `json:"portErrorCode"`
  150. PortError string `json:"portError"`
  151. }
  152. func apiNetworkFromNetwork(n *Network) *APINetwork {
  153. var nn APINetwork
  154. nn.ID = n.ID()
  155. nn.Config = n.Config()
  156. ls := n.LocalSettings()
  157. nn.Settings = &ls
  158. nn.MulticastSubscriptions = n.MulticastSubscriptions()
  159. nn.PortType = n.Tap().Type()
  160. nn.PortName = n.Tap().DeviceName()
  161. nn.PortEnabled = n.Tap().Enabled()
  162. ec, errStr := n.Tap().Error()
  163. nn.PortErrorCode = ec
  164. nn.PortError = errStr
  165. return &nn
  166. }
  167. func apiSetStandardHeaders(out http.ResponseWriter) {
  168. h := out.Header()
  169. h.Set("Cache-Control", "no-cache, no-store, must-revalidate")
  170. h.Set("Expires", "0")
  171. h.Set("Pragma", "no-cache")
  172. t := time.Now().UTC()
  173. h.Set("Date", t.Format(time.RFC1123))
  174. h.Set("X-ZT-Clock", strconv.FormatInt(t.UnixNano()/int64(1000000), 10))
  175. }
  176. func apiSendObj(out http.ResponseWriter, req *http.Request, httpStatusCode int, obj interface{}) error {
  177. h := out.Header()
  178. h.Set("Content-Type", "application/json")
  179. if req.Method == http.MethodHead {
  180. out.WriteHeader(httpStatusCode)
  181. return nil
  182. }
  183. var j []byte
  184. var err error
  185. if obj != nil {
  186. j, err = json.Marshal(obj)
  187. if err != nil {
  188. return err
  189. }
  190. }
  191. out.WriteHeader(httpStatusCode)
  192. _, err = out.Write(j)
  193. return err
  194. }
  195. func apiReadObj(out http.ResponseWriter, req *http.Request, dest interface{}) (err error) {
  196. err = json.NewDecoder(req.Body).Decode(&dest)
  197. if err != nil {
  198. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"invalid JSON: " + err.Error()})
  199. }
  200. return
  201. }
  202. func apiCheckAuth(out http.ResponseWriter, req *http.Request, token string) bool {
  203. ah := req.Header.Get("Authorization")
  204. if len(ah) > 0 && strings.TrimSpace(ah) == ("bearer "+token) {
  205. return true
  206. }
  207. ah = req.Header.Get("X-ZT1-Auth")
  208. if len(ah) > 0 && strings.TrimSpace(ah) == token {
  209. return true
  210. }
  211. _ = apiSendObj(out, req, http.StatusUnauthorized, &APIErr{"authorization token not found or incorrect (checked X-ZT1-Auth and Authorization headers)"})
  212. return false
  213. }
  214. // createAPIServer creates and starts an HTTP server for a given node
  215. func createAPIServer(basePath string, node *Node) (*http.Server, *http.Server, error) {
  216. // Read authorization token, automatically generating one if it's missing
  217. var authToken string
  218. authTokenFile := path.Join(basePath, "authtoken.secret")
  219. authTokenB, err := ioutil.ReadFile(authTokenFile)
  220. if err != nil {
  221. var atb [20]byte
  222. _, err = secrand.Read(atb[:])
  223. if err != nil {
  224. return nil, nil, err
  225. }
  226. for i := 0; i < 20; i++ {
  227. atb[i] = "abcdefghijklmnopqrstuvwxyz0123456789"[atb[i]%36]
  228. }
  229. err = ioutil.WriteFile(authTokenFile, atb[:], 0600)
  230. if err != nil {
  231. return nil, nil, err
  232. }
  233. _ = acl.Chmod(authTokenFile, 0600)
  234. authToken = string(atb[:])
  235. } else {
  236. authToken = strings.TrimSpace(string(authTokenB))
  237. }
  238. smux := http.NewServeMux()
  239. ////////////////////////////////////////////////////////////////////////////
  240. smux.HandleFunc("/status", func(out http.ResponseWriter, req *http.Request) {
  241. defer func() {
  242. e := recover()
  243. if e != nil {
  244. _ = apiSendObj(out, req, http.StatusInternalServerError, nil)
  245. }
  246. }()
  247. if !apiCheckAuth(out, req, authToken) {
  248. return
  249. }
  250. apiSetStandardHeaders(out)
  251. if req.Method == http.MethodGet || req.Method == http.MethodHead {
  252. pathCount := 0
  253. peers := node.Peers()
  254. for _, p := range peers {
  255. pathCount += len(p.Paths)
  256. }
  257. _ = apiSendObj(out, req, http.StatusOK, &APIStatus{
  258. Address: node.Address(),
  259. Clock: TimeMs(),
  260. StartupTime: startTime,
  261. Config: node.LocalConfig(),
  262. Online: node.Online(),
  263. PeerCount: len(peers),
  264. PathCount: pathCount,
  265. Identity: node.Identity(),
  266. InterfaceAddresses: node.InterfaceAddresses(),
  267. MappedExternalAddresses: nil,
  268. Version: fmt.Sprintf("%d.%d.%d", CoreVersionMajor, CoreVersionMinor, CoreVersionRevision),
  269. VersionMajor: CoreVersionMajor,
  270. VersionMinor: CoreVersionMinor,
  271. VersionRevision: CoreVersionRevision,
  272. VersionBuild: CoreVersionBuild,
  273. OS: runtime.GOOS,
  274. Architecture: runtime.GOARCH,
  275. Concurrency: runtime.NumCPU(),
  276. Runtime: runtime.Version(),
  277. })
  278. } else {
  279. out.Header().Set("Allow", "GET, HEAD")
  280. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"/status is read-only"})
  281. }
  282. })
  283. ////////////////////////////////////////////////////////////////////////////
  284. smux.HandleFunc("/config", func(out http.ResponseWriter, req *http.Request) {
  285. defer func() {
  286. e := recover()
  287. if e != nil {
  288. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  289. }
  290. }()
  291. if !apiCheckAuth(out, req, authToken) {
  292. return
  293. }
  294. apiSetStandardHeaders(out)
  295. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  296. var c LocalConfig
  297. if apiReadObj(out, req, &c) == nil {
  298. _, err := node.SetLocalConfig(&c)
  299. if err != nil {
  300. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"error applying local config: " + err.Error()})
  301. } else {
  302. lc := node.LocalConfig()
  303. _ = apiSendObj(out, req, http.StatusOK, &lc)
  304. }
  305. }
  306. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  307. _ = apiSendObj(out, req, http.StatusOK, node.LocalConfig())
  308. } else {
  309. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  310. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method: " + req.Method})
  311. }
  312. })
  313. ////////////////////////////////////////////////////////////////////////////
  314. smux.HandleFunc("/peer/", func(out http.ResponseWriter, req *http.Request) {
  315. defer func() {
  316. e := recover()
  317. if e != nil {
  318. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  319. }
  320. }()
  321. if !apiCheckAuth(out, req, authToken) {
  322. return
  323. }
  324. apiSetStandardHeaders(out)
  325. var queriedID Address
  326. if len(req.URL.Path) > 6 {
  327. var err error
  328. queriedID, err = NewAddressFromString(req.URL.Path[6:])
  329. if err != nil {
  330. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  331. return
  332. }
  333. }
  334. // Right now POST/PUT is only used with peers to add or remove root servers.
  335. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  336. if queriedID == 0 {
  337. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  338. return
  339. }
  340. var peerChanges PeerMutableFields
  341. if apiReadObj(out, req, &peerChanges) == nil {
  342. if peerChanges.Root != nil || peerChanges.Bootstrap != nil {
  343. peers := node.Peers()
  344. for _, p := range peers {
  345. if p.Address == queriedID && (peerChanges.Identity == nil || peerChanges.Identity.Equals(p.Identity)) {
  346. if peerChanges.Root != nil && *peerChanges.Root != p.Root {
  347. if *peerChanges.Root {
  348. _ = node.AddRoot(p.Identity, peerChanges.Bootstrap)
  349. } else {
  350. node.RemoveRoot(p.Identity)
  351. }
  352. }
  353. break
  354. }
  355. }
  356. }
  357. } else {
  358. return
  359. }
  360. }
  361. if req.Method == http.MethodGet || req.Method == http.MethodHead || req.Method == http.MethodPost || req.Method == http.MethodPut {
  362. peers := node.Peers()
  363. if queriedID != 0 {
  364. for _, p := range peers {
  365. if p.Address == queriedID {
  366. _ = apiSendObj(out, req, http.StatusOK, p)
  367. return
  368. }
  369. }
  370. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  371. } else {
  372. _ = apiSendObj(out, req, http.StatusOK, peers)
  373. }
  374. } else {
  375. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  376. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"peers are read only"})
  377. }
  378. })
  379. ////////////////////////////////////////////////////////////////////////////
  380. smux.HandleFunc("/network/", func(out http.ResponseWriter, req *http.Request) {
  381. defer func() {
  382. e := recover()
  383. if e != nil {
  384. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  385. }
  386. }()
  387. if !apiCheckAuth(out, req, authToken) {
  388. return
  389. }
  390. apiSetStandardHeaders(out)
  391. var queriedID NetworkID
  392. if len(req.URL.Path) > 9 {
  393. var err error
  394. queriedID, err = NewNetworkIDFromString(req.URL.Path[9:])
  395. if err != nil {
  396. _ = apiSendObj(out, req, http.StatusNotFound, nil)
  397. return
  398. }
  399. }
  400. if req.Method == http.MethodDelete {
  401. if queriedID == 0 {
  402. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only specific networks can be deleted"})
  403. return
  404. }
  405. networks := node.Networks()
  406. for _, nw := range networks {
  407. if nw.id == queriedID {
  408. _ = node.Leave(queriedID)
  409. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  410. return
  411. }
  412. }
  413. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  414. } else if req.Method == http.MethodPost || req.Method == http.MethodPut {
  415. if queriedID == 0 {
  416. _ = apiSendObj(out, req, http.StatusBadRequest, nil)
  417. return
  418. }
  419. var nw APINetwork
  420. if apiReadObj(out, req, &nw) == nil {
  421. n := node.GetNetwork(nw.ID)
  422. if n == nil {
  423. if nw.ControllerFingerprint != nil && nw.ControllerFingerprint.Address != nw.ID.Controller() {
  424. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"fingerprint's address does not match what should be the controller's address"})
  425. } else {
  426. n, err := node.Join(nw.ID, nw.ControllerFingerprint, nw.Settings, nil)
  427. if err != nil {
  428. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only individual networks can be added or modified with POST/PUT"})
  429. } else {
  430. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  431. }
  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. }