netshovel/examples/simple/simple.go

88 lines
1.5 KiB
Go
Raw Normal View History

2018-07-23 09:58:31 -06:00
package main
import (
2018-07-23 15:34:22 -06:00
"fmt"
"io"
"log"
"strings"
"sync"
"time"
2018-07-23 15:34:22 -06:00
"github.com/google/gopacket"
"github.com/google/gopacket/tcpassembly"
2018-07-23 09:58:31 -06:00
"github.com/dirtbags/netshovel"
)
var threads int
2018-07-23 15:34:22 -06:00
var wg sync.WaitGroup
type SimpleStreamFactory struct {
2018-07-23 09:58:31 -06:00
}
2018-07-23 15:34:22 -06:00
type SimpleStream struct {
2018-07-23 09:58:31 -06:00
netshovel.Stream
}
2018-07-23 15:34:22 -06:00
type SimplePacket struct {
netshovel.Packet
}
func NewSimplePacket() SimplePacket {
return SimplePacket{
Packet: netshovel.NewPacket(),
}
}
2018-07-23 09:58:31 -06:00
func (f *SimpleStreamFactory) New(net, transport gopacket.Flow) tcpassembly.Stream {
2018-07-23 15:34:22 -06:00
stream := &SimpleStream{
Stream: netshovel.NewStream(net, transport),
}
threads += 1
2018-07-23 15:34:22 -06:00
wg.Add(1)
go stream.Decode(wg)
return stream
2018-07-23 09:58:31 -06:00
}
2018-07-23 15:34:22 -06:00
func (stream SimpleStream) Display(pkt SimplePacket) {
out := new(strings.Builder)
fmt.Fprintf(out, "Simple %v:%v → %v:%v\n",
stream.Net.Src().String(), stream.Transport.Src().String(),
stream.Net.Dst().String(), stream.Transport.Dst().String(),
)
out.WriteString(pkt.Describe())
fmt.Println(out.String())
}
func (stream SimpleStream) Decode(wg sync.WaitGroup) {
for {
pkt := NewSimplePacket()
utterance, err := stream.Read(-1)
if err != nil {
if err != io.EOF {
log.Println(err)
}
break
}
pkt.Payload = utterance.Data
pkt.When = utterance.When
stream.Display(pkt)
}
threads -= 1
wg.Done()
2018-07-23 09:58:31 -06:00
}
func main() {
threads = 0
2018-07-23 15:34:22 -06:00
netshovel.Shovel(&SimpleStreamFactory{})
// XXX: ZOMG WHY
for threads > 0 {
time.Sleep(100 * time.Millisecond)
}
//wg.Wait()
2018-07-23 09:58:31 -06:00
}