fluffy/pcap.go

126 lines
1.9 KiB
Go
Raw Normal View History

2013-12-24 15:15:07 -07:00
package main
//package pcap
import (
"time"
"os"
"fmt"
"io"
"encoding/binary"
)
const MAXFRAME = 9000
2014-03-17 14:32:54 -06:00
const MAGIC_BE = "\xa1\xb2\xc3\xd4"
const MAGIC_LE = "\xd4\xc3\xb2\xa1"
2013-12-24 15:15:07 -07:00
const LINKTYPE_ETHERNET = 1
const LINKTYPE_RAW = 101
type FileHeader struct {
VersionMajor uint16
VersionMinor uint16
ThisZone int32
SigFigs uint32
2013-12-24 16:37:33 -07:00
SnapLen uint32
LinkType uint32
2013-12-24 15:15:07 -07:00
}
type PcapFile struct {
order binary.ByteOrder
header FileHeader
}
2013-12-24 16:37:33 -07:00
type FrameHeader struct {
2014-01-08 11:49:55 -07:00
Sec uint32
Usec uint32
Caplen uint32
Framelen uint32
}
func (h *FrameHeader) Time() time.Time {
return time.Unix(int64(h.Sec), int64(h.Usec) * 1000)
2013-12-24 16:37:33 -07:00
}
type Frame struct {
FrameHeader
payload []byte
}
2013-12-24 15:15:07 -07:00
type Reader struct {
PcapFile
r io.Reader
}
type Writer struct {
PcapFile
w io.Writer
}
func NewReader(r io.Reader) (*Reader, error) {
var h FileHeader
2014-03-17 14:32:54 -06:00
var order binary.ByteOrder
magic := make([]byte, 4)
2013-12-24 15:15:07 -07:00
2014-03-17 14:32:54 -06:00
if err := r.Read(&magic); err != nil {
2013-12-24 15:15:07 -07:00
return nil, err
}
2014-03-17 14:32:54 -06:00
switch (magic) {
case MAGIC_BE:
order = binary.BigEndian
case MAGIC_LE:
2013-12-24 15:15:07 -07:00
order = binary.LittleEndian
2014-03-17 14:32:54 -06:00
default:
return nil, fmt.Errorf("Cannot determine endianness")
2013-12-24 15:15:07 -07:00
}
2014-03-17 14:32:54 -06:00
2013-12-24 15:15:07 -07:00
if err := binary.Read(r, order, &h); err != nil {
return nil, err
}
ret := &Reader{PcapFile{order, h}, r}
return ret, nil
}
2013-12-24 16:37:33 -07:00
func (r *Reader) Read() (*Frame, error) {
var h FrameHeader
if err := binary.Read(r.r, r.order, &h); err != nil {
return nil, err
}
2014-01-08 11:49:55 -07:00
payload := make([]byte, h.Caplen)
2013-12-24 16:37:33 -07:00
l, err := r.r.Read(payload)
if err != nil {
return nil, err
}
2014-01-08 11:49:55 -07:00
if uint32(l) < h.Caplen {
return nil, fmt.Errorf("Short read: %d (wanted %d)", l, h.Caplen)
2013-12-24 16:37:33 -07:00
}
ret := &Frame{h, payload}
return ret, nil
}
2013-12-24 15:15:07 -07:00
func main() {
r, err := NewReader(os.Stdin)
if err != nil {
panic(err)
}
fmt.Println(r.order, r.header)
2014-01-08 11:49:55 -07:00
for ;; {
frame, err := r.Read()
if err != nil {
panic(err)
}
if frame == nil {
break
}
fmt.Println("hi")
fmt.Println(frame)
}
2013-12-24 15:15:07 -07:00
}