api.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  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. // createAPIServer creates and starts an HTTP server for a given node
  214. func createAPIServer(basePath string, node *Node) (*http.Server, *http.Server, error) {
  215. // Read authorization token, automatically generating one if it's missing
  216. var authToken string
  217. authTokenFile := path.Join(basePath, "authtoken.secret")
  218. authTokenB, err := ioutil.ReadFile(authTokenFile)
  219. if err != nil {
  220. var atb [20]byte
  221. _, err = secrand.Read(atb[:])
  222. if err != nil {
  223. return nil, nil, err
  224. }
  225. for i := 0; i < 20; i++ {
  226. atb[i] = "abcdefghijklmnopqrstuvwxyz0123456789"[atb[i]%36]
  227. }
  228. err = ioutil.WriteFile(authTokenFile, atb[:], 0600)
  229. if err != nil {
  230. return nil, nil, err
  231. }
  232. _ = acl.Chmod(authTokenFile, 0600)
  233. authToken = string(atb[:])
  234. } else {
  235. authToken = strings.TrimSpace(string(authTokenB))
  236. }
  237. smux := http.NewServeMux()
  238. ////////////////////////////////////////////////////////////////////////////
  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: startTime,
  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. ////////////////////////////////////////////////////////////////////////////
  283. smux.HandleFunc("/config", func(out http.ResponseWriter, req *http.Request) {
  284. defer func() {
  285. e := recover()
  286. if e != nil {
  287. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  288. }
  289. }()
  290. if !apiCheckAuth(out, req, authToken) {
  291. return
  292. }
  293. apiSetStandardHeaders(out)
  294. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  295. var c LocalConfig
  296. if apiReadObj(out, req, &c) == nil {
  297. _, err := node.SetLocalConfig(&c)
  298. if err != nil {
  299. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"error applying local config: " + err.Error()})
  300. } else {
  301. lc := node.LocalConfig()
  302. _ = apiSendObj(out, req, http.StatusOK, &lc)
  303. }
  304. }
  305. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  306. _ = apiSendObj(out, req, http.StatusOK, node.LocalConfig())
  307. } else {
  308. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  309. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method: " + req.Method})
  310. }
  311. })
  312. ////////////////////////////////////////////////////////////////////////////
  313. smux.HandleFunc("/peer/", func(out http.ResponseWriter, req *http.Request) {
  314. defer func() {
  315. e := recover()
  316. if e != nil {
  317. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  318. }
  319. }()
  320. if !apiCheckAuth(out, req, authToken) {
  321. return
  322. }
  323. apiSetStandardHeaders(out)
  324. var queriedID Address
  325. if len(req.URL.Path) > 6 {
  326. var err error
  327. queriedID, err = NewAddressFromString(req.URL.Path[6:])
  328. if err != nil {
  329. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  330. return
  331. }
  332. }
  333. if req.Method == http.MethodPost || req.Method == http.MethodPut {
  334. if queriedID == 0 {
  335. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  336. return
  337. }
  338. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  339. peers := node.Peers()
  340. if queriedID != 0 {
  341. for _, p := range peers {
  342. if p.Address == queriedID {
  343. _ = apiSendObj(out, req, http.StatusOK, p)
  344. return
  345. }
  346. }
  347. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  348. } else {
  349. _ = apiSendObj(out, req, http.StatusOK, peers)
  350. }
  351. } else {
  352. out.Header().Set("Allow", "GET, HEAD, PUT, POST")
  353. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"peers are read only"})
  354. }
  355. })
  356. ////////////////////////////////////////////////////////////////////////////
  357. smux.HandleFunc("/network/", func(out http.ResponseWriter, req *http.Request) {
  358. defer func() {
  359. e := recover()
  360. if e != nil {
  361. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  362. }
  363. }()
  364. if !apiCheckAuth(out, req, authToken) {
  365. return
  366. }
  367. apiSetStandardHeaders(out)
  368. var queriedID NetworkID
  369. if len(req.URL.Path) > 9 {
  370. var err error
  371. queriedID, err = NewNetworkIDFromString(req.URL.Path[9:])
  372. if err != nil {
  373. _ = apiSendObj(out, req, http.StatusNotFound, nil)
  374. return
  375. }
  376. }
  377. if req.Method == http.MethodDelete {
  378. if queriedID == 0 {
  379. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only specific networks can be deleted"})
  380. return
  381. }
  382. networks := node.Networks()
  383. for _, nw := range networks {
  384. if nw.id == queriedID {
  385. _ = node.Leave(queriedID)
  386. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  387. return
  388. }
  389. }
  390. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  391. } else if req.Method == http.MethodPost || req.Method == http.MethodPut {
  392. if queriedID == 0 {
  393. _ = apiSendObj(out, req, http.StatusBadRequest, nil)
  394. return
  395. }
  396. var nw APINetwork
  397. if apiReadObj(out, req, &nw) == nil {
  398. n := node.GetNetwork(nw.ID)
  399. if n == nil {
  400. n, err := node.Join(nw.ID, nw.Settings, nil)
  401. if err != nil {
  402. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only individual networks can be added or modified with POST/PUT"})
  403. } else {
  404. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  405. }
  406. } else {
  407. if nw.Settings != nil {
  408. n.SetLocalSettings(nw.Settings)
  409. }
  410. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  411. }
  412. }
  413. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  414. networks := node.Networks()
  415. if queriedID == 0 { // no queried ID lists all networks
  416. nws := make([]*APINetwork, 0, len(networks))
  417. for _, nw := range networks {
  418. nws = append(nws, apiNetworkFromNetwork(nw))
  419. }
  420. _ = apiSendObj(out, req, http.StatusOK, nws)
  421. return
  422. }
  423. for _, nw := range networks {
  424. if nw.ID() == queriedID {
  425. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  426. return
  427. }
  428. }
  429. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  430. } else {
  431. out.Header().Set("Allow", "GET, HEAD, PUT, POST, DELETE")
  432. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method " + req.Method})
  433. }
  434. })
  435. ////////////////////////////////////////////////////////////////////////////
  436. listener, err := createNamedSocketListener(basePath, APISocketName)
  437. if err != nil {
  438. return nil, nil, err
  439. }
  440. httpServer := &http.Server{
  441. MaxHeaderBytes: 4096,
  442. Handler: smux,
  443. IdleTimeout: 10 * time.Second,
  444. ReadTimeout: 10 * time.Second,
  445. WriteTimeout: 600 * time.Second,
  446. }
  447. httpServer.SetKeepAlivesEnabled(true)
  448. go func() {
  449. _ = httpServer.Serve(listener)
  450. _ = listener.Close()
  451. }()
  452. var tcpHttpServer *http.Server
  453. tcpBindAddr := node.LocalConfig().Settings.APITCPBindAddress
  454. if tcpBindAddr != nil {
  455. tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
  456. IP: tcpBindAddr.IP,
  457. Port: tcpBindAddr.Port,
  458. })
  459. if err != nil {
  460. 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())
  461. } else {
  462. tcpHttpServer = &http.Server{
  463. MaxHeaderBytes: 4096,
  464. Handler: smux,
  465. IdleTimeout: 10 * time.Second,
  466. ReadTimeout: 10 * time.Second,
  467. WriteTimeout: 600 * time.Second,
  468. }
  469. tcpHttpServer.SetKeepAlivesEnabled(true)
  470. go func() {
  471. _ = tcpHttpServer.Serve(tcpListener)
  472. _ = tcpListener.Close()
  473. }()
  474. }
  475. }
  476. return httpServer, tcpHttpServer, nil
  477. }