Skip to content

Commit

Permalink
Windows: ensure buffer passed to HidD_SetFeature is large enough (#224)
Browse files Browse the repository at this point in the history
  • Loading branch information
Mornix committed Dec 24, 2020
1 parent 916fad5 commit fb4135c
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion windows/hid.c
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,8 @@ struct hid_device_ {
BOOL blocking;
USHORT output_report_length;
size_t input_report_length;
USHORT feature_report_length;
unsigned char *feature_buf;
void *last_error_str;
DWORD last_error_num;
BOOL read_pending;
Expand All @@ -160,6 +162,8 @@ static hid_device *new_hid_device()
dev->blocking = TRUE;
dev->output_report_length = 0;
dev->input_report_length = 0;
dev->feature_report_length = 0;
dev->feature_buf = NULL;
dev->last_error_str = NULL;
dev->last_error_num = 0;
dev->read_pending = FALSE;
Expand All @@ -178,6 +182,7 @@ static void free_hid_device(hid_device *dev)
CloseHandle(dev->write_ol.hEvent);
CloseHandle(dev->device_handle);
LocalFree(dev->last_error_str);
free(dev->feature_buf);
free(dev->read_buf);
free(dev);
}
Expand Down Expand Up @@ -640,6 +645,7 @@ HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
}
dev->output_report_length = caps.OutputReportByteLength;
dev->input_report_length = caps.InputReportByteLength;
dev->feature_report_length = caps.FeatureReportByteLength;
HidD_FreePreparsedData(pp_data);

dev->read_buf = (char*) malloc(dev->input_report_length);
Expand Down Expand Up @@ -811,7 +817,29 @@ int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonbloc

int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
{
BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, (DWORD) length);
BOOL res = FALSE;
unsigned char *buf;
size_t length_to_send;

/* Windows expects at least caps.FeatureReportByteLength bytes passed
to HidD_SetFeature(), even if the report is shorter. Any less sent and
the function fails with error ERROR_INVALID_PARAMETER set. Any more
and HidD_SetFeature() silently truncates the data sent in the report
to caps.FeatureReportByteLength. */
if (length >= dev->feature_report_length) {
buf = (unsigned char *) data;
length_to_send = length;
} else {
if (dev->feature_buf == NULL)
dev->feature_buf = (unsigned char *) malloc(dev->feature_report_length);
buf = dev->feature_buf;
memcpy(buf, data, length);
memset(buf + length, 0, dev->feature_report_length - length);
length_to_send = dev->feature_report_length;
}

res = HidD_SetFeature(dev->device_handle, (PVOID)buf, (DWORD) length_to_send);

if (!res) {
register_error(dev, "HidD_SetFeature");
return -1;
Expand Down

0 comments on commit fb4135c

Please sign in to comment.