afl-transmit/net/peer.go

71 lines
1.6 KiB
Go
Raw Normal View History

2020-06-19 13:31:20 +00:00
package net
import (
2020-06-20 17:07:58 +00:00
"fmt"
2021-04-20 08:28:03 +00:00
"github.com/maride/afl-transmit/stats"
2020-06-19 13:31:20 +00:00
"log"
"net"
2020-06-20 17:07:58 +00:00
"regexp"
"strings"
)
var (
portSuffixRegex = regexp.MustCompile(":\\d{0,5}$")
2020-06-19 13:31:20 +00:00
)
type Peer struct {
Address string
}
2020-06-20 17:07:58 +00:00
// Creates a peer from the given address
func CreatePeer(address string) Peer {
// Clean line
address = strings.TrimSpace(address)
// Check if a port is already part of the address
// This is the lazy way: if a IPv6 literal is given without square brackets and without a port, this will fail badly.
if !portSuffixRegex.MatchString(address) {
// Port number is not yet part of the address, so append the default port number
address = fmt.Sprintf("%s:%d", address, ServerPort)
}
// Return constructed Peer
return Peer{
Address: address,
}
}
2020-06-19 13:31:20 +00:00
// Sends the given content to the peer
func (p *Peer) SendToPeer(content []byte) {
2021-04-23 14:17:44 +00:00
// Encrypt content if desired
if CryptApplicable() {
// Encrypt packet
var encryptErr error
content, encryptErr = Encrypt(content)
if encryptErr != nil {
log.Printf("Failed to decrypt packet from %s: %s", p.Address, encryptErr)
return
}
}
2020-06-19 13:31:20 +00:00
// Build up a connection
tcpConn, dialErr := net.Dial("tcp", p.Address)
if dialErr != nil {
log.Printf("Unable to connect to peer %s: %s", p.Address, dialErr)
return
}
// Send
2021-04-20 08:28:03 +00:00
written, writeErr := tcpConn.Write(content)
2020-06-19 13:31:20 +00:00
if writeErr != nil {
log.Printf("Unable to write to peer %s: %s", tcpConn.RemoteAddr().String(), writeErr)
return
}
2021-04-20 08:28:03 +00:00
// Push written bytes to stats
stats.PushStat(stats.Stat{SentBytes: uint64(written)})
2020-06-19 13:31:20 +00:00
// Close connection
tcpConn.Close()
}