api.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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"
  20. "io/ioutil"
  21. "net"
  22. "net/http"
  23. "path"
  24. "runtime"
  25. "strconv"
  26. "strings"
  27. "time"
  28. "github.com/hectane/go-acl"
  29. )
  30. // APISocketName is the default socket name for accessing the API
  31. const APISocketName = "apisocket"
  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. smux.HandleFunc("/status", func(out http.ResponseWriter, req *http.Request) {
  240. defer func() {
  241. e := recover()
  242. if e != nil {
  243. _ = apiSendObj(out, req, http.StatusInternalServerError, nil)
  244. }
  245. }()
  246. if !apiCheckAuth(out, req, authToken) {
  247. return
  248. }
  249. apiSetStandardHeaders(out)
  250. if req.Method == http.MethodGet || req.Method == http.MethodHead {
  251. pathCount := 0
  252. peers := node.Peers()
  253. for _, p := range peers {
  254. pathCount += len(p.Paths)
  255. }
  256. _ = apiSendObj(out, req, http.StatusOK, &APIStatus{
  257. Address: node.Address(),
  258. Clock: TimeMs(),
  259. StartupTime: node.startupTime,
  260. Config: node.LocalConfig(),
  261. Online: node.Online(),
  262. PeerCount: len(peers),
  263. PathCount: pathCount,
  264. Identity: node.Identity(),
  265. InterfaceAddresses: node.InterfaceAddresses(),
  266. MappedExternalAddresses: nil,
  267. Version: fmt.Sprintf("%d.%d.%d", CoreVersionMajor, CoreVersionMinor, CoreVersionRevision),
  268. VersionMajor: CoreVersionMajor,
  269. VersionMinor: CoreVersionMinor,
  270. VersionRevision: CoreVersionRevision,
  271. VersionBuild: CoreVersionBuild,
  272. OS: runtime.GOOS,
  273. Architecture: runtime.GOARCH,
  274. Concurrency: runtime.NumCPU(),
  275. Runtime: runtime.Version(),
  276. })
  277. } else {
  278. out.Header().Set("Allow", "GET, HEAD")
  279. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"/status is read-only"})
  280. }
  281. })
  282. smux.HandleFunc("/config", func(out http.ResponseWriter, req *http.Request) {
  283. defer func() {
  284. e := recover()
  285. if e != nil {
  286. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  287. }
  288. }()
  289. if !apiCheckAuth(out, req, authToken) {
  290. return
  291. }
  292. apiSetStandardHeaders(out)
  293. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  294. var c LocalConfig
  295. if apiReadObj(out, req, &c) == nil {
  296. _, err := node.SetLocalConfig(&c)
  297. if err != nil {
  298. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"error applying local config: " + err.Error()})
  299. } else {
  300. lc := node.LocalConfig()
  301. _ = apiSendObj(out, req, http.StatusOK, &lc)
  302. }
  303. }
  304. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  305. _ = apiSendObj(out, req, http.StatusOK, node.LocalConfig())
  306. } else {
  307. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  308. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method: " + req.Method})
  309. }
  310. })
  311. smux.HandleFunc("/peer/", func(out http.ResponseWriter, req *http.Request) {
  312. var err error
  313. defer func() {
  314. e := recover()
  315. if e != nil {
  316. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  317. }
  318. }()
  319. if !apiCheckAuth(out, req, authToken) {
  320. return
  321. }
  322. apiSetStandardHeaders(out)
  323. if req.URL.Path == "/peer/_addroot" {
  324. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  325. rsdata, err := ioutil.ReadAll(io.LimitReader(req.Body, 16384))
  326. if err != nil || len(rsdata) == 0 {
  327. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"read error"})
  328. } else {
  329. // TODO
  330. _ = apiSendObj(out, req, http.StatusOK, nil)
  331. }
  332. } else {
  333. out.Header().Set("Allow", "POST, PUT")
  334. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"no root spec supplied"})
  335. }
  336. return
  337. }
  338. var queriedStr string
  339. var queriedID Address
  340. var queriedFP *Fingerprint
  341. if len(req.URL.Path) > 6 {
  342. queriedStr = req.URL.Path[6:]
  343. if len(queriedStr) == AddressStringLength {
  344. queriedID, err = NewAddressFromString(queriedStr)
  345. if err != nil {
  346. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  347. return
  348. }
  349. } else {
  350. queriedFP, err = NewFingerprintFromString(queriedStr)
  351. if err != nil {
  352. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  353. return
  354. }
  355. }
  356. }
  357. var peer *Peer
  358. peers := node.Peers()
  359. if queriedFP != nil {
  360. for _, p := range peers {
  361. if p.Fingerprint.Equals(queriedFP) {
  362. peer = p
  363. break
  364. }
  365. }
  366. } else if queriedID != 0 {
  367. for _, p := range peers {
  368. if p.Address == queriedID {
  369. peer = p
  370. break
  371. }
  372. }
  373. }
  374. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  375. if peer != nil {
  376. var posted Peer
  377. if apiReadObj(out, req, &posted) == nil {
  378. if posted.Root && !peer.Root {
  379. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"root spec must be submitted to /peer/_addroot, post to peers can only be used to clear the root flag"})
  380. } else if !posted.Root && peer.Root {
  381. peer.Root = false
  382. node.RemoveRoot(peer.Address)
  383. _ = apiSendObj(out, req, http.StatusOK, peer)
  384. }
  385. }
  386. } else {
  387. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  388. }
  389. } else if req.Method == http.MethodGet || req.Method == http.MethodHead || req.Method == http.MethodPost || req.Method == http.MethodPut {
  390. if peer != nil {
  391. _ = apiSendObj(out, req, http.StatusOK, peer)
  392. } else if len(queriedStr) > 0 {
  393. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  394. } else {
  395. _ = apiSendObj(out, req, http.StatusOK, peers)
  396. }
  397. } else {
  398. out.Header().Set("Allow", "GET, HEAD, POST, PUT")
  399. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method"})
  400. }
  401. })
  402. smux.HandleFunc("/network/", func(out http.ResponseWriter, req *http.Request) {
  403. defer func() {
  404. e := recover()
  405. if e != nil {
  406. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  407. }
  408. }()
  409. if !apiCheckAuth(out, req, authToken) {
  410. return
  411. }
  412. apiSetStandardHeaders(out)
  413. var queriedID NetworkID
  414. if len(req.URL.Path) > 9 {
  415. var err error
  416. queriedID, err = NewNetworkIDFromString(req.URL.Path[9:])
  417. if err != nil {
  418. _ = apiSendObj(out, req, http.StatusNotFound, nil)
  419. return
  420. }
  421. }
  422. if req.Method == http.MethodDelete {
  423. if queriedID == 0 {
  424. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only specific networks can be deleted"})
  425. return
  426. }
  427. networks := node.Networks()
  428. for _, nw := range networks {
  429. if nw.id == queriedID {
  430. _ = node.Leave(queriedID)
  431. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  432. return
  433. }
  434. }
  435. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  436. } else if req.Method == http.MethodPost || req.Method == http.MethodPut {
  437. if queriedID == 0 {
  438. _ = apiSendObj(out, req, http.StatusBadRequest, nil)
  439. return
  440. }
  441. var nw APINetwork
  442. if apiReadObj(out, req, &nw) == nil {
  443. n := node.GetNetwork(nw.ID)
  444. if n == nil {
  445. if nw.ControllerFingerprint != nil && nw.ControllerFingerprint.Address != nw.ID.Controller() {
  446. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"fingerprint's address does not match what should be the controller's address"})
  447. } else {
  448. n, err := node.Join(nw.ID, nw.ControllerFingerprint, nw.Settings, nil)
  449. if err != nil {
  450. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only individual networks can be added or modified with POST/PUT"})
  451. } else {
  452. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  453. }
  454. }
  455. } else {
  456. if nw.Settings != nil {
  457. n.SetLocalSettings(nw.Settings)
  458. }
  459. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  460. }
  461. }
  462. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  463. networks := node.Networks()
  464. if queriedID == 0 { // no queried ID lists all networks
  465. nws := make([]*APINetwork, 0, len(networks))
  466. for _, nw := range networks {
  467. nws = append(nws, apiNetworkFromNetwork(nw))
  468. }
  469. _ = apiSendObj(out, req, http.StatusOK, nws)
  470. return
  471. }
  472. for _, nw := range networks {
  473. if nw.ID() == queriedID {
  474. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  475. return
  476. }
  477. }
  478. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  479. } else {
  480. out.Header().Set("Allow", "GET, HEAD, PUT, POST, DELETE")
  481. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method " + req.Method})
  482. }
  483. })
  484. listener, err := createNamedSocketListener(basePath, APISocketName)
  485. if err != nil {
  486. return nil, nil, err
  487. }
  488. httpServer := &http.Server{
  489. MaxHeaderBytes: 4096,
  490. Handler: smux,
  491. IdleTimeout: 10 * time.Second,
  492. ReadTimeout: 10 * time.Second,
  493. WriteTimeout: 600 * time.Second,
  494. }
  495. httpServer.SetKeepAlivesEnabled(true)
  496. go func() {
  497. _ = httpServer.Serve(listener)
  498. _ = listener.Close()
  499. }()
  500. var tcpHttpServer *http.Server
  501. tcpBindAddr := node.LocalConfig().Settings.APITCPBindAddress
  502. if tcpBindAddr != nil {
  503. tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
  504. IP: tcpBindAddr.IP,
  505. Port: tcpBindAddr.Port,
  506. })
  507. if err != nil {
  508. 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())
  509. } else {
  510. tcpHttpServer = &http.Server{
  511. MaxHeaderBytes: 4096,
  512. Handler: smux,
  513. IdleTimeout: 10 * time.Second,
  514. ReadTimeout: 10 * time.Second,
  515. WriteTimeout: 600 * time.Second,
  516. }
  517. tcpHttpServer.SetKeepAlivesEnabled(true)
  518. go func() {
  519. _ = tcpHttpServer.Serve(tcpListener)
  520. _ = tcpListener.Close()
  521. }()
  522. }
  523. }
  524. return httpServer, tcpHttpServer, nil
  525. }