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.

web.go 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package cmd
  5. import (
  6. "fmt"
  7. "net"
  8. "net/http"
  9. "net/http/fcgi"
  10. _ "net/http/pprof" // Used for debugging if enabled and a web server is running
  11. "os"
  12. "strings"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/routers"
  16. "code.gitea.io/gitea/routers/routes"
  17. context2 "github.com/gorilla/context"
  18. "github.com/unknwon/com"
  19. "github.com/urfave/cli"
  20. "golang.org/x/crypto/acme/autocert"
  21. ini "gopkg.in/ini.v1"
  22. )
  23. // CmdWeb represents the available web sub-command.
  24. var CmdWeb = cli.Command{
  25. Name: "web",
  26. Usage: "Start Gitea web server",
  27. Description: `Gitea web server is the only thing you need to run,
  28. and it takes care of all the other things for you`,
  29. Action: runWeb,
  30. Flags: []cli.Flag{
  31. cli.StringFlag{
  32. Name: "port, p",
  33. Value: "3000",
  34. Usage: "Temporary port number to prevent conflict",
  35. },
  36. cli.StringFlag{
  37. Name: "pid, P",
  38. Value: "/var/run/gitea.pid",
  39. Usage: "Custom pid file path",
  40. },
  41. },
  42. }
  43. func runHTTPRedirector() {
  44. source := fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.PortToRedirect)
  45. dest := strings.TrimSuffix(setting.AppURL, "/")
  46. log.Info("Redirecting: %s to %s", source, dest)
  47. handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  48. target := dest + r.URL.Path
  49. if len(r.URL.RawQuery) > 0 {
  50. target += "?" + r.URL.RawQuery
  51. }
  52. http.Redirect(w, r, target, http.StatusTemporaryRedirect)
  53. })
  54. var err = runHTTP(source, context2.ClearHandler(handler))
  55. if err != nil {
  56. log.Fatal("Failed to start port redirection: %v", err)
  57. }
  58. }
  59. func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error {
  60. certManager := autocert.Manager{
  61. Prompt: autocert.AcceptTOS,
  62. HostPolicy: autocert.HostWhitelist(domain),
  63. Cache: autocert.DirCache(directory),
  64. Email: email,
  65. }
  66. go func() {
  67. log.Info("Running Let's Encrypt handler on %s", setting.HTTPAddr+":"+setting.PortToRedirect)
  68. var err = http.ListenAndServe(setting.HTTPAddr+":"+setting.PortToRedirect, certManager.HTTPHandler(http.HandlerFunc(runLetsEncryptFallbackHandler))) // all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validation happens here)
  69. if err != nil {
  70. log.Fatal("Failed to start the Let's Encrypt handler on port %s: %v", setting.PortToRedirect, err)
  71. }
  72. }()
  73. server := &http.Server{
  74. Addr: listenAddr,
  75. Handler: m,
  76. TLSConfig: certManager.TLSConfig(),
  77. }
  78. return server.ListenAndServeTLS("", "")
  79. }
  80. func runLetsEncryptFallbackHandler(w http.ResponseWriter, r *http.Request) {
  81. if r.Method != "GET" && r.Method != "HEAD" {
  82. http.Error(w, "Use HTTPS", http.StatusBadRequest)
  83. return
  84. }
  85. // Remove the trailing slash at the end of setting.AppURL, the request
  86. // URI always contains a leading slash, which would result in a double
  87. // slash
  88. target := strings.TrimRight(setting.AppURL, "/") + r.URL.RequestURI()
  89. http.Redirect(w, r, target, http.StatusFound)
  90. }
  91. func runWeb(ctx *cli.Context) error {
  92. if ctx.IsSet("pid") {
  93. setting.CustomPID = ctx.String("pid")
  94. }
  95. routers.GlobalInit()
  96. m := routes.NewMacaron()
  97. routes.RegisterRoutes(m)
  98. // Flag for port number in case first time run conflict.
  99. if ctx.IsSet("port") {
  100. setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, ctx.String("port"), 1)
  101. setting.HTTPPort = ctx.String("port")
  102. switch setting.Protocol {
  103. case setting.UnixSocket:
  104. case setting.FCGI:
  105. default:
  106. // Save LOCAL_ROOT_URL if port changed
  107. cfg := ini.Empty()
  108. if com.IsFile(setting.CustomConf) {
  109. // Keeps custom settings if there is already something.
  110. if err := cfg.Append(setting.CustomConf); err != nil {
  111. return fmt.Errorf("Failed to load custom conf '%s': %v", setting.CustomConf, err)
  112. }
  113. }
  114. defaultLocalURL := string(setting.Protocol) + "://"
  115. if setting.HTTPAddr == "0.0.0.0" {
  116. defaultLocalURL += "localhost"
  117. } else {
  118. defaultLocalURL += setting.HTTPAddr
  119. }
  120. defaultLocalURL += ":" + setting.HTTPPort + "/"
  121. cfg.Section("server").Key("LOCAL_ROOT_URL").SetValue(defaultLocalURL)
  122. if err := cfg.SaveTo(setting.CustomConf); err != nil {
  123. return fmt.Errorf("Error saving generated JWT Secret to custom config: %v", err)
  124. }
  125. }
  126. }
  127. listenAddr := setting.HTTPAddr
  128. if setting.Protocol != setting.UnixSocket {
  129. listenAddr += ":" + setting.HTTPPort
  130. }
  131. log.Info("Listen: %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
  132. if setting.LFS.StartServer {
  133. log.Info("LFS server enabled")
  134. }
  135. if setting.EnablePprof {
  136. go func() {
  137. log.Info("Starting pprof server on localhost:6060")
  138. log.Info("%v", http.ListenAndServe("localhost:6060", nil))
  139. }()
  140. }
  141. var err error
  142. switch setting.Protocol {
  143. case setting.HTTP:
  144. err = runHTTP(listenAddr, context2.ClearHandler(m))
  145. case setting.HTTPS:
  146. if setting.EnableLetsEncrypt {
  147. err = runLetsEncrypt(listenAddr, setting.Domain, setting.LetsEncryptDirectory, setting.LetsEncryptEmail, context2.ClearHandler(m))
  148. break
  149. }
  150. if setting.RedirectOtherPort {
  151. go runHTTPRedirector()
  152. }
  153. err = runHTTPS(listenAddr, setting.CertFile, setting.KeyFile, context2.ClearHandler(m))
  154. case setting.FCGI:
  155. var listener net.Listener
  156. listener, err = net.Listen("tcp", listenAddr)
  157. if err != nil {
  158. log.Fatal("Failed to bind %s: %v", listenAddr, err)
  159. }
  160. defer func() {
  161. if err := listener.Close(); err != nil {
  162. log.Fatal("Failed to stop server: %v", err)
  163. }
  164. }()
  165. err = fcgi.Serve(listener, context2.ClearHandler(m))
  166. case setting.UnixSocket:
  167. if err := os.Remove(listenAddr); err != nil && !os.IsNotExist(err) {
  168. log.Fatal("Failed to remove unix socket directory %s: %v", listenAddr, err)
  169. }
  170. var listener *net.UnixListener
  171. listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
  172. if err != nil {
  173. break // Handle error after switch
  174. }
  175. // FIXME: add proper implementation of signal capture on all protocols
  176. // execute this on SIGTERM or SIGINT: listener.Close()
  177. if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
  178. log.Fatal("Failed to set permission of unix socket: %v", err)
  179. }
  180. err = http.Serve(listener, context2.ClearHandler(m))
  181. default:
  182. log.Fatal("Invalid protocol: %s", setting.Protocol)
  183. }
  184. if err != nil {
  185. log.Fatal("Failed to start server: %v", err)
  186. }
  187. return nil
  188. }