Skip to content

Commit

Permalink
Merge pull request #5 from MarinX/handle-error-on-read
Browse files Browse the repository at this point in the history
Handle error when reading/parsing from file
  • Loading branch information
MarinX authored Feb 14, 2019
2 parents 7f76a35 + e14f2cf commit bf368a5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
24 changes: 13 additions & 11 deletions keylogger.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ func (k *KeyLogger) Read() chan InputEvent {
event := make(chan InputEvent)
go func(event chan InputEvent) {
for {
e := k.read()
e, err := k.read()
if err != nil {
logrus.Error(err)
close(event)
break
}

if e != nil {
event <- *e
}
Expand All @@ -70,28 +76,24 @@ func (k *KeyLogger) Read() chan InputEvent {
}

// read from file description and parse binary into go struct
func (k *KeyLogger) read() *InputEvent {
func (k *KeyLogger) read() (*InputEvent, error) {
buffer := make([]byte, eventsize)
n, err := k.fd.Read(buffer)
if err != nil {
logrus.Error(err)
return nil
return nil, err
}
// no input, dont send error
if n <= 0 {
return nil
return nil, nil
}
return k.eventFromBuffer(buffer)
}

// eventFromBuffer parser bytes into InputEvent struct
func (k *KeyLogger) eventFromBuffer(buffer []byte) *InputEvent {
func (k *KeyLogger) eventFromBuffer(buffer []byte) (*InputEvent, error) {
event := &InputEvent{}
err := binary.Read(bytes.NewBuffer(buffer), binary.LittleEndian, event)
if err != nil {
logrus.Error(err)
return nil
}
return event
return event, err
}

// Close file descriptor
Expand Down
6 changes: 5 additions & 1 deletion keylogger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ func TestBufferParser(t *testing.T) {
k := &KeyLogger{}

// keyboard
input := k.eventFromBuffer([]byte{138, 180, 84, 92, 0, 0, 0, 0, 62, 75, 8, 0, 0, 0, 0, 0, 4, 0, 4, 0, 30, 0, 0, 0})
input, err := k.eventFromBuffer([]byte{138, 180, 84, 92, 0, 0, 0, 0, 62, 75, 8, 0, 0, 0, 0, 0, 4, 0, 4, 0, 30, 0, 0, 0})
if err != nil {
t.Error(err)
return
}
if input == nil {
t.Error("Event is empty, expected parsed event")
return
Expand Down

0 comments on commit bf368a5

Please sign in to comment.