-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtls_feature.go
69 lines (57 loc) · 1.57 KB
/
tls_feature.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package xmppcore
import (
"crypto/tls"
"github.com/jackal-xmpp/stravaganza/v2"
)
type tlsFeature struct {
certFile string
keyFile string
mandatory bool
handled bool
IDAble
}
func TlsFailureElem() stravaganza.Element {
return stravaganza.NewBuilder("failure").WithAttribute("xmlns", NSTls).Build()
}
const (
NSTls = "urn:ietf:params:xml:ns:xmpp-tls"
)
func TlsFeature(certFile, keyFile string, mandatory bool) tlsFeature {
return tlsFeature{
certFile: certFile,
keyFile: keyFile,
mandatory: mandatory,
handled: false,
IDAble: CreateIDAble()}
}
func (tf tlsFeature) Elem() stravaganza.Element {
elem := stravaganza.NewBuilder("starttls").
WithAttribute("xmlns", NSTls)
elem.WithChild(stravaganza.NewBuilder("required").Build())
return elem.Build()
}
func (tf tlsFeature) Mandatory() bool {
return true
}
func (tf tlsFeature) Match(elem stravaganza.Element) bool {
return elem.Name() == "starttls" && elem.Attribute("xmlns") == NSTls
}
func (tf *tlsFeature) Handle(elem stravaganza.Element, part Part) (catched bool, err error) {
if !tf.Match(elem) {
return false, nil
}
tf.handled = true
cert, err := tls.LoadX509KeyPair(tf.certFile, tf.keyFile)
if err != nil {
part.Channel().SendElement(TlsFailureElem())
part.Logger().Printf(LogError, "create tls cert error: %s\n", err.Error())
return
}
msg := stravaganza.NewBuilder("proceed").WithAttribute("xmlns", NSTls).Build()
part.Channel().SendElement(msg)
part.Conn().StartTLS(&tls.Config{Certificates: []tls.Certificate{cert}})
return
}
func (tf tlsFeature) Handled() bool {
return tf.handled
}