Skip to content

Commit

Permalink
Avoid calling fstat on things we already know are valid sockets.
Browse files Browse the repository at this point in the history
  • Loading branch information
ioquatix committed Jul 12, 2021
1 parent 0895d57 commit 028441d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 20 deletions.
30 changes: 28 additions & 2 deletions ext/socket/basicsocket.c
Expand Up @@ -10,6 +10,28 @@

#include "rubysocket.h"

#ifdef _WIN32
#define is_socket(fd) rb_w32_is_socket(fd)
#else
static int
is_socket(int fd)
{
struct stat sbuf;

if (fstat(fd, &sbuf) < 0)
rb_sys_fail("fstat(2)");
return S_ISSOCK(sbuf.st_mode);
}
#endif

static void
rsock_validate_descriptor(int descriptor)
{
if (!is_socket(descriptor) || rb_reserved_fd_p(descriptor)) {
rb_syserr_fail(EBADF, "not a socket file descriptor");
}
}

/*
* call-seq:
* BasicSocket.for_fd(fd) => basicsocket
Expand All @@ -22,10 +44,14 @@
*
*/
static VALUE
bsock_s_for_fd(VALUE klass, VALUE fd)
bsock_s_for_fd(VALUE klass, VALUE _descriptor)
{
rb_io_t *fptr;
VALUE sock = rsock_init_sock(rb_obj_alloc(klass), NUM2INT(fd));

int descriptor = RB_NUM2INT(_descriptor);
rsock_validate_descriptor(descriptor);

VALUE sock = rsock_init_sock(rb_obj_alloc(klass), descriptor);

GetOpenFile(sock, fptr);

Expand Down
18 changes: 0 additions & 18 deletions ext/socket/init.c
Expand Up @@ -54,20 +54,6 @@ rsock_raise_socket_error(const char *reason, int error)
#endif
}

#ifdef _WIN32
#define is_socket(fd) rb_w32_is_socket(fd)
#else
static int
is_socket(int fd)
{
struct stat sbuf;

if (fstat(fd, &sbuf) < 0)
rb_sys_fail("fstat(2)");
return S_ISSOCK(sbuf.st_mode);
}
#endif

#if defined __APPLE__
# define do_write_retry(code) do {ret = code;} while (ret == -1 && errno == EPROTOTYPE)
#else
Expand All @@ -79,10 +65,6 @@ rsock_init_sock(VALUE sock, int fd)
{
rb_io_t *fp;

if (!is_socket(fd) || rb_reserved_fd_p(fd)) {
rb_syserr_fail(EBADF, "not a socket file descriptor");
}

rb_update_max_fd(fd);
MakeOpenFile(sock, fp);
fp->fd = fd;
Expand Down

0 comments on commit 028441d

Please sign in to comment.