diff options
author | Fluf <36822577+flufmonster@users.noreply.github.com> | 2018-08-21 09:56:50 -0400 |
---|---|---|
committer | techknowlogick <techknowlogick@users.noreply.github.com> | 2018-08-21 09:56:50 -0400 |
commit | b82c14b3d2259912b47fa292b85772ba1d2493d0 (patch) | |
tree | e4cca15b19a1549961543779f9a11c9127e7475c /cmd/web.go | |
parent | 6c1a31ffaaddf8ced7c30bf5b1e6e82d66f8c6ee (diff) | |
download | gitea-b82c14b3d2259912b47fa292b85772ba1d2493d0.tar.gz gitea-b82c14b3d2259912b47fa292b85772ba1d2493d0.zip |
add letsencrypt to Gitea (#4189)
Diffstat (limited to 'cmd/web.go')
-rw-r--r-- | cmd/web.go | 33 |
1 files changed, 33 insertions, 0 deletions
diff --git a/cmd/web.go b/cmd/web.go index bc3cee69e5..4991721211 100644 --- a/cmd/web.go +++ b/cmd/web.go @@ -5,6 +5,7 @@ package cmd import ( + "crypto/tls" "fmt" "net" "net/http" @@ -22,6 +23,7 @@ import ( "github.com/Unknwon/com" context2 "github.com/gorilla/context" "github.com/urfave/cli" + "golang.org/x/crypto/acme/autocert" ini "gopkg.in/ini.v1" ) @@ -71,6 +73,33 @@ func runHTTPRedirector() { } } +func runLetsEncrypt(listenAddr, domain, directory, email string, m http.Handler) error { + certManager := autocert.Manager{ + Prompt: autocert.AcceptTOS, + HostPolicy: autocert.HostWhitelist(domain), + Cache: autocert.DirCache(directory), + Email: email, + } + go http.ListenAndServe(listenAddr+":"+setting.PortToRedirect, certManager.HTTPHandler(http.HandlerFunc(runLetsEncryptFallbackHandler))) // all traffic coming into HTTP will be redirect to HTTPS automatically (LE HTTP-01 validatio happens here) + server := &http.Server{ + Addr: listenAddr, + Handler: m, + TLSConfig: &tls.Config{ + GetCertificate: certManager.GetCertificate, + }, + } + return server.ListenAndServeTLS("", "") +} + +func runLetsEncryptFallbackHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != "GET" && r.Method != "HEAD" { + http.Error(w, "Use HTTPS", http.StatusBadRequest) + return + } + target := setting.AppURL + r.URL.RequestURI() + http.Redirect(w, r, target, http.StatusFound) +} + func runWeb(ctx *cli.Context) error { if ctx.IsSet("config") { setting.CustomConf = ctx.String("config") @@ -143,6 +172,10 @@ func runWeb(ctx *cli.Context) error { case setting.HTTP: err = runHTTP(listenAddr, context2.ClearHandler(m)) case setting.HTTPS: + if setting.EnableLetsEncrypt { + err = runLetsEncrypt(listenAddr, setting.Domain, setting.LetsEncryptDirectory, setting.LetsEncryptEmail, context2.ClearHandler(m)) + break + } if setting.RedirectOtherPort { go runHTTPRedirector() } |