Merge branch 'fleischer-dc17'
[polipo.git] / mingw.c
bloba33d2ccfc7be9c6dd13c6ea74c35e0a32a565b3c
1 /*
2 Copyright (c) 2006 by Dan Kennedy.
3 Copyright (c) 2006 by Juliusz Chroboczek.
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to deal
7 in the Software without restriction, including without limitation the rights
8 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 THE SOFTWARE.
24 #include "polipo.h"
26 #ifndef MINGW
28 static int dummy ATTRIBUTE((unused));
30 #else
32 #undef poll
33 #undef socket
34 #undef connect
35 #undef accept
36 #undef shutdown
37 #undef getpeername
38 #undef sleep
39 #undef inet_aton
40 #undef gettimeofday
41 #undef stat
43 /* Windows needs this header file for the implementation of inet_aton() */
44 #include <ctype.h>
46 /*
47 * Check whether "cp" is a valid ascii representation of an Internet address
48 * and convert to a binary address. Returns 1 if the address is valid, 0 if
49 * not. This replaces inet_addr, the return value from which cannot
50 * distinguish between failure and a local broadcast address.
52 * This implementation of the standard inet_aton() function was copied
53 * (with trivial modifications) from the OpenBSD project.
55 int
56 mingw_inet_aton(const char *cp, struct in_addr *addr)
58 register unsigned int val;
59 register int base, n;
60 register char c;
61 unsigned int parts[4];
62 register unsigned int *pp = parts;
64 assert(sizeof(val) == 4);
66 c = *cp;
67 while(1) {
69 * Collect number up to ``.''.
70 * Values are specified as for C:
71 * 0x=hex, 0=octal, isdigit=decimal.
73 if(!isdigit(c))
74 return (0);
75 val = 0; base = 10;
76 if(c == '0') {
77 c = *++cp;
78 if(c == 'x' || c == 'X')
79 base = 16, c = *++cp;
80 else
81 base = 8;
83 while(1) {
84 if(isascii(c) && isdigit(c)) {
85 val = (val * base) + (c - '0');
86 c = *++cp;
87 } else if(base == 16 && isascii(c) && isxdigit(c)) {
88 val = (val << 4) |
89 (c + 10 - (islower(c) ? 'a' : 'A'));
90 c = *++cp;
91 } else
92 break;
94 if(c == '.') {
96 * Internet format:
97 * a.b.c.d
98 * a.b.c (with c treated as 16 bits)
99 * a.b (with b treated as 24 bits)
101 if(pp >= parts + 3)
102 return (0);
103 *pp++ = val;
104 c = *++cp;
105 } else
106 break;
109 * Check for trailing characters.
111 if(c != '\0' && (!isascii(c) || !isspace(c)))
112 return (0);
114 * Concoct the address according to
115 * the number of parts specified.
117 n = pp - parts + 1;
118 switch(n) {
120 case 0:
121 return (0); /* initial nondigit */
123 case 1: /* a -- 32 bits */
124 break;
126 case 2: /* a.b -- 8.24 bits */
127 if((val > 0xffffff) || (parts[0] > 0xff))
128 return (0);
129 val |= parts[0] << 24;
130 break;
132 case 3: /* a.b.c -- 8.8.16 bits */
133 if((val > 0xffff) || (parts[0] > 0xff) || (parts[1] > 0xff))
134 return (0);
135 val |= (parts[0] << 24) | (parts[1] << 16);
136 break;
138 case 4: /* a.b.c.d -- 8.8.8.8 bits */
139 if((val > 0xff) || (parts[0] > 0xff) ||
140 (parts[1] > 0xff) || (parts[2] > 0xff))
141 return (0);
142 val |= (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8);
143 break;
145 if(addr)
146 addr->s_addr = htonl(val);
147 return (1);
150 unsigned int
151 mingw_sleep(unsigned int seconds)
153 Sleep(seconds * 1000);
154 return 0;
158 mingw_gettimeofday(struct timeval *tv, char *tz)
160 const long long EPOCHFILETIME = (116444736000000000LL);
161 FILETIME ft;
162 LARGE_INTEGER li;
163 long long t;
165 /* This implementation doesn't support the timezone parameter. That's Ok,
166 * as at present polipo always passed NULL as the second arg. We
167 * also need to make sure that we have at least 8 bytes of space to
168 * do the math in - otherwise there will be overflow errors.
170 assert(tz == NULL);
171 assert(sizeof(t) == 8);
173 if(tv) {
174 GetSystemTimeAsFileTime(&ft);
175 li.LowPart = ft.dwLowDateTime;
176 li.HighPart = ft.dwHighDateTime;
177 t = li.QuadPart; /* In 100-nanosecond intervals */
178 t -= EPOCHFILETIME; /* Offset to the Epoch time */
179 t /= 10; /* In microseconds */
180 tv->tv_sec = (long)(t / 1000000);
181 tv->tv_usec = (long)(t % 1000000);
183 return 0;
186 int mingw_poll(struct pollfd *fds, unsigned int nfds, int timo)
188 struct timeval timeout, *toptr;
189 fd_set ifds, ofds, efds, *ip, *op;
190 int i, rc;
192 /* Set up the file-descriptor sets in ifds, ofds and efds. */
193 FD_ZERO(&ifds);
194 FD_ZERO(&ofds);
195 FD_ZERO(&efds);
196 for (i = 0, op = ip = 0; i < nfds; ++i) {
197 fds[i].revents = 0;
198 if(fds[i].events & (POLLIN|POLLPRI)) {
199 ip = &ifds;
200 FD_SET(fds[i].fd, ip);
202 if(fds[i].events & POLLOUT) {
203 op = &ofds;
204 FD_SET(fds[i].fd, op);
206 FD_SET(fds[i].fd, &efds);
209 /* Set up the timeval structure for the timeout parameter */
210 if(timo < 0) {
211 toptr = 0;
212 } else {
213 toptr = &timeout;
214 timeout.tv_sec = timo / 1000;
215 timeout.tv_usec = (timo - timeout.tv_sec * 1000) * 1000;
218 #ifdef DEBUG_POLL
219 printf("Entering select() sec=%ld usec=%ld ip=%lx op=%lx\n",
220 (long)timeout.tv_sec, (long)timeout.tv_usec, (long)ip, (long)op);
221 #endif
222 rc = select(0, ip, op, &efds, toptr);
223 #ifdef DEBUG_POLL
224 printf("Exiting select rc=%d\n", rc);
225 #endif
227 if(rc <= 0)
228 return rc;
230 if(rc > 0) {
231 for (i = 0; i < nfds; ++i) {
232 int fd = fds[i].fd;
233 if(fds[i].events & (POLLIN|POLLPRI) && FD_ISSET(fd, &ifds))
234 fds[i].revents |= POLLIN;
235 if(fds[i].events & POLLOUT && FD_ISSET(fd, &ofds))
236 fds[i].revents |= POLLOUT;
237 if(FD_ISSET(fd, &efds))
238 /* Some error was detected ... should be some way to know. */
239 fds[i].revents |= POLLHUP;
240 #ifdef DEBUG_POLL
241 printf("%d %d %d revent = %x\n",
242 FD_ISSET(fd, &ifds), FD_ISSET(fd, &ofds), FD_ISSET(fd, &efds),
243 fds[i].revents
245 #endif
248 return rc;
251 int mingw_close_socket(SOCKET fd) {
252 int rc;
254 rc = closesocket(fd);
255 return 0;
258 static void
259 set_errno(int winsock_err)
261 switch(winsock_err) {
262 case WSAEWOULDBLOCK:
263 errno = EAGAIN;
264 break;
265 default:
266 errno = winsock_err;
267 break;
271 int mingw_write_socket(SOCKET fd, void *buf, int n)
273 int rc = send(fd, buf, n, 0);
274 if(rc == SOCKET_ERROR) {
275 set_errno(WSAGetLastError());
277 return rc;
280 int mingw_read_socket(SOCKET fd, void *buf, int n)
282 int rc = recv(fd, buf, n, 0);
283 if(rc == SOCKET_ERROR) {
284 set_errno(WSAGetLastError());
286 return rc;
291 * Set the "non-blocking" flag on socket fd to the value specified by
292 * the second argument (i.e. if the nonblocking argument is non-zero, the
293 * socket is set to non-blocking mode). Zero is returned if the operation
294 * is successful, other -1.
297 mingw_setnonblocking(SOCKET fd, int nonblocking)
299 int rc;
301 unsigned long mode = 1;
302 rc = ioctlsocket(fd, FIONBIO, &mode);
303 if(rc != 0) {
304 set_errno(WSAGetLastError());
306 return (rc == 0 ? 0 : -1);
310 * A wrapper around the socket() function. The purpose of this wrapper
311 * is to ensure that the global errno symbol is set if an error occurs,
312 * even if we are using winsock.
314 SOCKET
315 mingw_socket(int domain, int type, int protocol)
317 SOCKET fd = socket(domain, type, protocol);
318 if(fd == INVALID_SOCKET) {
319 set_errno(WSAGetLastError());
321 return fd;
324 static void
325 set_connect_errno(int winsock_err)
327 switch(winsock_err) {
328 case WSAEINVAL:
329 case WSAEALREADY:
330 case WSAEWOULDBLOCK:
331 errno = EINPROGRESS;
332 break;
333 default:
334 errno = winsock_err;
335 break;
340 * A wrapper around the connect() function. The purpose of this wrapper
341 * is to ensure that the global errno symbol is set if an error occurs,
342 * even if we are using winsock.
345 mingw_connect(SOCKET fd, struct sockaddr *addr, socklen_t addr_len)
347 int rc = connect(fd, addr, addr_len);
348 assert(rc == 0 || rc == SOCKET_ERROR);
349 if(rc == SOCKET_ERROR) {
350 set_connect_errno(WSAGetLastError());
352 return rc;
356 * A wrapper around the accept() function. The purpose of this wrapper
357 * is to ensure that the global errno symbol is set if an error occurs,
358 * even if we are using winsock.
360 SOCKET
361 mingw_accept(SOCKET fd, struct sockaddr *addr, socklen_t *addr_len)
363 SOCKET newfd = accept(fd, addr, addr_len);
364 if(newfd == INVALID_SOCKET) {
365 set_errno(WSAGetLastError());
366 newfd = -1;
368 return newfd;
372 * A wrapper around the shutdown() function. The purpose of this wrapper
373 * is to ensure that the global errno symbol is set if an error occurs,
374 * even if we are using winsock.
377 mingw_shutdown(SOCKET fd, int mode)
379 int rc = shutdown(fd, mode);
380 assert(rc == 0 || rc == SOCKET_ERROR);
381 if(rc == SOCKET_ERROR) {
382 set_errno(WSAGetLastError());
384 return rc;
388 * A wrapper around the getpeername() function. The purpose of this wrapper
389 * is to ensure that the global errno symbol is set if an error occurs,
390 * even if we are using winsock.
393 mingw_getpeername(SOCKET fd, struct sockaddr *name, socklen_t *namelen)
395 int rc = getpeername(fd, name, namelen);
396 assert(rc == 0 || rc == SOCKET_ERROR);
397 if(rc == SOCKET_ERROR) {
398 set_errno(WSAGetLastError());
400 return rc;
403 /* Stat doesn't work on directories if the name ends in a slash. */
406 mingw_stat(const char *filename, struct stat *ss)
408 int len, rc, saved_errno;
409 char *noslash;
411 len = strlen(filename);
412 if(len <= 1 || filename[len - 1] != '/')
413 return stat(filename, ss);
415 noslash = malloc(len);
416 if(noslash == NULL)
417 return -1;
419 memcpy(noslash, filename, len - 1);
420 noslash[len - 1] = '\0';
422 rc = stat(noslash, ss);
423 saved_errno = errno;
424 free(noslash);
425 errno = saved_errno;
426 return rc;
428 #endif /* #ifdef MINGW */
430 #ifndef HAVE_READV_WRITEV
433 polipo_writev(int fd, const struct iovec *vector, int count)
435 int rc; /* Return Code */
436 if(count == 1) {
437 rc = WRITE(fd, vector->iov_base, vector->iov_len);
438 } else {
439 int n = 0; /* Total bytes to write */
440 char *buf = 0; /* Buffer to copy to before writing */
441 int i; /* Counter var for looping over vector[] */
442 int offset = 0; /* Offset for copying to buf */
444 /* Figure out the required buffer size */
445 for(i = 0; i < count; i++) {
446 n += vector[i].iov_len;
449 /* Allocate the buffer. If the allocation fails, bail out */
450 buf = malloc(n);
451 if(!buf) {
452 errno = ENOMEM;
453 return -1;
456 /* Copy the contents of the vector array to the buffer */
457 for(i = 0; i < count; i++) {
458 memcpy(&buf[offset], vector[i].iov_base, vector[i].iov_len);
459 offset += vector[i].iov_len;
461 assert(offset == n);
463 /* Write the entire buffer to the socket and free the allocation */
464 rc = WRITE(fd, buf, n);
465 free(buf);
467 return rc;
471 polipo_readv(int fd, const struct iovec *vector, int count)
473 int ret = 0; /* Return value */
474 int i;
475 for(i = 0; i < count; i++) {
476 int n = vector[i].iov_len;
477 int rc = READ(fd, vector[i].iov_base, n);
478 if(rc == n) {
479 ret += rc;
480 } else {
481 if(rc < 0) {
482 ret = (ret == 0 ? rc : ret);
483 } else {
484 ret += rc;
486 break;
489 return ret;
491 #endif