Skip to content

Commit 8f8be69

Browse files
committed
feat: validate response length
1 parent aa945d5 commit 8f8be69

File tree

2 files changed

+12
-5
lines changed

2 files changed

+12
-5
lines changed

hid/device.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,6 @@ func (d *Device) Read(count int) ([]byte, error) {
7777
if err != nil {
7878
return nil, err
7979
}
80-
packet := buf[1:]
8180
if d.debug {
8281
if length > 0 {
8382
log.Printf("Read %v", buf)
@@ -86,7 +85,7 @@ func (d *Device) Read(count int) ([]byte, error) {
8685
}
8786
}
8887
d.waitSync()
89-
return packet, nil
88+
return buf[1:], nil
9089
}
9190

9291
// Request sends a request to the device.
@@ -137,7 +136,15 @@ func (d *Device) tryRequest(payload []byte, count int) ([]byte, error) {
137136
if err != nil {
138137
return nil, err
139138
}
140-
return d.Read(count)
139+
resp, err := d.Read(count)
140+
if err != nil {
141+
return nil, err
142+
}
143+
// The first element is feature report id, it is truncated
144+
if len(resp) != count-1 {
145+
return nil, NewErrCountMismatch(count-1, len(resp))
146+
}
147+
return resp, nil
141148
}
142149

143150
func (d *Device) waitSync() {

hid/errors.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ import (
99
// ErrNotFound is returned when the device wasn't found
1010
var ErrNotFound = errors.New("keyboard is not found")
1111

12-
// ErrCountMismatch is returned when transmitted number of bytes is not expected
13-
var ErrCountMismatch = errors.New("transmitted number of bytes is not expected")
12+
// ErrCountMismatch is returned when number of bytes is not expected
13+
var ErrCountMismatch = errors.New("unexpected bytes count")
1414

1515
// NewErrCountMismatch creates a byte count mismatch error.
1616
func NewErrCountMismatch(expected, actual int) error {

0 commit comments

Comments
 (0)