4 * BSD socket emulation code for Winsock2
5 * File IO compatibility shims
6 * Brent Cook <bcook@openbsd.org>
9 #define NO_REDEF_POSIX_FUNCTIONS
22 posix_perror(const char *s
)
24 fprintf(stderr
, "%s: %s\n", s
, strerror(errno
));
28 posix_fopen(const char *path
, const char *mode
)
30 if (strchr(mode
, 'b') == NULL
) {
31 char *bin_mode
= NULL
;
32 if (asprintf(&bin_mode
, "%sb", mode
) == -1)
34 FILE *f
= fopen(path
, bin_mode
);
39 return fopen(path
, mode
);
43 posix_fgets(char *s
, int size
, FILE *stream
)
45 char *ret
= fgets(s
, size
, stream
);
47 size_t end
= strlen(ret
);
48 if (end
>= 2 && ret
[end
- 2] == '\r' && ret
[end
- 1] == '\n') {
57 posix_rename(const char *oldpath
, const char *newpath
)
59 return MoveFileEx(oldpath
, newpath
, MOVEFILE_REPLACE_EXISTING
) ? 0 : -1;
72 case WSANOTINITIALISED
:
106 case WSAECONNREFUSED
:
107 errno
= ECONNREFUSED
;
109 case WSAEAFNOSUPPORT
:
110 errno
= EAFNOSUPPORT
;
114 case WSAECONNABORTED
:
125 posix_connect(int sockfd
, const struct sockaddr
*addr
, socklen_t addrlen
)
127 int rc
= connect(sockfd
, addr
, addrlen
);
128 if (rc
== SOCKET_ERROR
)
129 return wsa_errno(WSAGetLastError());
136 if (closesocket(fd
) == SOCKET_ERROR
) {
137 int err
= WSAGetLastError();
138 return err
== WSAENOTSOCK
?
139 close(fd
) : wsa_errno(err
);
145 posix_read(int fd
, void *buf
, size_t count
)
147 ssize_t rc
= recv(fd
, buf
, count
, 0);
148 if (rc
== SOCKET_ERROR
) {
149 int err
= WSAGetLastError();
150 return err
== WSAENOTSOCK
?
151 read(fd
, buf
, count
) : wsa_errno(err
);
157 posix_write(int fd
, const void *buf
, size_t count
)
159 ssize_t rc
= send(fd
, buf
, count
, 0);
160 if (rc
== SOCKET_ERROR
) {
161 int err
= WSAGetLastError();
162 return err
== WSAENOTSOCK
?
163 write(fd
, buf
, count
) : wsa_errno(err
);
169 posix_getsockopt(int sockfd
, int level
, int optname
,
170 void *optval
, socklen_t
*optlen
)
172 int rc
= getsockopt(sockfd
, level
, optname
, (char *)optval
, optlen
);
173 return rc
== 0 ? 0 : wsa_errno(WSAGetLastError());
178 posix_setsockopt(int sockfd
, int level
, int optname
,
179 const void *optval
, socklen_t optlen
)
181 int rc
= setsockopt(sockfd
, level
, optname
, (char *)optval
, optlen
);
182 return rc
== 0 ? 0 : wsa_errno(WSAGetLastError());
186 int gettimeofday(struct timeval
* tp
, struct timezone
* tzp
)
189 * Note: some broken versions only have 8 trailing zero's, the correct
190 * epoch has 9 trailing zero's
192 static const uint64_t EPOCH
= ((uint64_t) 116444736000000000ULL);
194 SYSTEMTIME system_time
;
198 GetSystemTime(&system_time
);
199 SystemTimeToFileTime(&system_time
, &file_time
);
200 time
= ((uint64_t)file_time
.dwLowDateTime
);
201 time
+= ((uint64_t)file_time
.dwHighDateTime
) << 32;
203 tp
->tv_sec
= (long)((time
- EPOCH
) / 10000000L);
204 tp
->tv_usec
= (long)(system_time
.wMilliseconds
* 1000);
208 unsigned int sleep(unsigned int seconds
)
210 Sleep(seconds
* 1000);