Skip to content

Commit f832d95

Browse files
nurseioquatix
andcommitted
ext/socket/init.c: do not return uninitialized buffer
BasicSocket#read_nonblock and some methods changes the size of a buffer string, but when no data is available, the buffer is returned as uninitialized. Co-Authored-By: Samuel Williams <samuel.williams@oriontransfer.co.nz>
1 parent 5caee29 commit f832d95

File tree

1 file changed

+8
-9
lines changed

1 file changed

+8
-9
lines changed

ext/socket/init.c

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ rsock_send_blocking(void *data)
121121
struct recvfrom_arg {
122122
int fd, flags;
123123
VALUE str;
124+
size_t length;
124125
socklen_t alen;
125126
union_sockaddr buf;
126127
};
@@ -131,10 +132,11 @@ recvfrom_blocking(void *data)
131132
struct recvfrom_arg *arg = data;
132133
socklen_t len0 = arg->alen;
133134
ssize_t ret;
134-
ret = recvfrom(arg->fd, RSTRING_PTR(arg->str), RSTRING_LEN(arg->str),
135+
ret = recvfrom(arg->fd, RSTRING_PTR(arg->str), arg->length,
135136
arg->flags, &arg->buf.addr, &arg->alen);
136137
if (ret != -1 && len0 < arg->alen)
137138
arg->alen = len0;
139+
138140
return (VALUE)ret;
139141
}
140142

@@ -152,7 +154,6 @@ rsock_strbuf(VALUE str, long buflen)
152154
} else {
153155
rb_str_modify_expand(str, buflen - len);
154156
}
155-
rb_str_set_len(str, buflen);
156157
return str;
157158
}
158159

@@ -188,6 +189,7 @@ rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
188189
arg.fd = fptr->fd;
189190
arg.alen = (socklen_t)sizeof(arg.buf);
190191
arg.str = str;
192+
arg.length = buflen;
191193

192194
while (rb_io_check_closed(fptr),
193195
rsock_maybe_wait_fd(arg.fd),
@@ -198,9 +200,8 @@ rsock_s_recvfrom(VALUE sock, int argc, VALUE *argv, enum sock_recv_type from)
198200
}
199201
}
200202

201-
if (slen != RSTRING_LEN(str)) {
202-
rb_str_set_len(str, slen);
203-
}
203+
/* Resize the string to the amount of data received */
204+
rb_str_set_len(str, slen);
204205
switch (from) {
205206
case RECV_RECV:
206207
return str;
@@ -330,6 +331,7 @@ rsock_read_nonblock(VALUE sock, VALUE length, VALUE buf, VALUE ex)
330331
GetOpenFile(sock, fptr);
331332

332333
if (len == 0) {
334+
rb_str_set_len(str, 0);
333335
return str;
334336
}
335337

@@ -347,12 +349,9 @@ rsock_read_nonblock(VALUE sock, VALUE length, VALUE buf, VALUE ex)
347349
rb_syserr_fail_path(e, fptr->pathv);
348350
}
349351
}
350-
if (len != n) {
352+
if (n != RSTRING_LEN(str)) {
351353
rb_str_modify(str);
352354
rb_str_set_len(str, n);
353-
if (str != buf) {
354-
rb_str_resize(str, n);
355-
}
356355
}
357356
if (n == 0) {
358357
if (ex == Qfalse) return Qnil;

0 commit comments

Comments
 (0)