Move decode logic into separate function

This commit is contained in:
Jan Philipp Timme 2019-11-23 20:23:05 +01:00
parent 41b78f0b58
commit 2b4dfdc56d
1 changed files with 44 additions and 28 deletions

48
main.go
View File

@ -14,37 +14,53 @@ var (
logger logging.Logger logger logging.Logger
) )
func handleMtaConnection(clientConnection *bufio.ReadWriter) { type milterPacket struct {
payloadLength uint32
message string
payload []byte
}
type smficOptineg struct {
version uint32
actions uint32
protocol uint32
}
func readRequestPacket(clientConnection *bufio.ReadWriter) (milterPacket, error) {
buf := make([]byte, 4096) buf := make([]byte, 4096)
for {
bytesRead, err := clientConnection.Read(buf) bytesRead, err := clientConnection.Read(buf)
if err != nil { if err != nil {
logger.Errorln("Error reading from clientConnection:", err.Error()) logger.Errorln("Error reading from clientConnection:", err.Error())
break return milterPacket{}, err
} else { }
logger.Infof("Read %d bytes from connection\n", bytesRead) logger.Infof("Read %d bytes from connection\n", bytesRead)
logger.Debugf("Hexdump of bytes read:\n%s", hex.Dump(buf[0:bytesRead])) logger.Debugf("Hexdump of bytes read:\n%s", hex.Dump(buf[0:bytesRead]))
reqPacket := milterPacket{}
// First 4 Bytes will be some integer thing "length" // First 4 Bytes will be some integer thing "length"
// Let's parse that
var packetLength uint32
bytesReader := bytes.NewReader(buf[0:4]) bytesReader := bytes.NewReader(buf[0:4])
err := binary.Read(bytesReader, binary.BigEndian, &packetLength) err = binary.Read(bytesReader, binary.BigEndian, &reqPacket.payloadLength)
if err != nil { if err != nil {
logger.Errorln(err.Error()) logger.Errorln(err.Error())
} }
logger.Debugf("Parsed length: %d\n", packetLength) logger.Debugf("Parsed length: %d\n", reqPacket.payloadLength)
// Next up is a character, indicating the milter command // Next up is a character, indicating the milter command
logger.Debugf("Parsing command from byte: %X\n", buf[4]) logger.Debugf("Parsing command from byte: %X\n", buf[4])
command := string(buf[4]) reqPacket.message = string(buf[4])
logger.Debugf("Parsed packet command: %s\n", command) logger.Debugf("Parsed packet command: %s\n", reqPacket.message)
// Last part is data with lenght len-1 // Last part is data with lenght len-1
data := make([]byte, packetLength) reqPacket.payload = buf[5 : 5+reqPacket.payloadLength-1]
data = buf[5 : 5+packetLength-1] logger.Debugf("Hexdump of packet payload read:\n%s", hex.Dump(reqPacket.payload))
logger.Debugf("Hexdump of packet payload read:\n%s", hex.Dump(data)) // That's it, we're done.
return reqPacket, nil
}
func handleMtaConnection(clientConnection *bufio.ReadWriter) {
for {
request, _ := readRequestPacket(clientConnection)
if request.message == "O" {
responsePayload := smficOptineg{2, 0, 2}
//clientConnection.Write()
} }
} }
} }