Remove channel binding logic

This commit is contained in:
Zoltán Papp
2024-05-23 13:24:02 +02:00
parent 0a05f8b4d4
commit 36b2cd16cc
11 changed files with 229 additions and 374 deletions

View File

@ -1,7 +1,6 @@
package client
import (
"context"
"fmt"
"io"
"net"
@ -19,25 +18,21 @@ const (
serverResponseTimeout = 8 * time.Second
)
type bufMsg struct {
bufPtr *[]byte
buf []byte
type Msg struct {
buf []byte
}
type connContainer struct {
conn *Conn
messages chan bufMsg
messages chan Msg
}
// Client Todo:
// - handle automatic reconnection
type Client struct {
log *log.Entry
serverAddress string
peerID string
hashedID []byte
channelsPending map[string]chan net.Conn // todo: protect map with mutex
channels map[uint16]*connContainer
msgPool sync.Pool
conns map[string]*connContainer
relayConn net.Conn
relayConnState bool
@ -45,17 +40,12 @@ type Client struct {
}
func NewClient(serverAddress, peerID string) *Client {
hashedID, hashedStringId := messages.HashID(peerID)
return &Client{
serverAddress: serverAddress,
peerID: peerID,
channelsPending: make(map[string]chan net.Conn),
channels: make(map[uint16]*connContainer),
msgPool: sync.Pool{
New: func() any {
buf := make([]byte, bufferSize)
return &buf
},
},
log: log.WithField("client_id", hashedStringId),
serverAddress: serverAddress,
hashedID: hashedID,
conns: make(map[string]*connContainer),
}
}
@ -89,31 +79,17 @@ func (c *Client) Connect() error {
return nil
}
func (c *Client) BindChannel(remotePeerID string) (net.Conn, error) {
c.mu.Lock()
defer c.mu.Unlock()
func (c *Client) OpenConn(dstPeerID string) (net.Conn, error) {
hashedID, hashedStringID := messages.HashID(dstPeerID)
log.Infof("open connection to peer: %s", hashedStringID)
messageBuffer := make(chan Msg, 2)
conn := NewConn(c, hashedID, c.generateConnReaderFN(messageBuffer))
if c.relayConn == nil {
return nil, fmt.Errorf("client not connected to the relay server")
}
bindSuccessChan := make(chan net.Conn, 1)
c.channelsPending[remotePeerID] = bindSuccessChan
msg := messages.MarshalBindNewChannelMsg(remotePeerID)
_, err := c.relayConn.Write(msg)
if err != nil {
log.Errorf("failed to write out bind message: %s", err)
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), serverResponseTimeout)
defer cancel()
select {
case <-ctx.Done():
return nil, fmt.Errorf("bind timeout")
case c := <-bindSuccessChan:
return c, nil
c.conns[hashedStringID] = &connContainer{
conn,
messageBuffer,
}
return conn, nil
}
func (c *Client) Close() error {
@ -124,18 +100,15 @@ func (c *Client) Close() error {
return nil
}
for _, conn := range c.channels {
close(conn.messages)
}
c.channels = make(map[uint16]*connContainer)
c.relayConnState = false
err := c.relayConn.Close()
return err
}
func (c *Client) handShake() error {
msg, err := messages.MarshalHelloMsg(c.peerID)
msg, err := messages.MarshalHelloMsg(c.hashedID)
if err != nil {
log.Errorf("failed to marshal hello message: %s", err)
return err
}
_, err = c.relayConn.Write(msg)
@ -171,85 +144,56 @@ func (c *Client) handShake() error {
}
func (c *Client) readLoop() {
log := log.WithField("client_id", c.peerID)
defer func() {
c.log.Debugf("exit from read loop")
}()
var errExit error
var n int
for {
bufPtr := c.msgPool.Get().(*[]byte)
buf := *bufPtr
buf := make([]byte, bufferSize)
n, errExit = c.relayConn.Read(buf)
if errExit != nil {
log.Debugf("failed to read message from relay server: %s", errExit)
c.freeBuf(bufPtr)
if c.relayConnState {
c.log.Debugf("failed to read message from relay server: %s", errExit)
}
break
}
msgType, err := messages.DetermineServerMsgType(buf[:n])
if err != nil {
log.Errorf("failed to determine message type: %s", err)
c.freeBuf(bufPtr)
c.log.Errorf("failed to determine message type: %s", err)
continue
}
switch msgType {
case messages.MsgTypeBindResponse:
channelId, peerId, err := messages.UnmarshalBindResponseMsg(buf[:n])
if err != nil {
log.Errorf("failed to parse bind response message: %v", err)
} else {
c.handleBindResponse(channelId, peerId)
}
c.freeBuf(bufPtr)
continue
case messages.MsgTypeTransport:
channelId, err := messages.UnmarshalTransportID(buf[:n])
peerID, err := messages.UnmarshalTransportID(buf[:n])
if err != nil {
log.Errorf("failed to parse transport message: %v", err)
c.freeBuf(bufPtr)
c.log.Errorf("failed to parse transport message: %v", err)
continue
}
container, ok := c.channels[channelId]
stringID := messages.HashIDToString(peerID)
container, ok := c.conns[stringID]
if !ok {
log.Errorf("unexpected transport message for channel: %d", channelId)
c.freeBuf(bufPtr)
return
c.log.Errorf("peer not found: %s", stringID)
continue
}
container.messages <- bufMsg{
bufPtr,
container.messages <- Msg{
buf[:n],
}
}
}
if c.relayConnState {
log.Errorf("failed to read message from relay server: %s", errExit)
c.log.Errorf("failed to read message from relay server: %s", errExit)
_ = c.relayConn.Close()
}
}
func (c *Client) handleBindResponse(channelId uint16, peerId string) {
bindSuccessChan, ok := c.channelsPending[peerId]
if !ok {
log.Errorf("unexpected bind response from: %s", peerId)
return
}
delete(c.channelsPending, peerId)
messageBuffer := make(chan bufMsg, 2)
conn := NewConn(c, channelId, c.generateConnReaderFN(messageBuffer))
c.channels[channelId] = &connContainer{
conn,
messageBuffer,
}
log.Debugf("bind success for '%s': %d", peerId, channelId)
bindSuccessChan <- conn
}
func (c *Client) writeTo(channelID uint16, payload []byte) (int, error) {
msg := messages.MarshalTransportMsg(channelID, payload)
func (c *Client) writeTo(dstID []byte, payload []byte) (int, error) {
msg := messages.MarshalTransportMsg(dstID, payload)
n, err := c.relayConn.Write(msg)
if err != nil {
log.Errorf("failed to write transport message: %s", err)
@ -257,26 +201,19 @@ func (c *Client) writeTo(channelID uint16, payload []byte) (int, error) {
return n, err
}
func (c *Client) generateConnReaderFN(messageBufferChan chan bufMsg) func(b []byte) (n int, err error) {
func (c *Client) generateConnReaderFN(msgChannel chan Msg) func(b []byte) (n int, err error) {
return func(b []byte) (n int, err error) {
select {
case bufMsg, ok := <-messageBufferChan:
if !ok {
return 0, io.EOF
}
payload, err := messages.UnmarshalTransportPayload(bufMsg.buf)
if err != nil {
return 0, err
}
n = copy(b, payload)
c.freeBuf(bufMsg.bufPtr)
msg, ok := <-msgChannel
if !ok {
return 0, io.EOF
}
payload, err := messages.UnmarshalTransportPayload(msg.buf)
if err != nil {
return 0, err
}
n = copy(b, payload)
return n, nil
}
}
func (c *Client) freeBuf(ptr *[]byte) {
c.msgPool.Put(ptr)
}