forked from shanemhansen/gossl
/
ssl.go
81 lines (73 loc) · 1.72 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
package gossl
/*
#include "openssl/ssl.h"
#include "openssl/err.h"
extern int get_errno(void);
*/
import "C"
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)))
C.SSL_set_accept_state(self.SSL)
}
func (self *SSL) SetAcceptState() {
C.SSL_set_accept_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))
return length, self.getError(ret)
}
func (self *SSL) Write(b []byte) (int, error) {
length := len(b)
ret := C.SSL_write(self.SSL, unsafe.Pointer(&b[0]), C.int(length))
return length, self.getError(ret)
}
func (self *SSL) getError(ret C.int) error {
err := C.SSL_get_error(self.SSL, ret)
switch err {
case C.SSL_ERROR_NONE:
case C.SSL_ERROR_ZERO_RETURN:
return nil
case C.SSL_ERROR_SYSCALL:
if int(C.ERR_peek_error()) != 0 {
return syscall.Errno(C.get_errno())
}
default:
msg := sslerr.SSLErrorMessage()
return errors.New(msg)
}
return nil
}