diff --git a/uinput_test.go b/uinput_test.go index 2982acd..5007bd6 100644 --- a/uinput_test.go +++ b/uinput_test.go @@ -24,3 +24,47 @@ func TestBasicVKeyboard(t *testing.T) { t.Fatalf("Failed to close device. Last error was: %s\n", err) } } + +// This test will confirm that a proper error code is returned if an invalid uinput path is +// passed to the library +func TestInvalidDevicePath(t *testing.T) { + devId, err := CreateVKeyboardDevice("/invalid/path") + + if err == nil { + // this usually shouldn't happen, but if the device is created, we need to close it + CloseDevice(devId) + t.Fatalf("Expected error code,but received %s instead.\n", err) + } +} + +// This test will confirm that a proper error code is returned if an invalid keycode is +// passed to the library +func TestInvalidKeycode(t *testing.T) { + devId, err := CreateVKeyboardDevice("/dev/uinput") + + if err != nil { + t.Fatalf("Failed to create the virtual keyboard. Last error was: %s\n", err) + } + + err = SendBtnEvent(devId, 4711, 1) + + if err == nil { + t.Fatalf("Sending an invalid keycode did not trigger an error. Got: %d.\n") + } +} + +// This test will confirm that a proper error code is returned if an invalid button state is +// passed to the library +func TestInvalidBtnState(t *testing.T) { + devId, err := CreateVKeyboardDevice("/dev/uinput") + + if err != nil { + t.Fatalf("Failed to create the virtual keyboard. Last error was: %s\n", err) + } + + err = SendBtnEvent(devId, KEY_1, 3) + + if err == nil { + t.Fatalf("Sending an invalid btnState did not trigger an error. Got: %d.\n") + } +} diff --git a/uinputwrapper.c b/uinputwrapper.c index 867a09c..5c14db8 100755 --- a/uinputwrapper.c +++ b/uinputwrapper.c @@ -30,8 +30,8 @@ int initVKeyboardDevice(char* uinputPath) { deviceHandle = -1; } } else { - // register key events - for(i=0; i<255; i++) { + // register key events - only values from 1 to 255 are valid + for(i=1; i<256; i++) { ioctl(deviceHandle, UI_SET_KEYBIT, i); } @@ -59,6 +59,16 @@ int initVKeyboardDevice(char* uinputPath) { } int sendBtnEvent(int deviceHandle, int key, int btnState) { + // check whether the keycode is valid and return -1 on error + if (key < 1 || key > 255) { + return -1; + } + + // btnState should only be either 0 or 1 + if (btnState < 0 || btnState > 1) { + return -1; + } + struct input_event ev; memset(&ev, 0, sizeof(ev));