dnscrypto-proxy: Update to release 1.3.0
[tomato.git] / release / src / router / dnscrypt / src / proxy / safe_rw.c
blobd0c0905ff2ad0d46522764ea5b60b89864bd0af2
2 #include <config.h>
3 #include <sys/types.h>
5 #include <assert.h>
6 #include <errno.h>
7 #ifndef _WIN32
8 # include <poll.h>
9 #endif
10 #include <stdlib.h>
11 #include <unistd.h>
13 #include "safe_rw.h"
15 #ifndef _WIN32
16 ssize_t
17 safe_write(const int fd, const void * const buf_, size_t count,
18 const int timeout)
20 struct pollfd pfd;
21 const char *buf = (const char *) buf_;
22 ssize_t written;
24 pfd.fd = fd;
25 pfd.events = POLLOUT;
27 while (count > (size_t) 0) {
28 while ((written = write(fd, buf, count)) <= (ssize_t) 0) {
29 if (errno == EAGAIN) {
30 if (poll(&pfd, (nfds_t) 1, timeout) == 0) {
31 errno = ETIMEDOUT;
32 goto ret;
34 } else if (errno != EINTR) {
35 goto ret;
38 buf += written;
39 count -= (size_t) written;
41 ret:
42 return (ssize_t) (buf - (const char *) buf_);
45 ssize_t
46 safe_read(const int fd, void * const buf_, size_t count)
48 unsigned char *buf = (unsigned char *) buf_;
49 ssize_t readnb;
51 do {
52 while ((readnb = read(fd, buf, count)) < (ssize_t) 0 &&
53 errno == EINTR);
54 if (readnb < (ssize_t) 0) {
55 return readnb;
57 if (readnb == (ssize_t) 0) {
58 break;
60 count -= (size_t) readnb;
61 buf += readnb;
62 } while (count > (ssize_t) 0);
64 return (ssize_t) (buf - (unsigned char *) buf_);
67 ssize_t
68 safe_read_partial(const int fd, void * const buf_, const size_t max_count)
70 unsigned char * const buf = (unsigned char *) buf_;
71 ssize_t readnb;
73 while ((readnb = read(fd, buf, max_count)) < (ssize_t) 0 &&
74 errno == EINTR);
76 return readnb;
79 #else /* _WIN32 */
81 ssize_t
82 safe_write(const int fd, const void * const buf_, size_t count,
83 const int timeout)
85 assert(fd != -1);
86 assert(buf_ != NULL);
87 assert(count > (size_t) 0U);
88 (void) timeout;
90 return -1;
93 ssize_t
94 safe_read(const int fd, void * const buf_, size_t count)
96 assert(fd != -1);
97 assert(buf_ != NULL);
98 assert(count > (size_t) 0U);
100 return -1;
103 ssize_t
104 safe_read_partial(const int fd, void * const buf_, const size_t max_count)
106 assert(fd != -1);
107 assert(buf_ != NULL);
108 assert(max_count > (size_t) 0U);
110 return -1;
113 #endif