Skip to content

Commit d25ae92

Browse files
committed
mruby-socket: fix file descriptor leaks in accept2 and socketpair
Fixed critical resource leaks by pre-allocating mruby objects before system calls. Since mrb_str_resize to smaller size and mrb_ary_push within pre-allocated size cannot fail, moving allocations before socket creation eliminates all leak potential with minimal code changes. Co-authored-by: Atlassian Rovo Dev
1 parent ea7ac6d commit d25ae92

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

mrbgems/mruby-socket/src/socket.c

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -765,14 +765,14 @@ mrb_socket_accept2(mrb_state *mrb, mrb_value klass)
765765

766766
socklen_t socklen = sizeof(struct sockaddr_storage);
767767
mrb_value sastr = mrb_str_new_capa(mrb, (mrb_int)socklen);
768+
mrb_value ary = mrb_ary_new_capa(mrb, 2);
769+
768770
int s1 = (int)accept(s0, (struct sockaddr*)RSTRING_PTR(sastr), &socklen);
769771
if (s1 == -1) {
770772
mrb_sys_fail(mrb, "accept");
771773
}
772-
// XXX: possible descriptor leakage here!
773-
mrb_str_resize(mrb, sastr, socklen);
774774

775-
mrb_value ary = mrb_ary_new_capa(mrb, 2);
775+
mrb_str_resize(mrb, sastr, socklen);
776776
mrb_ary_push(mrb, ary, mrb_fixnum_value(s1));
777777
mrb_ary_push(mrb, ary, sastr);
778778
return ary;
@@ -868,11 +868,12 @@ mrb_socket_socketpair(mrb_state *mrb, mrb_value klass)
868868
int sv[2];
869869

870870
mrb_get_args(mrb, "iii", &domain, &type, &protocol);
871+
mrb_value ary = mrb_ary_new_capa(mrb, 2);
872+
871873
if (socketpair(domain, type, protocol, sv) == -1) {
872874
mrb_sys_fail(mrb, "socketpair");
873875
}
874-
// XXX: possible descriptor leakage here!
875-
mrb_value ary = mrb_ary_new_capa(mrb, 2);
876+
876877
mrb_ary_push(mrb, ary, mrb_fixnum_value(sv[0]));
877878
mrb_ary_push(mrb, ary, mrb_fixnum_value(sv[1]));
878879
return ary;

0 commit comments

Comments
 (0)