Fixed endless loop in receive function in case of a incomplete frame

(limit = 3 timeouts)
This commit is contained in:
Stefan Wahren 2012-05-29 19:15:52 +02:00
parent dd97141f21
commit ad4d307b57
2 changed files with 29 additions and 3 deletions

View File

@ -223,7 +223,7 @@ int
mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame) mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame)
{ {
char buff[PACKET_BUFF_SIZE]; char buff[PACKET_BUFF_SIZE];
int len, remaining, nread; int len, remaining, nread, timeouts;
if (handle == NULL || frame == NULL) if (handle == NULL || frame == NULL)
{ {
@ -238,6 +238,7 @@ mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame)
// //
remaining = 1; // start by reading 1 byte remaining = 1; // start by reading 1 byte
len = 0; len = 0;
timeouts = 0;
do { do {
//printf("%s: Attempt to read %d bytes [len = %d]\n", __PRETTY_FUNCTION__, remaining, len); //printf("%s: Attempt to read %d bytes [len = %d]\n", __PRETTY_FUNCTION__, remaining, len);
@ -251,6 +252,18 @@ mbus_serial_recv_frame(mbus_serial_handle *handle, mbus_frame *frame)
// printf("%s: Got %d byte [remaining %d, len %d]\n", __PRETTY_FUNCTION__, nread, remaining, len); // printf("%s: Got %d byte [remaining %d, len %d]\n", __PRETTY_FUNCTION__, nread, remaining, len);
if (nread == 0)
{
timeouts++;
if (timeouts >= 3)
{
// abort to avoid endless loop
fprintf(stderr, "%s: Timeout\n", __PRETTY_FUNCTION__);
break;
}
}
len += nread; len += nread;
} while ((remaining = mbus_parse(frame, buff, len)) > 0); } while ((remaining = mbus_parse(frame, buff, len)) > 0);

View File

@ -165,7 +165,7 @@ int
mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame) mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame)
{ {
char buff[PACKET_BUFF_SIZE]; char buff[PACKET_BUFF_SIZE];
int len, remaining, nread; int len, remaining, nread, timeouts;
if (handle == NULL || frame == NULL) if (handle == NULL || frame == NULL)
{ {
@ -180,6 +180,7 @@ mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame)
// //
remaining = 1; // start by reading 1 byte remaining = 1; // start by reading 1 byte
len = 0; len = 0;
timeouts = 0;
do { do {
@ -189,6 +190,18 @@ mbus_tcp_recv_frame(mbus_tcp_handle *handle, mbus_frame *frame)
return -1; return -1;
} }
if (nread == 0)
{
timeouts++;
if (timeouts >= 3)
{
// abort to avoid endless loop
fprintf(stderr, "%s: Timeout\n", __PRETTY_FUNCTION__);
break;
}
}
len += nread; len += nread;
} while ((remaining = mbus_parse(frame, buff, len)) > 0); } while ((remaining = mbus_parse(frame, buff, len)) > 0);