File tree 1 file changed +14
-2
lines changed
1 file changed +14
-2
lines changed Original file line number Diff line number Diff line change 16
16
17
17
#include <stdio.h>
18
18
#include <stdlib.h>
19
+ #include <stdint.h>
20
+ #include <limits.h>
19
21
#include <string.h>
20
22
#include <errno.h>
21
23
#ifndef _MSC_VER
@@ -478,7 +480,9 @@ static void _modbus_tcp_close(modbus_t *ctx)
478
480
static int _modbus_tcp_flush (modbus_t * ctx )
479
481
{
480
482
int rc ;
481
- int rc_sum = 0 ;
483
+ // Use an unsigned 16-bit integer to reduce overflow risk. The flush function
484
+ // is not expected to handle huge amounts of data (> 2GB).
485
+ uint16_t rc_sum = 0 ;
482
486
483
487
do {
484
488
/* Extract the garbage from the socket */
@@ -505,7 +509,15 @@ static int _modbus_tcp_flush(modbus_t *ctx)
505
509
}
506
510
#endif
507
511
if (rc > 0 ) {
508
- rc_sum += rc ;
512
+ // Check for overflow before adding
513
+ if (rc_sum <= UINT16_MAX - rc ) {
514
+ rc_sum += rc ;
515
+ } else {
516
+ // Handle overflow
517
+ ctx -> error_recovery = MODBUS_ERROR_RECOVERY_PROTOCOL ;
518
+ errno = EOVERFLOW ;
519
+ return -1 ;
520
+ }
509
521
}
510
522
} while (rc == MODBUS_TCP_MAX_ADU_LENGTH );
511
523
You can’t perform that action at this time.
0 commit comments