dissertation-2-code/tcp/flow.go

102 lines
1.9 KiB
Go
Raw Normal View History

package tcp
import (
"encoding/binary"
"errors"
"io"
"mbpl3p/proxy"
"net"
)
var ErrNotEnoughBytes = errors.New("not enough bytes")
type Flow struct {
2020-10-24 17:44:14 +01:00
Local string
Remote string
2020-10-24 17:44:14 +01:00
conn *net.TCPConn
}
2020-10-24 17:44:14 +01:00
func NewFlow(local, remote string) (Flow, error) {
f := Flow{
Local: local,
Remote: remote,
}
2020-10-24 17:44:14 +01:00
if err := f.dial(); err != nil {
return Flow{}, err
}
2020-10-24 17:44:14 +01:00
return f, nil
}
func newFlowConn(conn *net.TCPConn) Flow {
return Flow{conn: conn}
}
func (f *Flow) dial() error {
localAddr, err := net.ResolveTCPAddr("tcp", f.Local)
if err != nil {
2020-10-24 17:44:14 +01:00
return err
}
2020-10-24 17:44:14 +01:00
remoteAddr, err := net.ResolveTCPAddr("tcp", f.Remote)
if err != nil {
return err
}
2020-10-24 17:44:14 +01:00
f.conn, err = net.DialTCP("tcp", localAddr, remoteAddr)
if err != nil {
return err
}
2020-10-24 17:44:14 +01:00
return nil
}
func (f *Flow) IsAlive() bool {
// TODO: Implement this
return true
}
func (f *Flow) Consume(p proxy.Packet, g proxy.MacGenerator) error {
data := p.Marshal(g)
2020-10-24 17:44:14 +01:00
return f.consumeMarshalled(data)
}
2020-10-24 17:44:14 +01:00
func (f *Flow) consumeMarshalled(data []byte) error {
prefixedData := make([]byte, len(data)+4)
binary.LittleEndian.PutUint32(prefixedData, uint32(len(data)))
copy(prefixedData[4:], data)
_, err := f.conn.Write(prefixedData)
return err
}
func (f *Flow) Produce(v proxy.MacVerifier) (proxy.Packet, error) {
2020-10-24 17:44:14 +01:00
data, err := f.produceMarshalled()
if err != nil {
return proxy.Packet{}, err
}
return proxy.UnmarshalPacket(data, v)
}
func (f *Flow) produceMarshalled() ([]byte,error) {
lengthBytes := make([]byte, 4)
if n, err := io.LimitReader(f.conn, 4).Read(lengthBytes); err != nil {
2020-10-24 17:44:14 +01:00
return nil, err
} else if n != 4 {
2020-10-24 17:44:14 +01:00
return nil, ErrNotEnoughBytes
}
length := binary.LittleEndian.Uint32(lengthBytes)
dataBytes := make([]byte, length)
if n, err := io.LimitReader(f.conn, int64(length)).Read(dataBytes); err != nil {
2020-10-24 17:44:14 +01:00
return nil, err
} else if n != int(length) {
2020-10-24 17:44:14 +01:00
return nil, ErrNotEnoughBytes
}
2020-10-24 17:44:14 +01:00
return dataBytes, nil
}