gitea源码

net_unix.go 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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() {
  115. mutex.Lock()
  116. defer mutex.Unlock()
  117. for _, l := range providedListeners {
  118. err := l.Close()
  119. if err != nil {
  120. log.Error("Error in closing unused provided listener: %v", err)
  121. }
  122. }
  123. providedListeners = []net.Listener{}
  124. }
  125. // DefaultGetListener obtains a listener for the stream-oriented local network address:
  126. // "tcp", "tcp4", "tcp6", "unix" or "unixpacket".
  127. func DefaultGetListener(network, address string) (net.Listener, error) {
  128. // Add a deferral to say that we've tried to grab a listener
  129. defer GetManager().InformCleanup()
  130. switch network {
  131. case "tcp", "tcp4", "tcp6":
  132. tcpAddr, err := net.ResolveTCPAddr(network, address)
  133. if err != nil {
  134. return nil, err
  135. }
  136. return GetListenerTCP(network, tcpAddr)
  137. case "unix", "unixpacket":
  138. unixAddr, err := net.ResolveUnixAddr(network, address)
  139. if err != nil {
  140. return nil, err
  141. }
  142. return GetListenerUnix(network, unixAddr)
  143. default:
  144. return nil, net.UnknownNetworkError(network)
  145. }
  146. }
  147. // GetListenerTCP announces on the local network address. The network must be:
  148. // "tcp", "tcp4" or "tcp6". It returns a provided net.Listener for the
  149. // matching network and address, or creates a new one using net.ListenTCP.
  150. func GetListenerTCP(network string, address *net.TCPAddr) (*net.TCPListener, error) {
  151. if err := getProvidedFDs(); err != nil {
  152. return nil, err
  153. }
  154. mutex.Lock()
  155. defer mutex.Unlock()
  156. // look for a provided listener
  157. for i, l := range providedListeners {
  158. if isSameAddr(l.Addr(), address) {
  159. providedListeners = append(providedListeners[:i], providedListeners[i+1:]...)
  160. needsUnlink := providedListenersToUnlink[i]
  161. providedListenersToUnlink = append(providedListenersToUnlink[:i], providedListenersToUnlink[i+1:]...)
  162. activeListeners = append(activeListeners, l)
  163. activeListenersToUnlink = append(activeListenersToUnlink, needsUnlink)
  164. return l.(*net.TCPListener), nil
  165. }
  166. }
  167. // no provided listener for this address -> make a fresh listener
  168. l, err := net.ListenTCP(network, address)
  169. if err != nil {
  170. return nil, err
  171. }
  172. activeListeners = append(activeListeners, l)
  173. activeListenersToUnlink = append(activeListenersToUnlink, false)
  174. return l, nil
  175. }
  176. // GetListenerUnix announces on the local network address. The network must be:
  177. // "unix" or "unixpacket". It returns a provided net.Listener for the
  178. // matching network and address, or creates a new one using net.ListenUnix.
  179. func GetListenerUnix(network string, address *net.UnixAddr) (*net.UnixListener, error) {
  180. if err := getProvidedFDs(); err != nil {
  181. return nil, err
  182. }
  183. mutex.Lock()
  184. defer mutex.Unlock()
  185. // look for a provided listener
  186. for i, l := range providedListeners {
  187. if isSameAddr(l.Addr(), address) {
  188. providedListeners = append(providedListeners[:i], providedListeners[i+1:]...)
  189. needsUnlink := providedListenersToUnlink[i]
  190. providedListenersToUnlink = append(providedListenersToUnlink[:i], providedListenersToUnlink[i+1:]...)
  191. activeListenersToUnlink = append(activeListenersToUnlink, needsUnlink)
  192. activeListeners = append(activeListeners, l)
  193. unixListener := l.(*net.UnixListener)
  194. if needsUnlink {
  195. unixListener.SetUnlinkOnClose(true)
  196. }
  197. return unixListener, nil
  198. }
  199. }
  200. // make a fresh listener
  201. if err := util.Remove(address.Name); err != nil && !os.IsNotExist(err) {
  202. return nil, fmt.Errorf("Failed to remove unix socket %s: %w", address.Name, err)
  203. }
  204. l, err := net.ListenUnix(network, address)
  205. if err != nil {
  206. return nil, err
  207. }
  208. fileMode := os.FileMode(setting.UnixSocketPermission)
  209. if err = os.Chmod(address.Name, fileMode); err != nil {
  210. return nil, fmt.Errorf("Failed to set permission of unix socket to %s: %w", fileMode.String(), err)
  211. }
  212. activeListeners = append(activeListeners, l)
  213. activeListenersToUnlink = append(activeListenersToUnlink, true)
  214. return l, nil
  215. }
  216. func isSameAddr(a1, a2 net.Addr) bool {
  217. // If the addresses are not on the same network fail.
  218. if a1.Network() != a2.Network() {
  219. return false
  220. }
  221. // If the two addresses have the same string representation they're equal
  222. a1s := a1.String()
  223. a2s := a2.String()
  224. if a1s == a2s {
  225. return true
  226. }
  227. // This allows for ipv6 vs ipv4 local addresses to compare as equal. This
  228. // scenario is common when listening on localhost.
  229. const ipv6prefix = "[::]"
  230. a1s = strings.TrimPrefix(a1s, ipv6prefix)
  231. a2s = strings.TrimPrefix(a2s, ipv6prefix)
  232. const ipv4prefix = "0.0.0.0"
  233. a1s = strings.TrimPrefix(a1s, ipv4prefix)
  234. a2s = strings.TrimPrefix(a2s, ipv4prefix)
  235. return a1s == a2s
  236. }
  237. func getActiveListeners() []net.Listener {
  238. mutex.Lock()
  239. defer mutex.Unlock()
  240. listeners := make([]net.Listener, len(activeListeners))
  241. copy(listeners, activeListeners)
  242. return listeners
  243. }
  244. func getActiveListenersToUnlink() []bool {
  245. mutex.Lock()
  246. defer mutex.Unlock()
  247. listenersToUnlink := make([]bool, len(activeListenersToUnlink))
  248. copy(listenersToUnlink, activeListenersToUnlink)
  249. return listenersToUnlink
  250. }
  251. func getNotifySocket() (*net.UnixConn, error) {
  252. if err := getProvidedFDs(); err != nil {
  253. // This error will be logged elsewhere
  254. return nil, nil
  255. }
  256. if notifySocketAddr == "" {
  257. return nil, nil
  258. }
  259. socketAddr := &net.UnixAddr{
  260. Name: notifySocketAddr,
  261. Net: "unixgram",
  262. }
  263. notifySocket, err := net.DialUnix(socketAddr.Net, nil, socketAddr)
  264. if err != nil {
  265. log.Warn("failed to dial NOTIFY_SOCKET %s: %v", socketAddr, err)
  266. return nil, err
  267. }
  268. return notifySocket, nil
  269. }
  270. func getWatchdogTimeout() time.Duration {
  271. if err := getProvidedFDs(); err != nil {
  272. // This error will be logged elsewhere
  273. return 0
  274. }
  275. return watchdogTimeout
  276. }