SDL: Fixed potential clobbering of packets of different types using SDL_HIDAPI_SendRumble()

From 38af459dd9ea05c014aab71418ab8747bb773dd9 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Sun, 6 Nov 2022 01:15:19 -0700
Subject: [PATCH] Fixed potential clobbering of packets of different types
 using SDL_HIDAPI_SendRumble()

---
 src/joystick/hidapi/SDL_hidapi_ps4.c    |  4 +++-
 src/joystick/hidapi/SDL_hidapi_ps5.c    |  4 +++-
 src/joystick/hidapi/SDL_hidapi_rumble.c | 13 ++++++-------
 3 files changed, 12 insertions(+), 9 deletions(-)

diff --git a/src/joystick/hidapi/SDL_hidapi_ps4.c b/src/joystick/hidapi/SDL_hidapi_ps4.c
index 52326a9e4293..63d720df50ce 100644
--- a/src/joystick/hidapi/SDL_hidapi_ps4.c
+++ b/src/joystick/hidapi/SDL_hidapi_ps4.c
@@ -615,7 +615,9 @@ HIDAPI_DriverPS4_TickleBluetooth(SDL_HIDAPI_Device *device)
     data[0] = k_EPS4ReportIdBluetoothEffects;
     data[1] = 0xC0;  /* Magic value HID + CRC */
 
-    SDL_HIDAPI_SendRumble(device, data, sizeof(data));
+    if (SDL_HIDAPI_LockRumble() == 0) {
+        SDL_HIDAPI_SendRumbleAndUnlock(device, data, sizeof(data));
+    }
 }
 
 static void
diff --git a/src/joystick/hidapi/SDL_hidapi_ps5.c b/src/joystick/hidapi/SDL_hidapi_ps5.c
index 4b2255d17c01..7458adaf4522 100644
--- a/src/joystick/hidapi/SDL_hidapi_ps5.c
+++ b/src/joystick/hidapi/SDL_hidapi_ps5.c
@@ -746,7 +746,9 @@ HIDAPI_DriverPS5_TickleBluetooth(SDL_HIDAPI_Device *device)
     data[0] = k_EPS5ReportIdBluetoothEffects;
     data[1] = 0x02;  /* Magic value */
 
-    SDL_HIDAPI_SendRumble(device, data, sizeof(data));
+    if (SDL_HIDAPI_LockRumble() == 0) {
+        SDL_HIDAPI_SendRumbleAndUnlock(device, data, sizeof(data));
+    }
 }
 
 static void
diff --git a/src/joystick/hidapi/SDL_hidapi_rumble.c b/src/joystick/hidapi/SDL_hidapi_rumble.c
index 9cbdb959937b..9e4571f437dc 100644
--- a/src/joystick/hidapi/SDL_hidapi_rumble.c
+++ b/src/joystick/hidapi/SDL_hidapi_rumble.c
@@ -240,19 +240,18 @@ int SDL_HIDAPI_SendRumble(SDL_HIDAPI_Device *device, const Uint8 *data, int size
     int *pending_size;
     int maximum_size;
 
+    if (size <= 0) {
+        return SDL_SetError("Tried to send rumble with invalid size");
+    }
+
     if (SDL_HIDAPI_LockRumble() < 0) {
         return -1;
     }
 
     /* check if there is a pending request for the device and update it */
-    if (SDL_HIDAPI_GetPendingRumbleLocked(device, &pending_data, &pending_size, &maximum_size)) {
-        if (size > maximum_size) {
-            SDL_HIDAPI_UnlockRumble();
-            return SDL_SetError("Couldn't send rumble, size %d is greater than %d", size, maximum_size);
-        }
-
+    if (SDL_HIDAPI_GetPendingRumbleLocked(device, &pending_data, &pending_size, &maximum_size) &&
+        size == *pending_size && data[0] == pending_data[0]) {
         SDL_memcpy(pending_data, data, size);
-        *pending_size = size;
         SDL_HIDAPI_UnlockRumble();
         return size;
     }