]> Sergey Matveev's repositories - godlighty.git/blob - tls.go
Built-in MIMEs compression capability
[godlighty.git] / tls.go
1 /*
2 godlighty -- highly-customizable HTTP, HTTP/2, HTTPS server
3 Copyright (C) 2021 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package godlighty
19
20 import (
21         "crypto/tls"
22         "encoding/pem"
23         "errors"
24         "fmt"
25         "io/ioutil"
26         "log"
27 )
28
29 var HostToCertificate map[string]*tls.Certificate
30
31 func GetCertificate(chi *tls.ClientHelloInfo) (*tls.Certificate, error) {
32         cert := HostToCertificate[chi.ServerName]
33         if cert == nil {
34                 return nil, errors.New("no certificate found")
35         }
36         return cert, nil
37 }
38
39 func LoadCertificates() {
40         HostToCertificate = make(map[string]*tls.Certificate, len(Hosts))
41         for host, cfg := range Hosts {
42                 if cfg.TLS == nil {
43                         continue
44                 }
45                 cert, err := tls.LoadX509KeyPair(cfg.TLS.Cert, cfg.TLS.Key)
46                 if err != nil {
47                         log.Fatalln(err)
48                 }
49                 if cfg.TLS.CACert != "" {
50                         data, err := ioutil.ReadFile(cfg.TLS.CACert)
51                         if err != nil {
52                                 log.Fatalln(err)
53                         }
54                         block, _ := pem.Decode(data)
55                         if block == nil {
56                                 log.Fatalln(fmt.Errorf("no PEM found: %s", cfg.TLS.CACert))
57                         }
58                         if block.Type != "CERTIFICATE" {
59                                 log.Fatalln(fmt.Errorf("non CERTIFICATE: %s", cfg.TLS.CACert))
60                         }
61                         cert.Certificate = append(cert.Certificate, block.Bytes)
62                 }
63                 HostToCertificate[host] = &cert
64         }
65 }