internal/connshark: Add utility to log activity over a net.Conn

This commit is contained in:
Sasha Koshka 2025-10-19 17:48:13 -04:00
parent c326a2b6b9
commit da01a0d119

View File

@ -0,0 +1,56 @@
package connshark
import "os"
import "io"
import "fmt"
import "net"
import "log"
import "sync"
import "math/rand"
import tu "git.tebibyte.media/sashakoshka/hopp/internal/testutil"
type insert struct {
net.Conn
output io.WriteCloser
lock sync.Mutex
}
func LogDebugFile(underlying net.Conn) net.Conn {
file, err := os.Create(fmt.Sprintf("connshark-%08X.log", rand.Uint32()))
if err != nil {
log.Println("XXX COULD NOT OPEN DEBUG FILE! reason: ", err)
return underlying
}
return Log(underlying, file)
}
func Log(underlying net.Conn, output io.WriteCloser) net.Conn {
return &insert {
Conn: underlying,
output: output,
}
}
func (this *insert) Read(buffer []byte) (n int, err error) {
if n > 0 {
this.lock.Lock()
defer this.lock.Unlock()
fmt.Fprintf(this.output, "TX: %s\n", tu.HexBytes(buffer[:n]))
}
return n, err
}
func (this *insert) Write(buffer []byte) (n int, err error) {
n, err = this.Conn.Write(buffer)
if n > 0 {
this.lock.Lock()
defer this.lock.Unlock()
fmt.Fprintf(this.output, "RX: %s\n", tu.HexBytes(buffer[:n]))
}
return n, err
}
func (this *insert) Close() error {
this.output.Close()
return this.Conn.Close()
}