internal/connshark: Add utility to log activity over a net.Conn
This commit is contained in:
parent
c326a2b6b9
commit
da01a0d119
56
internal/connshark/connshark.go
Normal file
56
internal/connshark/connshark.go
Normal 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()
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user