forked from justinrosenthal/apns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
98 lines (79 loc) · 2.1 KB
/
conn.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package apns
import (
"crypto/tls"
"net"
"strings"
"time"
)
const (
ProductionGateway = "gateway.push.apple.com:2195"
SandboxGateway = "gateway.sandbox.push.apple.com:2195"
ProductionFeedbackGateway = "feedback.push.apple.com:2196"
SandboxFeedbackGateway = "feedback.sandbox.push.apple.com:2196"
)
// Conn is a wrapper for the actual TLS connections made to Apple
type Conn struct {
NetConn net.Conn
Conf *tls.Config
gateway string
connected bool
}
func NewConnWithCert(gw string, cert tls.Certificate) Conn {
gatewayParts := strings.Split(gw, ":")
conf := tls.Config{
Certificates: []tls.Certificate{cert},
ServerName: gatewayParts[0],
}
return Conn{gateway: gw, Conf: &conf}
}
// NewConnWithFiles creates a new Conn from certificate and key in the specified files
func NewConn(gw string, crt string, key string) (Conn, error) {
cert, err := tls.X509KeyPair([]byte(crt), []byte(key))
if err != nil {
return Conn{}, err
}
return NewConnWithCert(gw, cert), nil
}
// NewConnWithFiles creates a new Conn from certificate and key in the specified files
func NewConnWithFiles(gw string, certFile string, keyFile string) (Conn, error) {
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return Conn{}, err
}
return NewConnWithCert(gw, cert), nil
}
// Connect actually creates the TLS connection
func (c *Conn) Connect() error {
// Make sure the existing connection is closed
if c.NetConn != nil {
c.NetConn.Close()
}
conn, err := net.Dial("tcp", c.gateway)
if err != nil {
return err
}
conn.(*net.TCPConn).SetKeepAlive(true)
conn.(*net.TCPConn).SetKeepAlivePeriod(30 * time.Second)
tlsConn := tls.Client(conn, c.Conf)
err = tlsConn.Handshake()
if err != nil {
return err
}
c.NetConn = tlsConn
return nil
}
func (c *Conn) Close() error {
if c.NetConn != nil {
return c.NetConn.Close()
}
return nil
}
// Read reads data from the connection
func (c *Conn) Read(p []byte) (int, error) {
i, err := c.NetConn.Read(p)
return i, err
}
// Write writes data from the connection
func (c *Conn) Write(p []byte) (int, error) {
return c.NetConn.Write(p)
}