forked from spacemonkeygo/openssl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bio.go
355 lines (310 loc) · 7.35 KB
/
bio.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
// Copyright (C) 2014 Space Monkey, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build cgo
package openssl
/*
#include <string.h>
#include <openssl/bio.h>
extern int cbioNew(BIO *b);
static int cbioFree(BIO *b) {
return 1;
}
extern int writeBioWrite(BIO *b, char *buf, int size);
extern long writeBioCtrl(BIO *b, int cmd, long arg1, void *arg2);
static int writeBioPuts(BIO *b, const char *str) {
return writeBioWrite(b, (char*)str, (int)strlen(str));
}
extern int readBioRead(BIO *b, char *buf, int size);
extern long readBioCtrl(BIO *b, int cmd, long arg1, void *arg2);
static BIO_METHOD writeBioMethod = {
BIO_TYPE_SOURCE_SINK,
"Go Write BIO",
(int (*)(BIO *, const char *, int))writeBioWrite,
NULL,
writeBioPuts,
NULL,
writeBioCtrl,
cbioNew,
cbioFree,
NULL};
static BIO_METHOD* BIO_s_writeBio() { return &writeBioMethod; }
static BIO_METHOD readBioMethod = {
BIO_TYPE_SOURCE_SINK,
"Go Read BIO",
NULL,
readBioRead,
NULL,
NULL,
readBioCtrl,
cbioNew,
cbioFree,
NULL};
static BIO_METHOD* BIO_s_readBio() { return &readBioMethod; }
*/
import "C"
import (
"errors"
"io"
"reflect"
"sync"
"unsafe"
)
const (
SSLRecordSize = 16 * 1024
)
func nonCopyGoBytes(ptr uintptr, length int) []byte {
var slice []byte
header := (*reflect.SliceHeader)(unsafe.Pointer(&slice))
header.Cap = length
header.Len = length
header.Data = ptr
return slice
}
func nonCopyCString(data *C.char, size C.int) []byte {
return nonCopyGoBytes(uintptr(unsafe.Pointer(data)), int(size))
}
//export cbioNew
func cbioNew(b *C.BIO) C.int {
b.shutdown = 1
b.init = 1
b.num = -1
b.ptr = nil
b.flags = 0
return 1
}
type writeBio struct {
data_mtx sync.Mutex
op_mtx sync.Mutex
buf []byte
release_buffers bool
}
func loadWritePtr(b *C.BIO) *writeBio {
return (*writeBio)(unsafe.Pointer(b.ptr))
}
func bioClearRetryFlags(b *C.BIO) {
// from BIO_clear_retry_flags and BIO_clear_flags
b.flags &= ^(C.BIO_FLAGS_RWS | C.BIO_FLAGS_SHOULD_RETRY)
}
func bioSetRetryRead(b *C.BIO) {
// from BIO_set_retry_read and BIO_set_flags
b.flags |= (C.BIO_FLAGS_READ | C.BIO_FLAGS_SHOULD_RETRY)
}
//export writeBioWrite
func writeBioWrite(b *C.BIO, data *C.char, size C.int) (rc C.int) {
defer func() {
if err := recover(); err != nil {
logger.Critf("openssl: writeBioWrite panic'd: %v", err)
rc = -1
}
}()
ptr := loadWritePtr(b)
if ptr == nil || data == nil || size < 0 {
return -1
}
ptr.data_mtx.Lock()
defer ptr.data_mtx.Unlock()
bioClearRetryFlags(b)
ptr.buf = append(ptr.buf, nonCopyCString(data, size)...)
return size
}
//export writeBioCtrl
func writeBioCtrl(b *C.BIO, cmd C.int, arg1 C.long, arg2 unsafe.Pointer) (
rc C.long) {
defer func() {
if err := recover(); err != nil {
logger.Critf("openssl: writeBioCtrl panic'd: %v", err)
rc = -1
}
}()
switch cmd {
case C.BIO_CTRL_WPENDING:
return writeBioPending(b)
case C.BIO_CTRL_DUP, C.BIO_CTRL_FLUSH:
return 1
default:
return 0
}
}
func writeBioPending(b *C.BIO) C.long {
ptr := loadWritePtr(b)
if ptr == nil {
return 0
}
ptr.data_mtx.Lock()
defer ptr.data_mtx.Unlock()
return C.long(len(ptr.buf))
}
func (b *writeBio) WriteTo(w io.Writer) (rv int64, err error) {
b.op_mtx.Lock()
defer b.op_mtx.Unlock()
// write whatever data we currently have
b.data_mtx.Lock()
data := b.buf
b.data_mtx.Unlock()
if len(data) == 0 {
return 0, nil
}
n, err := w.Write(data)
// subtract however much data we wrote from the buffer
b.data_mtx.Lock()
b.buf = b.buf[:copy(b.buf, b.buf[n:])]
if b.release_buffers && len(b.buf) == 0 {
b.buf = nil
}
b.data_mtx.Unlock()
return int64(n), err
}
func (self *writeBio) Disconnect(b *C.BIO) {
if loadWritePtr(b) == self {
b.ptr = nil
}
}
func (b *writeBio) MakeCBIO() *C.BIO {
rv := C.BIO_new(C.BIO_s_writeBio())
rv.ptr = unsafe.Pointer(b)
return rv
}
type readBio struct {
data_mtx sync.Mutex
op_mtx sync.Mutex
buf []byte
eof bool
release_buffers bool
}
func loadReadPtr(b *C.BIO) *readBio {
return (*readBio)(unsafe.Pointer(b.ptr))
}
//export readBioRead
func readBioRead(b *C.BIO, data *C.char, size C.int) (rc C.int) {
defer func() {
if err := recover(); err != nil {
logger.Critf("openssl: readBioRead panic'd: %v", err)
rc = -1
}
}()
ptr := loadReadPtr(b)
if ptr == nil || size < 0 {
return -1
}
ptr.data_mtx.Lock()
defer ptr.data_mtx.Unlock()
bioClearRetryFlags(b)
if len(ptr.buf) == 0 {
if ptr.eof {
return 0
}
bioSetRetryRead(b)
return -1
}
if size == 0 || data == nil {
return C.int(len(ptr.buf))
}
n := copy(nonCopyCString(data, size), ptr.buf)
ptr.buf = ptr.buf[:copy(ptr.buf, ptr.buf[n:])]
if ptr.release_buffers && len(ptr.buf) == 0 {
ptr.buf = nil
}
return C.int(n)
}
//export readBioCtrl
func readBioCtrl(b *C.BIO, cmd C.int, arg1 C.long, arg2 unsafe.Pointer) (
rc C.long) {
defer func() {
if err := recover(); err != nil {
logger.Critf("openssl: readBioCtrl panic'd: %v", err)
rc = -1
}
}()
switch cmd {
case C.BIO_CTRL_PENDING:
return readBioPending(b)
case C.BIO_CTRL_DUP, C.BIO_CTRL_FLUSH:
return 1
default:
return 0
}
}
func readBioPending(b *C.BIO) C.long {
ptr := loadReadPtr(b)
if ptr == nil {
return 0
}
ptr.data_mtx.Lock()
defer ptr.data_mtx.Unlock()
return C.long(len(ptr.buf))
}
func (b *readBio) ReadFromOnce(r io.Reader) (n int, err error) {
b.op_mtx.Lock()
defer b.op_mtx.Unlock()
// make sure we have a destination that fits at least one SSL record
b.data_mtx.Lock()
if cap(b.buf) < len(b.buf)+SSLRecordSize {
new_buf := make([]byte, len(b.buf), len(b.buf)+SSLRecordSize)
copy(new_buf, b.buf)
b.buf = new_buf
}
dst := b.buf[len(b.buf):cap(b.buf)]
dst_slice := b.buf
b.data_mtx.Unlock()
n, err = r.Read(dst)
b.data_mtx.Lock()
defer b.data_mtx.Unlock()
if n > 0 {
if len(dst_slice) != len(b.buf) {
// someone shrunk the buffer, so we read in too far ahead and we
// need to slide backwards
copy(b.buf[len(b.buf):len(b.buf)+n], dst)
}
b.buf = b.buf[:len(b.buf)+n]
}
return n, err
}
func (b *readBio) MakeCBIO() *C.BIO {
rv := C.BIO_new(C.BIO_s_readBio())
rv.ptr = unsafe.Pointer(b)
return rv
}
func (self *readBio) Disconnect(b *C.BIO) {
if loadReadPtr(b) == self {
b.ptr = nil
}
}
func (b *readBio) MarkEOF() {
b.data_mtx.Lock()
defer b.data_mtx.Unlock()
b.eof = true
}
type anyBio C.BIO
func asAnyBio(b *C.BIO) *anyBio { return (*anyBio)(b) }
func (b *anyBio) Read(buf []byte) (n int, err error) {
if len(buf) == 0 {
return 0, nil
}
n = int(C.BIO_read((*C.BIO)(b), unsafe.Pointer(&buf[0]), C.int(len(buf))))
if n <= 0 {
return 0, io.EOF
}
return n, nil
}
func (b *anyBio) Write(buf []byte) (written int, err error) {
if len(buf) == 0 {
return 0, nil
}
n := int(C.BIO_write((*C.BIO)(b), unsafe.Pointer(&buf[0]),
C.int(len(buf))))
if n != len(buf) {
return n, errors.New("BIO write failed")
}
return n, nil
}