unix/modusocket: Fix use of setsockopt in usocket.settimeout impl.

The original code called setsockopt(SO_RCVTIMEO/SO_SNDTIMEO) with NULL
timeout structure argument, which is an illegal usage of that function.
The old code also didn't validate the return value of setsockopt, missing
the bug completely.
This commit is contained in:
Elad Namdar 2019-05-07 00:24:22 +03:00 committed by Damien George
parent b8c74014e4
commit 3f54462add
1 changed files with 11 additions and 9 deletions

View File

@ -337,10 +337,9 @@ STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) {
struct timeval tv = {0,};
bool new_blocking = true;
if (timeout_in == mp_const_none) {
setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, NULL, 0);
setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, NULL, 0);
} else {
// Timeout of None means no timeout, which in POSIX is signified with 0 timeout,
// and that's how 'tv' is initialized above
if (timeout_in != mp_const_none) {
#if MICROPY_PY_BUILTINS_FLOAT
mp_float_t val = mp_obj_get_float(timeout_in);
double ipart;
@ -354,14 +353,17 @@ STATIC mp_obj_t socket_settimeout(mp_obj_t self_in, mp_obj_t timeout_in) {
// for Python API it means non-blocking.
if (tv.tv_sec == 0 && tv.tv_usec == 0) {
new_blocking = false;
} else {
setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO,
&tv, sizeof(struct timeval));
setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO,
&tv, sizeof(struct timeval));
}
}
if (new_blocking) {
int r;
r = setsockopt(self->fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval));
RAISE_ERRNO(r, errno);
r = setsockopt(self->fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval));
RAISE_ERRNO(r, errno);
}
if (self->blocking != new_blocking) {
socket_setblocking(self_in, mp_obj_new_bool(new_blocking));
}