api.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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: 2025-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/base64"
  18. "encoding/json"
  19. "fmt"
  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:"localInterfaceAddresses,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: node.startupTime,
  261. Config: node.LocalConfig(),
  262. Online: node.Online(),
  263. PeerCount: len(peers),
  264. PathCount: pathCount,
  265. Identity: node.Identity(),
  266. InterfaceAddresses: node.LocalInterfaceAddresses(),
  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. var err error
  316. defer func() {
  317. e := recover()
  318. if e != nil {
  319. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  320. }
  321. }()
  322. if !apiCheckAuth(out, req, authToken) {
  323. return
  324. }
  325. apiSetStandardHeaders(out)
  326. var queriedStr string
  327. var queriedID Address
  328. var queriedFP *Fingerprint
  329. if len(req.URL.Path) > 6 {
  330. queriedStr = req.URL.Path[6:]
  331. if len(queriedStr) == AddressStringLength {
  332. queriedID, err = NewAddressFromString(queriedStr)
  333. if err != nil {
  334. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  335. return
  336. }
  337. } else {
  338. queriedFP, err = NewFingerprintFromString(queriedStr)
  339. if err != nil {
  340. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  341. return
  342. }
  343. }
  344. }
  345. var peer *Peer
  346. peers := node.Peers()
  347. if queriedFP != nil {
  348. for _, p := range peers {
  349. if p.Fingerprint.Equals(queriedFP) {
  350. peer = p
  351. break
  352. }
  353. }
  354. } else if queriedID != 0 {
  355. for _, p := range peers {
  356. if p.Address == queriedID {
  357. peer = p
  358. break
  359. }
  360. }
  361. }
  362. if req.Method == http.MethodGet || req.Method == http.MethodHead || req.Method == http.MethodPost || req.Method == http.MethodPut {
  363. if peer != nil {
  364. _ = apiSendObj(out, req, http.StatusOK, peer)
  365. } else if len(queriedStr) > 0 {
  366. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"peer not found"})
  367. } else {
  368. _ = apiSendObj(out, req, http.StatusOK, peers)
  369. }
  370. } else {
  371. out.Header().Set("Allow", "GET, HEAD")
  372. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method"})
  373. }
  374. })
  375. // -----------------------------------------------------------------------------------------------------------------
  376. smux.HandleFunc("/network/", func(out http.ResponseWriter, req *http.Request) {
  377. defer func() {
  378. e := recover()
  379. if e != nil {
  380. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"caught unexpected error in request handler"})
  381. }
  382. }()
  383. if !apiCheckAuth(out, req, authToken) {
  384. return
  385. }
  386. apiSetStandardHeaders(out)
  387. var queriedID NetworkID
  388. if len(req.URL.Path) > 9 {
  389. var err error
  390. queriedID, err = NewNetworkIDFromString(req.URL.Path[9:])
  391. if err != nil {
  392. _ = apiSendObj(out, req, http.StatusNotFound, nil)
  393. return
  394. }
  395. }
  396. if req.Method == http.MethodDelete {
  397. if queriedID == 0 {
  398. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only specific networks can be deleted"})
  399. return
  400. }
  401. networks := node.Networks()
  402. for _, nw := range networks {
  403. if nw.id == queriedID {
  404. _ = node.Leave(queriedID)
  405. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  406. return
  407. }
  408. }
  409. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  410. } else if req.Method == http.MethodPost || req.Method == http.MethodPut {
  411. if queriedID == 0 {
  412. _ = apiSendObj(out, req, http.StatusBadRequest, nil)
  413. return
  414. }
  415. var nw APINetwork
  416. if apiReadObj(out, req, &nw) == nil {
  417. n := node.Network(nw.ID)
  418. if n == nil {
  419. if nw.ControllerFingerprint != nil && nw.ControllerFingerprint.Address != nw.ID.Controller() {
  420. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"fingerprint's address does not match what should be the controller's address"})
  421. } else {
  422. n, err := node.Join(nw.ID, nw.ControllerFingerprint, nw.Settings, nil)
  423. if err != nil {
  424. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"only individual networks can be added or modified with POST/PUT"})
  425. } else {
  426. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  427. }
  428. }
  429. } else {
  430. if nw.Settings != nil {
  431. n.SetLocalSettings(nw.Settings)
  432. }
  433. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(n))
  434. }
  435. }
  436. } else if req.Method == http.MethodGet || req.Method == http.MethodHead {
  437. networks := node.Networks()
  438. if queriedID == 0 { // no queried ID lists all networks
  439. nws := make([]*APINetwork, 0, len(networks))
  440. for _, nw := range networks {
  441. nws = append(nws, apiNetworkFromNetwork(nw))
  442. }
  443. _ = apiSendObj(out, req, http.StatusOK, nws)
  444. return
  445. }
  446. for _, nw := range networks {
  447. if nw.ID() == queriedID {
  448. _ = apiSendObj(out, req, http.StatusOK, apiNetworkFromNetwork(nw))
  449. return
  450. }
  451. }
  452. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"network not found"})
  453. } else {
  454. out.Header().Set("Allow", "GET, HEAD, PUT, POST, DELETE")
  455. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method " + req.Method})
  456. }
  457. })
  458. // -----------------------------------------------------------------------------------------------------------------
  459. smux.HandleFunc("/cert/", func(out http.ResponseWriter, req *http.Request) {
  460. defer func() {
  461. e := recover()
  462. if e != nil {
  463. _ = apiSendObj(out, req, http.StatusInternalServerError, nil)
  464. }
  465. }()
  466. if !apiCheckAuth(out, req, authToken) {
  467. return
  468. }
  469. apiSetStandardHeaders(out)
  470. var queriedSerialNo []byte
  471. if len(req.URL.Path) > 6 {
  472. b, err := base64.URLEncoding.DecodeString(req.URL.Path[6:])
  473. if err != nil || len(b) != CertificateSerialNoSize {
  474. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"invalid base64 serial number in certificate path"})
  475. return
  476. }
  477. queriedSerialNo = b
  478. }
  479. if req.Method == http.MethodGet || req.Method == http.MethodHead {
  480. certs, err := node.ListCertificates()
  481. if err != nil {
  482. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"unexpected error listing certificates"})
  483. return
  484. }
  485. if len(queriedSerialNo) == CertificateSerialNoSize {
  486. for _, c := range certs {
  487. if bytes.Equal(c.Certificate.SerialNo, queriedSerialNo) {
  488. _ = apiSendObj(out, req, http.StatusOK, c)
  489. break
  490. }
  491. }
  492. } else {
  493. _ = apiSendObj(out, req, http.StatusOK, certs)
  494. }
  495. } else if req.Method == http.MethodPost || req.Method == http.MethodPut {
  496. var lc LocalCertificate
  497. if apiReadObj(out, req, &lc) == nil {
  498. if lc.Certificate == nil {
  499. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"missing certificate"})
  500. return
  501. }
  502. }
  503. if len(queriedSerialNo) == CertificateSerialNoSize && !bytes.Equal(queriedSerialNo, lc.Certificate.SerialNo) {
  504. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"certificate serial does not match serial in path"})
  505. return
  506. }
  507. err := node.AddCertificate(lc.Certificate, lc.LocalTrust)
  508. if err == nil {
  509. _ = apiSendObj(out, req, http.StatusOK, lc)
  510. } else {
  511. _ = apiSendObj(out, req, http.StatusBadRequest, &APIErr{"certificate rejected: " + err.Error()})
  512. }
  513. } else if req.Method == http.MethodDelete {
  514. if len(queriedSerialNo) == CertificateSerialNoSize {
  515. certs, err := node.ListCertificates()
  516. if err != nil {
  517. _ = apiSendObj(out, req, http.StatusInternalServerError, &APIErr{"unexpected error"})
  518. return
  519. }
  520. for _, c := range certs {
  521. if bytes.Equal(c.Certificate.SerialNo, queriedSerialNo) {
  522. _ = node.DeleteCertificate(queriedSerialNo)
  523. _ = apiSendObj(out, req, http.StatusOK, c)
  524. return
  525. }
  526. }
  527. }
  528. _ = apiSendObj(out, req, http.StatusNotFound, &APIErr{"certificate not found"})
  529. } else {
  530. out.Header().Set("Allow", "GET, HEAD, PUT, POST, DELETE")
  531. _ = apiSendObj(out, req, http.StatusMethodNotAllowed, &APIErr{"unsupported method " + req.Method})
  532. }
  533. })
  534. // -----------------------------------------------------------------------------------------------------------------
  535. listener, err := createNamedSocketListener(basePath, APISocketName)
  536. if err != nil {
  537. return nil, nil, err
  538. }
  539. httpServer := &http.Server{
  540. MaxHeaderBytes: 4096,
  541. Handler: smux,
  542. IdleTimeout: 10 * time.Second,
  543. ReadTimeout: 10 * time.Second,
  544. WriteTimeout: 600 * time.Second,
  545. }
  546. httpServer.SetKeepAlivesEnabled(true)
  547. go func() {
  548. _ = httpServer.Serve(listener)
  549. _ = listener.Close()
  550. }()
  551. var tcpHttpServer *http.Server
  552. tcpBindAddr := node.LocalConfig().Settings.APITCPBindAddress
  553. if tcpBindAddr != nil {
  554. tcpListener, err := net.ListenTCP("tcp", &net.TCPAddr{
  555. IP: tcpBindAddr.IP,
  556. Port: tcpBindAddr.Port,
  557. })
  558. if err != nil {
  559. 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())
  560. } else {
  561. tcpHttpServer = &http.Server{
  562. MaxHeaderBytes: 4096,
  563. Handler: smux,
  564. IdleTimeout: 10 * time.Second,
  565. ReadTimeout: 10 * time.Second,
  566. WriteTimeout: 600 * time.Second,
  567. }
  568. tcpHttpServer.SetKeepAlivesEnabled(true)
  569. go func() {
  570. _ = tcpHttpServer.Serve(tcpListener)
  571. _ = tcpListener.Close()
  572. }()
  573. }
  574. }
  575. return httpServer, tcpHttpServer, nil
  576. }