1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

Avoid calling fstat on things we already know are valid sockets.

This commit is contained in:
Samuel Williams 2021-07-12 16:28:43 +12:00
parent 0895d57d31
commit 028441d22f
Notes: git 2021-07-12 16:16:45 +09:00
2 changed files with 28 additions and 20 deletions

View file

@ -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
@ -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);

View file

@ -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
@ -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;