-
Notifications
You must be signed in to change notification settings - Fork 11
/
log_tcp.go
87 lines (72 loc) · 1.63 KB
/
log_tcp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package freki
import (
"encoding/hex"
"fmt"
"net"
"time"
"github.com/pkg/errors"
)
var readDeadline = time.Second * 5
type TCPLogger struct {
port uint
readSize uint
processor *Processor
listener net.Listener
}
func NewTCPLogger(port uint, readSize uint) *TCPLogger {
return &TCPLogger{
port: port,
readSize: readSize,
}
}
func (h *TCPLogger) Port() uint {
return h.port
}
func (h *TCPLogger) Type() string {
return "log.tcp"
}
func (h *TCPLogger) Start(p *Processor) error {
h.processor = p
var err error
// TODO: can I be more specific with the bind addr?
h.listener, err = net.Listen("tcp", fmt.Sprintf(":%d", h.port))
if err != nil {
return err
}
for {
conn, err := h.listener.Accept()
if err != nil {
logger.Error(errors.Wrap(err, h.Type()))
continue
}
go func(conn net.Conn) {
defer func() {
err := conn.Close()
if err != nil {
logger.Error(errors.Wrap(err, h.Type()))
}
}()
conn.SetReadDeadline(time.Now().Add(readDeadline))
host, port, _ := net.SplitHostPort(conn.RemoteAddr().String())
ck := NewConnKeyByString(host, port)
md := h.processor.Connections.GetByFlow(ck)
if md == nil {
logger.Warnf("[log.tcp ] untracked connection: %s", conn.RemoteAddr().String())
return
}
buffer := make([]byte, h.readSize)
n, _ := conn.Read(buffer)
if n > 0 {
logger.Infof("[log.tcp ] %s -> %s\n%s", host, md.TargetPort, hex.Dump(buffer[0:n]))
} else {
logger.Infof("[log.tcp ] %s -> %s", host, md.TargetPort)
}
}(conn)
}
}
func (h *TCPLogger) Shutdown() error {
if h.listener != nil {
return h.listener.Close()
}
return nil
}