Skip to content
This repository was archived by the owner on Jul 22, 2023. It is now read-only.

Commit b556488

Browse files
committed
Fix faulty io net error handling code in posix BSP
Basically, when the SDK allocates the structure in which it will store the socket descriptor it opens when connecting to the iotcore server, it initializes it to 0. If during the process of creating the socket, the posix BSP routine (iotc_bsp_io_net_socket_connect) that creates the socket can’t resolve the iotcore server name, it returns an error (leaving the socket descriptor field initialized to 0). In turn, the io net routine (iotc_io_net_layer_connect) that itself called iotc_bsp_io_net_socket_connect, on seeing the error, will then execute its error handling code that itself ends up calling the io net routine iotc_io_net_layer_close_externally that then calls the posix BSP iotc_bsp_io_net_close_socket routine. The posix BSP iotc_bsp_io_net_close_socket routine then blindly closes socket descriptor 0 (since this is what the data structure tracking the socket descriptor is still initialized to since no socket was ever successfully opened). Files modified: src/bsp/platform/posix/iotc_bsp_io_net_posix.c - always set *iotc_socket to -1 before attempting to connect or after closing the socket and always check that *iotc_socket is not -1 before attempting to close it in iotc_bsp_io_net_close_socket().
1 parent 09f84c8 commit b556488

File tree

1 file changed

+14
-1
lines changed

1 file changed

+14
-1
lines changed

src/bsp/platform/posix/iotc_bsp_io_net_posix.c

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,13 @@ iotc_bsp_io_net_state_t iotc_bsp_io_net_socket_connect(
4949
hints.ai_flags = 0;
5050
hints.ai_protocol = 0;
5151

52+
// in case of error, we want *iotc_socket initialized to a non-valid
53+
// value so that iotc_bsp_io_net_close_socket can check before
54+
// closing a socket to ensure that the socket was genuinely opened;
55+
// otherwise iotc_bsp_io_net_close_socket can be at risk of
56+
// incorrectly closing STDIN_FILENO
57+
*iotc_socket = -1;
58+
5259
// Address resolution.
5360
status = getaddrinfo(host, NULL, &hints, &result);
5461
if (0 != status) {
@@ -90,6 +97,7 @@ iotc_bsp_io_net_state_t iotc_bsp_io_net_socket_connect(
9097
return IOTC_BSP_IO_NET_STATE_OK;
9198
} else {
9299
close(*iotc_socket);
100+
*iotc_socket = -1;
93101
}
94102
}
95103
}
@@ -200,11 +208,16 @@ iotc_bsp_io_net_state_t iotc_bsp_io_net_close_socket(
200208
return IOTC_BSP_IO_NET_STATE_ERROR;
201209
}
202210

211+
if (*iotc_socket < 0)
212+
// no need to close a socket that was never opened in the first
213+
// place
214+
return IOTC_BSP_IO_NET_STATE_OK;
215+
203216
shutdown(*iotc_socket, SHUT_RDWR);
204217

205218
close(*iotc_socket);
206219

207-
*iotc_socket = 0;
220+
*iotc_socket = -1;
208221

209222
return IOTC_BSP_IO_NET_STATE_OK;
210223
}

0 commit comments

Comments
 (0)