Use writev() instead of writing before an allocated region

This commit is contained in:
Frank Denis 2015-11-04 02:18:19 +01:00
parent 8b8772f4f1
commit d3b16d7829
2 changed files with 22 additions and 7 deletions

View File

@ -56,16 +56,16 @@
int tcp_write(int fd, char *buf, int len) int tcp_write(int fd, char *buf, int len)
{ {
register char *ptr; struct iovec iov[2];
uint16_t header;
/* \/ WHOEVER WROTE THAT IS A DANGEROUS PSYCHOPATH \/ */ header = htons((uint16_t) len);
ptr = buf - sizeof(short); len = len & VTUN_FSIZE_MASK;
*((unsigned short *)ptr) = htons(len); iov[0] = (struct iovec) { .iov_base = &header, .iov_len = 2U };
/* /\ WHOEVER WROTE THAT IS A DANGEROUS PSYCHOPATH /\ */ iov[1] = (struct iovec) { .iov_base = buf, .iov_len = len };
len = (len & VTUN_FSIZE_MASK) + sizeof(short);
return write_n(fd, ptr, len); return write_v(fd, iov, 2);
} }
int tcp_read(int fd, char *buf) int tcp_read(int fd, char *buf)

15
lib.h
View File

@ -26,6 +26,7 @@
#include <sys/types.h> #include <sys/types.h>
#include <signal.h> #include <signal.h>
#include <errno.h> #include <errno.h>
#include <unistd.h>
#ifdef HAVE_LIBUTIL_H #ifdef HAVE_LIBUTIL_H
#include <libutil.h> #include <libutil.h>
@ -104,4 +105,18 @@ static inline int write_n(int fd, char *buf, int len)
return t; return t;
} }
static inline int write_v(int fd, const struct iovec *iov, int iov_count)
{
ssize_t w = -1;
while (!__io_canceled) {
if( (w = writev(fd, iov, iov_count)) < 0 ){
if( errno == EINTR || errno == EAGAIN )
continue;
}
break;
}
return (int) w;
}
#endif /* _VTUN_LIB_H */ #endif /* _VTUN_LIB_H */