2022-09-08 02:38:43 +05:30
|
|
|
// Copyright 2010-2022 Nicholas J. Kain <njkain at gmail dot com>
|
2022-02-07 06:35:29 +05:30
|
|
|
// SPDX-License-Identifier: MIT
|
2020-10-20 16:14:31 +05:30
|
|
|
#ifndef NCM_IO_H_
|
|
|
|
#define NCM_IO_H_
|
|
|
|
|
2022-09-08 02:38:43 +05:30
|
|
|
#include <unistd.h>
|
|
|
|
#include <errno.h>
|
|
|
|
#include <limits.h>
|
2020-10-20 16:14:31 +05:30
|
|
|
#include <sys/socket.h>
|
2022-09-08 02:38:43 +05:30
|
|
|
#include <sys/types.h>
|
2020-10-20 16:14:31 +05:30
|
|
|
|
|
|
|
ssize_t safe_read(int fd, char *buf, size_t len);
|
2022-09-08 02:38:43 +05:30
|
|
|
// Same as above, but will only call read one time.
|
|
|
|
// Meant to be used with a blocking fd where we need <= len bytes.
|
|
|
|
static inline ssize_t safe_read_once(int fd, char *buf, size_t len)
|
|
|
|
{
|
|
|
|
if (len > SSIZE_MAX) len = SSIZE_MAX;
|
|
|
|
ssize_t r;
|
|
|
|
for (;;) {
|
|
|
|
r = read(fd, buf, len);
|
|
|
|
if (r >= 0 || errno != EINTR) break;
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
2020-10-20 16:14:31 +05:30
|
|
|
ssize_t safe_write(int fd, const char *buf, size_t len);
|
|
|
|
ssize_t safe_sendto(int fd, const char *buf, size_t len, int flags,
|
|
|
|
const struct sockaddr *dest_addr, socklen_t addrlen);
|
2022-09-08 02:38:43 +05:30
|
|
|
|
2020-10-20 16:14:31 +05:30
|
|
|
ssize_t safe_recv(int fd, char *buf, size_t len, int flags);
|
2022-09-08 02:38:43 +05:30
|
|
|
// Same as above, but will only call read one time.
|
|
|
|
// Meant to be used with a blocking fd where we need <= len bytes.
|
|
|
|
static inline ssize_t safe_recv_once(int fd, char *buf, size_t len, int flags)
|
|
|
|
{
|
|
|
|
if (len > SSIZE_MAX) len = SSIZE_MAX;
|
|
|
|
ssize_t r;
|
|
|
|
for (;;) {
|
|
|
|
r = recv(fd, buf, len, flags);
|
|
|
|
if (r >= 0 || errno != EINTR) break;
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
|
|
|
|
static inline ssize_t safe_recvmsg(int fd, struct msghdr *msg, int flags)
|
|
|
|
{
|
|
|
|
ssize_t r;
|
|
|
|
for (;;) {
|
|
|
|
r = recvmsg(fd, msg, flags);
|
|
|
|
if (r >= 0 || errno != EINTR) break;
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
|
|
|
static inline int safe_ftruncate(int fd, off_t length)
|
|
|
|
{
|
|
|
|
int r;
|
|
|
|
for (;;) {
|
|
|
|
r = ftruncate(fd, length);
|
|
|
|
if (!r || errno != EINTR) break;
|
|
|
|
}
|
|
|
|
return r;
|
|
|
|
}
|
2020-10-20 16:14:31 +05:30
|
|
|
|
2022-02-07 06:35:29 +05:30
|
|
|
#endif
|
|
|
|
|