-
Notifications
You must be signed in to change notification settings - Fork 0
/
pgcap.go
118 lines (80 loc) · 2.34 KB
/
pgcap.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package main
import (
"bytes"
"flag"
"fmt"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"log"
"time"
)
var (
device = flag.String("device", "lo", "")
BPFFilter = flag.String("bpf_filter", "tcp and port 5432", "")
queryFilter = flag.String("query_filter", "", "not case-sensitive")
slowQueryTime = flag.Int64("slow_query_time", 0, "in milliseconds")
maxQueryLen = flag.Int("max_query_len", 2048, "")
queries = make(map[string]query)
)
type query struct {
query string
start time.Time
}
func main() {
flag.Parse()
handle, err := pcap.OpenLive(*device, int32(*maxQueryLen)+5, true, time.Second)
defer handle.Close()
if err != nil {
log.Fatal(err)
}
handle.SetBPFFilter(*BPFFilter)
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
var (
ipLayer *layers.IPv4
tcpLayer *layers.TCP
ok bool
)
for packet := range packetSource.Packets() {
if applicationLayer := packet.ApplicationLayer(); applicationLayer != nil {
if ipLayer, ok = packet.Layer(layers.LayerTypeIPv4).(*layers.IPv4); !ok {
continue
}
if tcpLayer, ok = packet.Layer(layers.LayerTypeTCP).(*layers.TCP); !ok {
continue
}
playload := applicationLayer.Payload()
if len(playload) < 5 {
continue
}
length := _len(playload[1:5])
if length > len(playload)-1 {
continue
}
switch playload[0] {
case 'Q', 'P':
from := fmt.Sprintf("%s%d:%s%d\n", ipLayer.SrcIP, tcpLayer.SrcPort, ipLayer.DstIP, tcpLayer.DstPort)
if *queryFilter == "" || bytes.Contains(bytes.ToLower(playload[5:length]), bytes.ToLower([]byte(*queryFilter))) {
queries[from] = query{
query: string(playload[5:length]),
start: packet.Metadata().Timestamp,
}
}
case 'B':
// params
default:
from := fmt.Sprintf("%s%d:%s%d\n", ipLayer.DstIP, tcpLayer.DstPort, ipLayer.SrcIP, tcpLayer.SrcPort)
if query, found := queries[from]; found {
queryTime := packet.Metadata().Timestamp.Sub(query.start)
if *slowQueryTime == 0 || queryTime.Nanoseconds() > *slowQueryTime*1000000 {
fmt.Printf("-[ QUERY %f s]-:\n%s\n\n\n", queryTime.Seconds(), query.query)
}
delete(queries, from)
}
}
}
}
}
func _len(b []byte) int {
return int(b[0])<<24 | int(b[1])<<16 | int(b[2])<<8 | int(b[3])
}