-
Notifications
You must be signed in to change notification settings - Fork 5
/
ssl.go
101 lines (91 loc) · 2.02 KB
/
ssl.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
99
100
101
package gossl
/*
#include "openssl/ssl.h"
#include "openssl/err.h"
static int get_errno(void)
{
return errno;
}
*/
import "C"
import "io"
import "unsafe"
import "syscall"
import "github.com/shanemhansen/gossl/sslerr"
import "errors"
type SSL struct {
SSL *C.SSL
}
func NewSSL(context *Context) *SSL {
ssl := &SSL{C.SSL_new(context.Ctx)}
return ssl
}
func (self *SSL) Free() {
C.SSL_free(self.SSL)
}
func (self *SSL) SetBIO(readbio *BIO, writebio *BIO) {
C.SSL_set_bio(self.SSL,
(*C.BIO)(unsafe.Pointer(readbio.BIO)),
(*C.BIO)(unsafe.Pointer(writebio.BIO)))
}
func (self *SSL) SetAcceptState() {
C.SSL_set_accept_state(self.SSL)
}
func (self *SSL) SetConnectState() {
C.SSL_set_connect_state(self.SSL)
}
func (self *SSL) Shutdown() error {
//shutdown should happen in 2 steps
//see http://www.openssl.org/docs/ssl/SSL_shutdown.html
defer self.Free()
ret := C.SSL_shutdown(self.SSL)
if int(ret) == 0 {
ret = C.SSL_shutdown(self.SSL)
if int(ret) != 1 {
return self.getError(ret)
}
}
return nil
}
func (self *SSL) Handshake() error {
ret := C.SSL_do_handshake(self.SSL)
return self.getError(ret)
}
func (self *SSL) Read(b []byte) (int, error) {
length := len(b)
ret := C.SSL_read(self.SSL, unsafe.Pointer(&b[0]), C.int(length))
if err := self.getError(ret); err != nil {
return 0, err
}
// if there's no error, but a return value of 0
// let's say it's an EOF
if ret == 0 {
return 0, io.EOF
}
return int(ret), nil
}
func (self *SSL) Write(b []byte) (int, error) {
length := len(b)
ret := C.SSL_write(self.SSL, unsafe.Pointer(&b[0]), C.int(length))
if err := self.getError(ret); err != nil {
return 0, err
}
return int(ret), nil
}
func (self *SSL) getError(ret C.int) error {
err := C.SSL_get_error(self.SSL, ret)
switch err {
case C.SSL_ERROR_NONE:
return nil
case C.SSL_ERROR_ZERO_RETURN:
return io.EOF
case C.SSL_ERROR_SYSCALL:
if int(C.ERR_peek_error()) != 0 {
return syscall.Errno(C.get_errno())
}
default:
msg := sslerr.SSLErrorMessage().String()
return errors.New(msg)
}
return nil
}