Implement mingw_stat.
[polipo.git] / mingw.c
blob357af36f125423270097930845572f39643aa54b
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 assert(rc == 0);
256 return 0;
259 static void
260 set_errno(int winsock_err)
262 switch(winsock_err) {
263 case WSAEWOULDBLOCK:
264 errno = EAGAIN;
265 break;
266 default:
267 errno = winsock_err;
268 break;
272 int mingw_write_socket(SOCKET fd, void *buf, int n)
274 int rc = send(fd, buf, n, 0);
275 if(rc == SOCKET_ERROR) {
276 set_errno(WSAGetLastError());
278 return rc;
281 int mingw_read_socket(SOCKET fd, void *buf, int n)
283 int rc = recv(fd, buf, n, 0);
284 if(rc == SOCKET_ERROR) {
285 set_errno(WSAGetLastError());
287 return rc;
292 * Set the "non-blocking" flag on socket fd to the value specified by
293 * the second argument (i.e. if the nonblocking argument is non-zero, the
294 * socket is set to non-blocking mode). Zero is returned if the operation
295 * is successful, other -1.
298 mingw_setnonblocking(SOCKET fd, int nonblocking)
300 int rc;
302 unsigned long mode = 1;
303 rc = ioctlsocket(fd, FIONBIO, &mode);
304 if(rc != 0) {
305 set_errno(WSAGetLastError());
307 return (rc == 0 ? 0 : -1);
311 * A wrapper around the socket() function. The purpose of this wrapper
312 * is to ensure that the global errno symbol is set if an error occurs,
313 * even if we are using winsock.
315 SOCKET
316 mingw_socket(int domain, int type, int protocol)
318 SOCKET fd = socket(domain, type, protocol);
319 if(fd == INVALID_SOCKET) {
320 set_errno(WSAGetLastError());
322 return fd;
325 static void
326 set_connect_errno(int winsock_err)
328 switch(winsock_err) {
329 case WSAEINVAL:
330 case WSAEALREADY:
331 case WSAEWOULDBLOCK:
332 errno = EINPROGRESS;
333 break;
334 default:
335 errno = winsock_err;
336 break;
341 * A wrapper around the connect() function. The purpose of this wrapper
342 * is to ensure that the global errno symbol is set if an error occurs,
343 * even if we are using winsock.
346 mingw_connect(SOCKET fd, struct sockaddr *addr, socklen_t addr_len)
348 int rc = connect(fd, addr, addr_len);
349 assert(rc == 0 || rc == SOCKET_ERROR);
350 if(rc == SOCKET_ERROR) {
351 set_connect_errno(WSAGetLastError());
353 return rc;
357 * A wrapper around the accept() function. The purpose of this wrapper
358 * is to ensure that the global errno symbol is set if an error occurs,
359 * even if we are using winsock.
361 SOCKET
362 mingw_accept(SOCKET fd, struct sockaddr *addr, socklen_t *addr_len)
364 SOCKET newfd = accept(fd, addr, addr_len);
365 if(newfd == INVALID_SOCKET) {
366 set_errno(WSAGetLastError());
367 newfd = -1;
369 return newfd;
373 * A wrapper around the shutdown() function. The purpose of this wrapper
374 * is to ensure that the global errno symbol is set if an error occurs,
375 * even if we are using winsock.
378 mingw_shutdown(SOCKET fd, int mode)
380 int rc = shutdown(fd, mode);
381 assert(rc == 0 || rc == SOCKET_ERROR);
382 if(rc == SOCKET_ERROR) {
383 set_errno(WSAGetLastError());
385 return rc;
389 * A wrapper around the getpeername() function. The purpose of this wrapper
390 * is to ensure that the global errno symbol is set if an error occurs,
391 * even if we are using winsock.
394 mingw_getpeername(SOCKET fd, struct sockaddr *name, socklen_t *namelen)
396 int rc = getpeername(fd, name, namelen);
397 assert(rc == 0 || rc == SOCKET_ERROR);
398 if(rc == SOCKET_ERROR) {
399 set_errno(WSAGetLastError());
401 return rc;
404 /* Stat doesn't work on directories if the name ends in a slash. */
407 mingw_stat(const char *filename, struct stat *ss)
409 int len, rc, saved_errno;
410 char *noslash;
412 len = strlen(filename);
413 if(len <= 1 || filename[len - 1] != '/')
414 return stat(filename, ss);
416 noslash = malloc(len);
417 if(noslash == NULL)
418 return -1;
420 memcpy(noslash, filename, len - 1);
421 noslash[len - 1] = '\0';
423 rc = stat(noslash, ss);
424 saved_errno = errno;
425 free(noslash);
426 errno = saved_errno;
427 return rc;
429 #endif /* #ifdef MINGW */
431 #ifndef HAVE_READV_WRITEV
434 polipo_writev(int fd, const struct iovec *vector, int count)
436 int rc; /* Return Code */
437 if(count == 1) {
438 rc = WRITE(fd, vector->iov_base, vector->iov_len);
439 } else {
440 int n = 0; /* Total bytes to write */
441 char *buf = 0; /* Buffer to copy to before writing */
442 int i; /* Counter var for looping over vector[] */
443 int offset = 0; /* Offset for copying to buf */
445 /* Figure out the required buffer size */
446 for(i = 0; i < count; i++) {
447 n += vector[i].iov_len;
450 /* Allocate the buffer. If the allocation fails, bail out */
451 buf = malloc(n);
452 if(!buf) {
453 errno = ENOMEM;
454 return -1;
457 /* Copy the contents of the vector array to the buffer */
458 for(i = 0; i < count; i++) {
459 memcpy(&buf[offset], vector[i].iov_base, vector[i].iov_len);
460 offset += vector[i].iov_len;
462 assert(offset == n);
464 /* Write the entire buffer to the socket and free the allocation */
465 rc = WRITE(fd, buf, n);
466 free(buf);
468 return rc;
472 polipo_readv(int fd, const struct iovec *vector, int count)
474 int ret = 0; /* Return value */
475 int i;
476 for(i = 0; i < count; i++) {
477 int n = vector[i].iov_len;
478 int rc = READ(fd, vector[i].iov_base, n);
479 if(rc == n) {
480 ret += rc;
481 } else {
482 if(rc < 0) {
483 ret = (ret == 0 ? rc : ret);
484 } else {
485 ret += rc;
487 break;
490 return ret;
492 #endif