You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

net_unix.go 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. // This code is heavily inspired by the archived gofacebook/gracenet/net.go handler
  4. //go:build !windows
  5. package graceful
  6. import (
  7. "fmt"
  8. "net"
  9. "os"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "time"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/util"
  17. )
  18. const (
  19. listenFDsEnv = "LISTEN_FDS"
  20. startFD = 3
  21. unlinkFDsEnv = "GITEA_UNLINK_FDS"
  22. notifySocketEnv = "NOTIFY_SOCKET"
  23. watchdogTimeoutEnv = "WATCHDOG_USEC"
  24. )
  25. // In order to keep the working directory the same as when we started we record
  26. // it at startup.
  27. var originalWD, _ = os.Getwd()
  28. var (
  29. once = sync.Once{}
  30. mutex = sync.Mutex{}
  31. providedListenersToUnlink = []bool{}
  32. activeListenersToUnlink = []bool{}
  33. providedListeners = []net.Listener{}
  34. activeListeners = []net.Listener{}
  35. notifySocketAddr string
  36. watchdogTimeout time.Duration
  37. )
  38. func getProvidedFDs() (savedErr error) {
  39. // Only inherit the provided FDS once but we will save the error so that repeated calls to this function will return the same error
  40. once.Do(func() {
  41. mutex.Lock()
  42. defer mutex.Unlock()
  43. // now handle some additional systemd provided things
  44. notifySocketAddr = os.Getenv(notifySocketEnv)
  45. if notifySocketAddr != "" {
  46. log.Debug("Systemd Notify Socket provided: %s", notifySocketAddr)
  47. savedErr = os.Unsetenv(notifySocketEnv)
  48. if savedErr != nil {
  49. log.Warn("Unable to Unset the NOTIFY_SOCKET environment variable: %v", savedErr)
  50. return
  51. }
  52. // FIXME: We don't handle WATCHDOG_PID
  53. timeoutStr := os.Getenv(watchdogTimeoutEnv)
  54. if timeoutStr != "" {
  55. savedErr = os.Unsetenv(watchdogTimeoutEnv)
  56. if savedErr != nil {
  57. log.Warn("Unable to Unset the WATCHDOG_USEC environment variable: %v", savedErr)
  58. return
  59. }
  60. s, err := strconv.ParseInt(timeoutStr, 10, 64)
  61. if err != nil {
  62. log.Error("Unable to parse the provided WATCHDOG_USEC: %v", err)
  63. savedErr = fmt.Errorf("unable to parse the provided WATCHDOG_USEC: %w", err)
  64. return
  65. }
  66. if s <= 0 {
  67. log.Error("Unable to parse the provided WATCHDOG_USEC: %s should be a positive number", timeoutStr)
  68. savedErr = fmt.Errorf("unable to parse the provided WATCHDOG_USEC: %s should be a positive number", timeoutStr)
  69. return
  70. }
  71. watchdogTimeout = time.Duration(s) * time.Microsecond
  72. }
  73. } else {
  74. log.Trace("No Systemd Notify Socket provided")
  75. }
  76. numFDs := os.Getenv(listenFDsEnv)
  77. if numFDs == "" {
  78. return
  79. }
  80. n, err := strconv.Atoi(numFDs)
  81. if err != nil {
  82. savedErr = fmt.Errorf("%s is not a number: %s. Err: %w", listenFDsEnv, numFDs, err)
  83. return
  84. }
  85. fdsToUnlinkStr := strings.Split(os.Getenv(unlinkFDsEnv), ",")
  86. providedListenersToUnlink = make([]bool, n)
  87. for _, fdStr := range fdsToUnlinkStr {
  88. i, err := strconv.Atoi(fdStr)
  89. if err != nil || i < 0 || i >= n {
  90. continue
  91. }
  92. providedListenersToUnlink[i] = true
  93. }
  94. for i := startFD; i < n+startFD; i++ {
  95. file := os.NewFile(uintptr(i), fmt.Sprintf("listener_FD%d", i))
  96. l, err := net.FileListener(file)
  97. if err == nil {
  98. // Close the inherited file if it's a listener
  99. if err = file.Close(); err != nil {
  100. savedErr = fmt.Errorf("error closing provided socket fd %d: %w", i, err)
  101. return
  102. }
  103. providedListeners = append(providedListeners, l)
  104. continue
  105. }
  106. // If needed we can handle packetconns here.
  107. savedErr = fmt.Errorf("Error getting provided socket fd %d: %w", i, err)
  108. return
  109. }
  110. })
  111. return savedErr
  112. }
  113. // CloseProvidedListeners closes all unused provided listeners.
  114. func CloseProvidedListeners() error {
  115. mutex.Lock()
  116. defer mutex.Unlock()
  117. var returnableError error
  118. for _, l := range providedListeners {
  119. err := l.Close()
  120. if err != nil {
  121. log.Error("Error in closing unused provided listener: %v", err)
  122. if returnableError != nil {
  123. returnableError = fmt.Errorf("%v & %w", returnableError, err)
  124. } else {
  125. returnableError = err
  126. }
  127. }
  128. }
  129. providedListeners = []net.Listener{}
  130. return returnableError
  131. }
  132. // GetListener obtains a listener for the local network address. The network must be
  133. // a stream-oriented network: "tcp", "tcp4", "tcp6", "unix" or "unixpacket". It
  134. // returns an provided net.Listener for the matching network and address, or
  135. // creates a new one using net.Listen.
  136. func GetListener(network, address string) (net.Listener, error) {
  137. // Add a deferral to say that we've tried to grab a listener
  138. defer GetManager().InformCleanup()
  139. switch network {
  140. case "tcp", "tcp4", "tcp6":
  141. tcpAddr, err := net.ResolveTCPAddr(network, address)
  142. if err != nil {
  143. return nil, err
  144. }
  145. return GetListenerTCP(network, tcpAddr)
  146. case "unix", "unixpacket":
  147. unixAddr, err := net.ResolveUnixAddr(network, address)
  148. if err != nil {
  149. return nil, err
  150. }
  151. return GetListenerUnix(network, unixAddr)
  152. default:
  153. return nil, net.UnknownNetworkError(network)
  154. }
  155. }
  156. // GetListenerTCP announces on the local network address. The network must be:
  157. // "tcp", "tcp4" or "tcp6". It returns a provided net.Listener for the
  158. // matching network and address, or creates a new one using net.ListenTCP.
  159. func GetListenerTCP(network string, address *net.TCPAddr) (*net.TCPListener, error) {
  160. if err := getProvidedFDs(); err != nil {
  161. return nil, err
  162. }
  163. mutex.Lock()
  164. defer mutex.Unlock()
  165. // look for a provided listener
  166. for i, l := range providedListeners {
  167. if isSameAddr(l.Addr(), address) {
  168. providedListeners = append(providedListeners[:i], providedListeners[i+1:]...)
  169. needsUnlink := providedListenersToUnlink[i]
  170. providedListenersToUnlink = append(providedListenersToUnlink[:i], providedListenersToUnlink[i+1:]...)
  171. activeListeners = append(activeListeners, l)
  172. activeListenersToUnlink = append(activeListenersToUnlink, needsUnlink)
  173. return l.(*net.TCPListener), nil
  174. }
  175. }
  176. // no provided listener for this address -> make a fresh listener
  177. l, err := net.ListenTCP(network, address)
  178. if err != nil {
  179. return nil, err
  180. }
  181. activeListeners = append(activeListeners, l)
  182. activeListenersToUnlink = append(activeListenersToUnlink, false)
  183. return l, nil
  184. }
  185. // GetListenerUnix announces on the local network address. The network must be:
  186. // "unix" or "unixpacket". It returns a provided net.Listener for the
  187. // matching network and address, or creates a new one using net.ListenUnix.
  188. func GetListenerUnix(network string, address *net.UnixAddr) (*net.UnixListener, error) {
  189. if err := getProvidedFDs(); err != nil {
  190. return nil, err
  191. }
  192. mutex.Lock()
  193. defer mutex.Unlock()
  194. // look for a provided listener
  195. for i, l := range providedListeners {
  196. if isSameAddr(l.Addr(), address) {
  197. providedListeners = append(providedListeners[:i], providedListeners[i+1:]...)
  198. needsUnlink := providedListenersToUnlink[i]
  199. providedListenersToUnlink = append(providedListenersToUnlink[:i], providedListenersToUnlink[i+1:]...)
  200. activeListenersToUnlink = append(activeListenersToUnlink, needsUnlink)
  201. activeListeners = append(activeListeners, l)
  202. unixListener := l.(*net.UnixListener)
  203. if needsUnlink {
  204. unixListener.SetUnlinkOnClose(true)
  205. }
  206. return unixListener, nil
  207. }
  208. }
  209. // make a fresh listener
  210. if err := util.Remove(address.Name); err != nil && !os.IsNotExist(err) {
  211. return nil, fmt.Errorf("Failed to remove unix socket %s: %w", address.Name, err)
  212. }
  213. l, err := net.ListenUnix(network, address)
  214. if err != nil {
  215. return nil, err
  216. }
  217. fileMode := os.FileMode(setting.UnixSocketPermission)
  218. if err = os.Chmod(address.Name, fileMode); err != nil {
  219. return nil, fmt.Errorf("Failed to set permission of unix socket to %s: %w", fileMode.String(), err)
  220. }
  221. activeListeners = append(activeListeners, l)
  222. activeListenersToUnlink = append(activeListenersToUnlink, true)
  223. return l, nil
  224. }
  225. func isSameAddr(a1, a2 net.Addr) bool {
  226. // If the addresses are not on the same network fail.
  227. if a1.Network() != a2.Network() {
  228. return false
  229. }
  230. // If the two addresses have the same string representation they're equal
  231. a1s := a1.String()
  232. a2s := a2.String()
  233. if a1s == a2s {
  234. return true
  235. }
  236. // This allows for ipv6 vs ipv4 local addresses to compare as equal. This
  237. // scenario is common when listening on localhost.
  238. const ipv6prefix = "[::]"
  239. a1s = strings.TrimPrefix(a1s, ipv6prefix)
  240. a2s = strings.TrimPrefix(a2s, ipv6prefix)
  241. const ipv4prefix = "0.0.0.0"
  242. a1s = strings.TrimPrefix(a1s, ipv4prefix)
  243. a2s = strings.TrimPrefix(a2s, ipv4prefix)
  244. return a1s == a2s
  245. }
  246. func getActiveListeners() []net.Listener {
  247. mutex.Lock()
  248. defer mutex.Unlock()
  249. listeners := make([]net.Listener, len(activeListeners))
  250. copy(listeners, activeListeners)
  251. return listeners
  252. }
  253. func getActiveListenersToUnlink() []bool {
  254. mutex.Lock()
  255. defer mutex.Unlock()
  256. listenersToUnlink := make([]bool, len(activeListenersToUnlink))
  257. copy(listenersToUnlink, activeListenersToUnlink)
  258. return listenersToUnlink
  259. }
  260. func getNotifySocket() (*net.UnixConn, error) {
  261. if err := getProvidedFDs(); err != nil {
  262. // This error will be logged elsewhere
  263. return nil, nil
  264. }
  265. if notifySocketAddr == "" {
  266. return nil, nil
  267. }
  268. socketAddr := &net.UnixAddr{
  269. Name: notifySocketAddr,
  270. Net: "unixgram",
  271. }
  272. notifySocket, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  273. if err != nil {
  274. log.Warn("failed to dial NOTIFY_SOCKET %s: %v", socketAddr, err)
  275. return nil, err
  276. }
  277. return notifySocket, nil
  278. }
  279. func getWatchdogTimeout() time.Duration {
  280. if err := getProvidedFDs(); err != nil {
  281. // This error will be logged elsewhere
  282. return 0
  283. }
  284. return watchdogTimeout
  285. }