| 735 | } |
| 736 | |
| 737 | func parseTLSConfig(tlsEnabled bool, jsconfig json.RawMessage) (*tls.Config, error) { |
| 738 | type tlsAutocertConfig struct { |
| 739 | // Domains to support by autocert |
| 740 | Domains []string `json:"domains"` |
| 741 | // Name of directory where auto-certificates are cached, e.g. /etc/letsencrypt/live/your-domain-here |
| 742 | CertCache string `json:"cache"` |
| 743 | // Contact email for letsencrypt |
| 744 | Email string `json:"email"` |
| 745 | } |
| 746 | |
| 747 | type tlsConfig struct { |
| 748 | // Flag enabling TLS |
| 749 | Enabled bool `json:"enabled"` |
| 750 | // Listen for connections on this address:port and redirect them to HTTPS port. |
| 751 | RedirectHTTP string `json:"http_redirect"` |
| 752 | // Enable Strict-Transport-Security by setting max_age > 0 |
| 753 | StrictMaxAge int `json:"strict_max_age"` |
| 754 | // ACME autocert config, e.g. letsencrypt.org |
| 755 | Autocert *tlsAutocertConfig `json:"autocert"` |
| 756 | // If Autocert is not defined, provide file names of static certificate and key |
| 757 | CertFile string `json:"cert_file"` |
| 758 | KeyFile string `json:"key_file"` |
| 759 | } |
| 760 | |
| 761 | var config tlsConfig |
| 762 | |
| 763 | if jsconfig != nil { |
| 764 | if err := json.Unmarshal(jsconfig, &config); err != nil { |
| 765 | return nil, errors.New("http: failed to parse tls_config: " + err.Error() + "(" + string(jsconfig) + ")") |
| 766 | } |
| 767 | } |
| 768 | |
| 769 | if !tlsEnabled && !config.Enabled { |
| 770 | return nil, nil |
| 771 | } |
| 772 | |
| 773 | if config.StrictMaxAge > 0 { |
| 774 | globals.tlsStrictMaxAge = strconv.Itoa(config.StrictMaxAge) |
| 775 | } |
| 776 | |
| 777 | globals.tlsRedirectHTTP = config.RedirectHTTP |
| 778 | |
| 779 | // If autocert is provided, use it. |
| 780 | if config.Autocert != nil { |
| 781 | certManager := autocert.Manager{ |
| 782 | Prompt: autocert.AcceptTOS, |
| 783 | HostPolicy: autocert.HostWhitelist(config.Autocert.Domains...), |
| 784 | Cache: autocert.DirCache(config.Autocert.CertCache), |
| 785 | Email: config.Autocert.Email, |
| 786 | } |
| 787 | return certManager.TLSConfig(), nil |
| 788 | } |
| 789 | |
| 790 | // Otherwise try to use static keys. |
| 791 | cert, err := tls.LoadX509KeyPair(config.CertFile, config.KeyFile) |
| 792 | if err != nil { |
| 793 | return nil, err |
| 794 | } |