@@ -254,7 +254,7 @@ void ModbusTCPTemplate<SERVER, CLIENT>::task() {
254254 for (n = 0 ; n < MODBUSIP_MAX_CLIENTS; n++) {
255255 if (!tcpclient[n]) continue ;
256256 if (!tcpclient[n]->connected ()) continue ;
257- while (millis () - taskStart < MODBUSIP_MAX_READMS && ( size_t )tcpclient[n]->available () > sizeof (_MBAP)) {
257+ while (( size_t )tcpclient[n]->available () > sizeof (_MBAP) && millis () - taskStart < MODBUSIP_MAX_READMS ) {
258258#if defined(MODBUSIP_DEBUG)
259259 Serial.print (n);
260260 Serial.print (" : Bytes available " );
@@ -268,20 +268,28 @@ void ModbusTCPTemplate<SERVER, CLIENT>::task() {
268268 continue ;
269269 }
270270 _len = __swap_16 (_MBAP.length );
271+ if (_len < MODBUSIP_MINFRAME) { // Length is over MODBUSIP_MAXFRAME
272+ while (tcpclient[n]->available ()) // Drop rest of the packet
273+ tcpclient[n]->read ();
274+ exceptionResponse (fc, EX_ILLEGAL_VALUE);
275+ }
271276 _len--; // Do not count with last byte from MBAP
272277 if (_len > MODBUSIP_MAXFRAME) { // Length is over MODBUSIP_MAXFRAME
273- exceptionResponse (( FunctionCode) tcpclient[n]->read (), EX_SLAVE_FAILURE );
278+ Modbus:: FunctionCode fc = tcpclient[n]->read ();
274279 _len--; // Subtract for read byte
275- for (uint8_t i = 0 ; tcpclient[n]->available () && i < _len; i++) // Drop rest of packet
280+ for (uint8_t i = 0 ; tcpclient[n]->available () && i < _len; i++) // Drop rest of the packet
276281 tcpclient[n]->read ();
282+ exceptionResponse (fc, EX_SLAVE_FAILURE);
277283 }
278284 else {
279285 free (_frame);
280286 _frame = (uint8_t *) malloc (_len);
281287 if (!_frame) {
282- exceptionResponse ((FunctionCode)tcpclient[n]->read (), EX_SLAVE_FAILURE);
283- for (uint8_t i = 0 ; tcpclient[n]->available () && i < _len; i++) // Drop packet
288+ Modbus::FunctionCode fc = tcpclient[n]->read ();
289+ _len--; // Subtract for read byte
290+ for (uint8_t i = 0 ; tcpclient[n]->available () && i < _len; i++) // Drop rest of the packet
284291 tcpclient[n]->read ();
292+ exceptionResponse (fc, EX_SLAVE_FAILURE);
285293 }
286294 else {
287295 if (tcpclient[n]->readBytes (_frame, _len) < _len) { // Try to read MODBUS frame
0 commit comments