-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
64 lines (52 loc) · 1.3 KB
/
connection.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
// Copyright 2016 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package miniv
// #cgo CFLAGS: -I/usr/include/nacl -std=c99
// #include "miniv.h"
import "C"
import (
"log"
"os"
"unsafe"
)
type connection struct {
c1, c2 C.struct_connection
}
func ConnectionPair() *connection {
c := &connection{}
p1r, p1w, _ := os.Pipe()
p2r, p2w, _ := os.Pipe()
C.connectionNew(&c.c1)
c.c1.rfd = C.int(p1r.Fd())
c.c1.wfd = C.int(p2w.Fd())
// c2 is the "server" who will write to c1
C.connectionNew(&c.c2)
c.c2.rfd = C.int(p2r.Fd())
c.c2.wfd = C.int(p1w.Fd())
return c
}
func (c *connection) handshakeAndReceive() ([]byte, error) {
go func() {
// start c2
err := C.connectionHandshake(&c.c2)
if err != C.ERR_OK {
log.Fatal("c2 handshake:", GoError(err))
}
// send some data towards c1
hello := []byte("hello from c2")
err = C.connectionWriteFrame(&c.c2, toBuf_t(hello))
if err != C.ERR_OK {
log.Fatal("c2 write:", GoError(err))
}
}()
err := C.connectionHandshake(&c.c1)
if err != C.ERR_OK {
return nil, GoError(err)
}
err = C.connectionReadFrame(&c.c1)
if err != C.ERR_OK {
return nil, GoError(err)
}
return C.GoBytes(unsafe.Pointer(c.c1.frame.buf), C.int(c.c1.frame.len)), nil
}