-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.go
85 lines (76 loc) · 2.05 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
package xlistener
import (
"bytes"
"crypto/md5"
"encoding/binary"
"errors"
"fmt"
"io"
"math/rand"
"net"
"time"
"github.com/sandwich-go/xlistener/internal/dh64"
)
var _ net.Conn = &xConn{}
type Dialer func() (net.Conn, error)
type xConn struct {
net.Conn
connID uint64
secretKey [8]byte
}
func newXConn(conn net.Conn, connId uint64) (*xConn, error) {
c := &xConn{
Conn: conn,
connID: connId,
}
return c, nil
}
func (x *xConn) handshake(serverAddr []byte, handshakeTimeout time.Duration) (err error) {
if handshakeTimeout > 0 {
_ = x.Conn.SetDeadline(time.Now().Add(handshakeTimeout))
defer func() { _ = x.Conn.SetDeadline(time.Time{}) }()
}
var (
addressLen = 1 + len(serverAddr)
buf = make([]byte, addressLen+24)
addressField = buf[0:addressLen]
publicKeyField = buf[addressLen : addressLen+8]
connIdField = buf[addressLen+8 : addressLen+16]
randField = buf[addressLen+16 : addressLen+24]
)
// read client public secret
if _, err = io.ReadFull(x.Conn, publicKeyField); err != nil {
return
}
clientPubKey := binary.LittleEndian.Uint64(publicKeyField)
if clientPubKey == 0 {
err = errors.New("client public key is zero")
return
}
serverPriKey, serverPubKey := dh64.KeyPair()
secret := dh64.Secret(serverPriKey, clientPubKey)
binary.LittleEndian.PutUint64(x.secretKey[:], secret)
addressField[0] = byte(addressLen - 1)
copy(addressField[1:], serverAddr)
binary.LittleEndian.PutUint64(publicKeyField, serverPubKey)
binary.LittleEndian.PutUint64(connIdField, x.connID)
_, _ = rand.Read(randField)
if _, err = x.Conn.Write(buf[:]); err != nil {
err = errors.New("send handshake response failed: " + err.Error())
return
}
var buf2 [16]byte
if _, err = io.ReadFull(x.Conn, buf2[:]); err != nil {
err = errors.New("read twice handshake failed: " + err.Error())
return
}
hash := md5.New()
hash.Write(randField)
hash.Write(x.secretKey[:])
md5sum := hash.Sum(nil)
if !bytes.Equal(buf2[:], md5sum) {
err = fmt.Errorf("twice handshake not equals: %x, %x", buf2[:], md5sum)
return
}
return
}