Now that we have Subversion's file renaming ability, it's time at
[u/mdw/putty] / windows / winnet.c
1 /*
2 * Windows networking abstraction.
3 *
4 * Due to this clean abstraction it was possible
5 * to easily implement IPv6 support :)
6 *
7 * IPv6 patch 1 (27 October 2000) Jeroen Massar <jeroen@unfix.org>
8 * - Preliminary hacked IPv6 support.
9 * - Connecting to IPv6 address (eg fec0:4242:4242:100:2d0:b7ff:fe8f:5d42) works.
10 * - Connecting to IPv6 hostname (eg heaven.ipv6.unfix.org) works.
11 * - Compiles as either IPv4 or IPv6.
12 *
13 * IPv6 patch 2 (29 October 2000) Jeroen Massar <jeroen@unfix.org>
14 * - When compiled as IPv6 it also allows connecting to IPv4 hosts.
15 * - Added some more documentation.
16 *
17 * IPv6 patch 3 (18 November 2000) Jeroen Massar <jeroen@unfix.org>
18 * - It now supports dynamically loading the IPv6 resolver dll's.
19 * This way we should be able to distribute one (1) binary
20 * which supports both IPv4 and IPv6.
21 * - getaddrinfo() and getnameinfo() are loaded dynamicaly if possible.
22 * - in6addr_any is defined in this file so we don't need to link to wship6.lib
23 * - The patch is now more unified so that we can still
24 * remove all IPv6 support by undef'ing IPV6.
25 * But where it fallsback to IPv4 it uses the IPv4 code which is already in place...
26 * - Canonical name resolving works.
27 *
28 * IPv6 patch 4 (07 January 2001) Jeroen Massar <jeroen@unfix.org>
29 * - patch against CVS of today, will be submitted to the bugs list
30 * as a 'cvs diff -u' on Simon's request...
31 *
32 */
33
34 /*
35 * Define IPV6 to have IPv6 on-the-fly-loading support.
36 * This means that one doesn't have to have an IPv6 stack to use it.
37 * But if an IPv6 stack is found it is used with a fallback to IPv4.
38 */
39 /* #define IPV6 1 */
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <assert.h>
44
45 #define DEFINE_PLUG_METHOD_MACROS
46 #include "putty.h"
47 #include "network.h"
48 #include "tree234.h"
49
50 #include <ws2tcpip.h>
51 #ifdef IPV6
52 #include <tpipv6.h>
53 #endif
54
55 #define ipv4_is_loopback(addr) \
56 ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
57
58 struct Socket_tag {
59 const struct socket_function_table *fn;
60 /* the above variable absolutely *must* be the first in this structure */
61 char *error;
62 SOCKET s;
63 Plug plug;
64 void *private_ptr;
65 bufchain output_data;
66 int connected;
67 int writable;
68 int frozen; /* this causes readability notifications to be ignored */
69 int frozen_readable; /* this means we missed at least one readability
70 * notification while we were frozen */
71 int localhost_only; /* for listening sockets */
72 char oobdata[1];
73 int sending_oob;
74 int oobinline;
75 int pending_error; /* in case send() returns error */
76 };
77
78 /*
79 * We used to typedef struct Socket_tag *Socket.
80 *
81 * Since we have made the networking abstraction slightly more
82 * abstract, Socket no longer means a tcp socket (it could mean
83 * an ssl socket). So now we must use Actual_Socket when we know
84 * we are talking about a tcp socket.
85 */
86 typedef struct Socket_tag *Actual_Socket;
87
88 struct SockAddr_tag {
89 char *error;
90 /*
91 * Which address family this address belongs to. AF_INET for
92 * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
93 * resolution has not been done and a simple host name is held
94 * in this SockAddr structure.
95 */
96 int family;
97 unsigned long address; /* Address IPv4 style. */
98 #ifdef IPV6
99 struct addrinfo *ai; /* Address IPv6 style. */
100 #endif
101 char hostname[512]; /* Store an unresolved host name. */
102 };
103
104 static tree234 *sktree;
105
106 static int cmpfortree(void *av, void *bv)
107 {
108 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
109 unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
110 if (as < bs)
111 return -1;
112 if (as > bs)
113 return +1;
114 return 0;
115 }
116
117 static int cmpforsearch(void *av, void *bv)
118 {
119 Actual_Socket b = (Actual_Socket) bv;
120 unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
121 if (as < bs)
122 return -1;
123 if (as > bs)
124 return +1;
125 return 0;
126 }
127
128 #define NOTHING
129 #define DECL_WINSOCK_FUNCTION(linkage, rettype, name, params) \
130 typedef rettype (WINAPI *t_##name) params; \
131 linkage t_##name p_##name
132 #define GET_WINSOCK_FUNCTION(name) \
133 p_##name = (t_##name) GetProcAddress(winsock_module, #name)
134
135 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAAsyncSelect,
136 (SOCKET, HWND, u_int, long));
137 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEventSelect, (SOCKET, WSAEVENT, long));
138 DECL_WINSOCK_FUNCTION(NOTHING, int, select,
139 (int, fd_set FAR *, fd_set FAR *,
140 fd_set FAR *, const struct timeval FAR *));
141 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAGetLastError, (void));
142 DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEnumNetworkEvents,
143 (SOCKET, WSAEVENT, LPWSANETWORKEVENTS));
144 DECL_WINSOCK_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
145 DECL_WINSOCK_FUNCTION(static, int, WSACleanup, (void));
146 DECL_WINSOCK_FUNCTION(static, int, closesocket, (SOCKET));
147 DECL_WINSOCK_FUNCTION(static, u_long, ntohl, (u_long));
148 DECL_WINSOCK_FUNCTION(static, u_long, htonl, (u_long));
149 DECL_WINSOCK_FUNCTION(static, u_short, htons, (u_short));
150 DECL_WINSOCK_FUNCTION(static, u_short, ntohs, (u_short));
151 DECL_WINSOCK_FUNCTION(static, struct hostent FAR *, gethostbyname,
152 (const char FAR *));
153 DECL_WINSOCK_FUNCTION(static, struct servent FAR *, getservbyname,
154 (const char FAR *, const char FAR *));
155 DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr, (const char FAR *));
156 DECL_WINSOCK_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
157 DECL_WINSOCK_FUNCTION(static, int, connect,
158 (SOCKET, const struct sockaddr FAR *, int));
159 DECL_WINSOCK_FUNCTION(static, int, bind,
160 (SOCKET, const struct sockaddr FAR *, int));
161 DECL_WINSOCK_FUNCTION(static, int, setsockopt,
162 (SOCKET, int, int, const char FAR *, int));
163 DECL_WINSOCK_FUNCTION(static, SOCKET, socket, (int, int, int));
164 DECL_WINSOCK_FUNCTION(static, int, listen, (SOCKET, int));
165 DECL_WINSOCK_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
166 DECL_WINSOCK_FUNCTION(static, int, ioctlsocket,
167 (SOCKET, long, u_long FAR *));
168 DECL_WINSOCK_FUNCTION(static, SOCKET, accept,
169 (SOCKET, struct sockaddr FAR *, int FAR *));
170 DECL_WINSOCK_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
171 DECL_WINSOCK_FUNCTION(static, int, WSAIoctl,
172 (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
173 LPDWORD, LPWSAOVERLAPPED,
174 LPWSAOVERLAPPED_COMPLETION_ROUTINE));
175
176 static HMODULE winsock_module;
177
178 void sk_init(void)
179 {
180 WORD winsock_ver;
181 WSADATA wsadata;
182
183 winsock_ver = MAKEWORD(2, 0);
184 winsock_module = LoadLibrary("WS2_32.DLL");
185 if (!winsock_module) {
186 winsock_module = LoadLibrary("WSOCK32.DLL");
187 winsock_ver = MAKEWORD(1, 1);
188 }
189 if (!winsock_module)
190 fatalbox("Unable to load any WinSock library");
191
192 GET_WINSOCK_FUNCTION(WSAAsyncSelect);
193 GET_WINSOCK_FUNCTION(WSAEventSelect);
194 GET_WINSOCK_FUNCTION(select);
195 GET_WINSOCK_FUNCTION(WSAGetLastError);
196 GET_WINSOCK_FUNCTION(WSAEnumNetworkEvents);
197 GET_WINSOCK_FUNCTION(WSAStartup);
198 GET_WINSOCK_FUNCTION(WSACleanup);
199 GET_WINSOCK_FUNCTION(closesocket);
200 GET_WINSOCK_FUNCTION(ntohl);
201 GET_WINSOCK_FUNCTION(htonl);
202 GET_WINSOCK_FUNCTION(htons);
203 GET_WINSOCK_FUNCTION(ntohs);
204 GET_WINSOCK_FUNCTION(gethostbyname);
205 GET_WINSOCK_FUNCTION(getservbyname);
206 GET_WINSOCK_FUNCTION(inet_addr);
207 GET_WINSOCK_FUNCTION(inet_ntoa);
208 GET_WINSOCK_FUNCTION(connect);
209 GET_WINSOCK_FUNCTION(bind);
210 GET_WINSOCK_FUNCTION(setsockopt);
211 GET_WINSOCK_FUNCTION(socket);
212 GET_WINSOCK_FUNCTION(listen);
213 GET_WINSOCK_FUNCTION(send);
214 GET_WINSOCK_FUNCTION(ioctlsocket);
215 GET_WINSOCK_FUNCTION(accept);
216 GET_WINSOCK_FUNCTION(recv);
217 GET_WINSOCK_FUNCTION(WSAIoctl);
218
219 if (p_WSAStartup(winsock_ver, &wsadata)) {
220 fatalbox("Unable to initialise WinSock");
221 }
222 if (LOBYTE(wsadata.wVersion) != LOBYTE(winsock_ver)) {
223 p_WSACleanup();
224 fatalbox("WinSock version is incompatible with %d.%d",
225 LOBYTE(winsock_ver), HIBYTE(winsock_ver));
226 }
227
228 sktree = newtree234(cmpfortree);
229 }
230
231 void sk_cleanup(void)
232 {
233 Actual_Socket s;
234 int i;
235
236 if (sktree) {
237 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
238 p_closesocket(s->s);
239 }
240 freetree234(sktree);
241 sktree = NULL;
242 }
243
244 p_WSACleanup();
245 if (winsock_module)
246 FreeLibrary(winsock_module);
247 }
248
249 char *winsock_error_string(int error)
250 {
251 switch (error) {
252 case WSAEACCES:
253 return "Network error: Permission denied";
254 case WSAEADDRINUSE:
255 return "Network error: Address already in use";
256 case WSAEADDRNOTAVAIL:
257 return "Network error: Cannot assign requested address";
258 case WSAEAFNOSUPPORT:
259 return
260 "Network error: Address family not supported by protocol family";
261 case WSAEALREADY:
262 return "Network error: Operation already in progress";
263 case WSAECONNABORTED:
264 return "Network error: Software caused connection abort";
265 case WSAECONNREFUSED:
266 return "Network error: Connection refused";
267 case WSAECONNRESET:
268 return "Network error: Connection reset by peer";
269 case WSAEDESTADDRREQ:
270 return "Network error: Destination address required";
271 case WSAEFAULT:
272 return "Network error: Bad address";
273 case WSAEHOSTDOWN:
274 return "Network error: Host is down";
275 case WSAEHOSTUNREACH:
276 return "Network error: No route to host";
277 case WSAEINPROGRESS:
278 return "Network error: Operation now in progress";
279 case WSAEINTR:
280 return "Network error: Interrupted function call";
281 case WSAEINVAL:
282 return "Network error: Invalid argument";
283 case WSAEISCONN:
284 return "Network error: Socket is already connected";
285 case WSAEMFILE:
286 return "Network error: Too many open files";
287 case WSAEMSGSIZE:
288 return "Network error: Message too long";
289 case WSAENETDOWN:
290 return "Network error: Network is down";
291 case WSAENETRESET:
292 return "Network error: Network dropped connection on reset";
293 case WSAENETUNREACH:
294 return "Network error: Network is unreachable";
295 case WSAENOBUFS:
296 return "Network error: No buffer space available";
297 case WSAENOPROTOOPT:
298 return "Network error: Bad protocol option";
299 case WSAENOTCONN:
300 return "Network error: Socket is not connected";
301 case WSAENOTSOCK:
302 return "Network error: Socket operation on non-socket";
303 case WSAEOPNOTSUPP:
304 return "Network error: Operation not supported";
305 case WSAEPFNOSUPPORT:
306 return "Network error: Protocol family not supported";
307 case WSAEPROCLIM:
308 return "Network error: Too many processes";
309 case WSAEPROTONOSUPPORT:
310 return "Network error: Protocol not supported";
311 case WSAEPROTOTYPE:
312 return "Network error: Protocol wrong type for socket";
313 case WSAESHUTDOWN:
314 return "Network error: Cannot send after socket shutdown";
315 case WSAESOCKTNOSUPPORT:
316 return "Network error: Socket type not supported";
317 case WSAETIMEDOUT:
318 return "Network error: Connection timed out";
319 case WSAEWOULDBLOCK:
320 return "Network error: Resource temporarily unavailable";
321 case WSAEDISCON:
322 return "Network error: Graceful shutdown in progress";
323 default:
324 return "Unknown network error";
325 }
326 }
327
328 SockAddr sk_namelookup(const char *host, char **canonicalname)
329 {
330 SockAddr ret = snew(struct SockAddr_tag);
331 unsigned long a;
332 struct hostent *h = NULL;
333 char realhost[8192];
334
335 /* Clear the structure and default to IPv4. */
336 memset(ret, 0, sizeof(struct SockAddr_tag));
337 ret->family = 0; /* We set this one when we have resolved the host. */
338 *realhost = '\0';
339
340 if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
341 #ifdef IPV6
342
343 /* Try to get the getaddrinfo() function from wship6.dll */
344 /* This way one doesn't need to have IPv6 dll's to use PuTTY and
345 * it will fallback to IPv4. */
346 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
347 const char *servname,
348 const struct addrinfo *
349 hints,
350 struct addrinfo ** res);
351 FGETADDRINFO fGetAddrInfo = NULL;
352
353 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
354 if (dllWSHIP6)
355 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
356 "getaddrinfo");
357
358 /*
359 * Use fGetAddrInfo when it's available (which usually also
360 * means IPv6 is installed...)
361 */
362 if (fGetAddrInfo) {
363 /*debug(("Resolving \"%s\" with getaddrinfo() (IPv4+IPv6 capable)...\n", host)); */
364 if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
365 ret->family = ret->ai->ai_family;
366 } else
367 #endif
368 {
369 /*
370 * Otherwise use the IPv4-only gethostbyname...
371 * (NOTE: we don't use gethostbyname as a
372 * fallback!)
373 */
374 if (ret->family == 0) {
375 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
376 if ( (h = p_gethostbyname(host)) )
377 ret->family = AF_INET;
378 }
379 }
380 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
381
382 if (ret->family == 0) {
383 DWORD err = p_WSAGetLastError();
384 ret->error = (err == WSAENETDOWN ? "Network is down" :
385 err ==
386 WSAHOST_NOT_FOUND ? "Host does not exist" : err
387 == WSATRY_AGAIN ? "Host not found" :
388 #ifdef IPV6
389 fGetAddrInfo ? "getaddrinfo: unknown error" :
390 #endif
391 "gethostbyname: unknown error");
392 #ifdef DEBUG
393 {
394 LPVOID lpMsgBuf;
395 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
396 FORMAT_MESSAGE_FROM_SYSTEM |
397 FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
398 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
399 (LPTSTR) & lpMsgBuf, 0, NULL);
400 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
401 /* Free the buffer. */
402 LocalFree(lpMsgBuf);
403 }
404 #endif
405 } else {
406 ret->error = NULL;
407
408 #ifdef IPV6
409 /* If we got an address info use that... */
410 if (ret->ai) {
411 typedef int (CALLBACK * FGETNAMEINFO)
412 (const struct sockaddr FAR * sa, socklen_t salen,
413 char FAR * host, size_t hostlen, char FAR * serv,
414 size_t servlen, int flags);
415 FGETNAMEINFO fGetNameInfo = NULL;
416
417 /* Are we in IPv4 fallback mode? */
418 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
419 if (ret->family == AF_INET)
420 memcpy(&a,
421 (char *) &((SOCKADDR_IN *) ret->ai->
422 ai_addr)->sin_addr, sizeof(a));
423
424 /* Now let's find that canonicalname... */
425 if ((dllWSHIP6)
426 && (fGetNameInfo =
427 (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
428 "getnameinfo"))) {
429 if (fGetNameInfo
430 ((struct sockaddr *) ret->ai->ai_addr,
431 ret->family ==
432 AF_INET ? sizeof(SOCKADDR_IN) :
433 sizeof(SOCKADDR_IN6), realhost,
434 sizeof(realhost), NULL, 0, 0) != 0) {
435 strncpy(realhost, host, sizeof(realhost));
436 }
437 }
438 }
439 /* We used the IPv4-only gethostbyname()... */
440 else
441 #endif
442 {
443 memcpy(&a, h->h_addr, sizeof(a));
444 /* This way we are always sure the h->h_name is valid :) */
445 strncpy(realhost, h->h_name, sizeof(realhost));
446 }
447 }
448 #ifdef IPV6
449 FreeLibrary(dllWSHIP6);
450 #endif
451 } else {
452 /*
453 * This must be a numeric IPv4 address because it caused a
454 * success return from inet_addr.
455 */
456 ret->family = AF_INET;
457 strncpy(realhost, host, sizeof(realhost));
458 }
459 ret->address = p_ntohl(a);
460 realhost[lenof(realhost)-1] = '\0';
461 *canonicalname = snewn(1+strlen(realhost), char);
462 strcpy(*canonicalname, realhost);
463 return ret;
464 }
465
466 SockAddr sk_nonamelookup(const char *host)
467 {
468 SockAddr ret = snew(struct SockAddr_tag);
469 ret->error = NULL;
470 ret->family = AF_UNSPEC;
471 strncpy(ret->hostname, host, lenof(ret->hostname));
472 ret->hostname[lenof(ret->hostname)-1] = '\0';
473 return ret;
474 }
475
476 void sk_getaddr(SockAddr addr, char *buf, int buflen)
477 {
478 #ifdef IPV6
479 if (addr->family == AF_INET6) {
480 FIXME; /* I don't know how to get a text form of an IPv6 address. */
481 } else
482 #endif
483 if (addr->family == AF_INET) {
484 struct in_addr a;
485 a.s_addr = p_htonl(addr->address);
486 strncpy(buf, p_inet_ntoa(a), buflen);
487 buf[buflen-1] = '\0';
488 } else {
489 assert(addr->family == AF_UNSPEC);
490 strncpy(buf, addr->hostname, buflen);
491 buf[buflen-1] = '\0';
492 }
493 }
494
495 int sk_hostname_is_local(char *name)
496 {
497 return !strcmp(name, "localhost");
498 }
499
500 static INTERFACE_INFO local_interfaces[16];
501 static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
502
503 static int ipv4_is_local_addr(struct in_addr addr)
504 {
505 if (ipv4_is_loopback(addr))
506 return 1; /* loopback addresses are local */
507 if (!n_local_interfaces) {
508 SOCKET s = p_socket(AF_INET, SOCK_DGRAM, 0);
509 DWORD retbytes;
510
511 if (p_WSAIoctl &&
512 p_WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0,
513 local_interfaces, sizeof(local_interfaces),
514 &retbytes, NULL, NULL) == 0)
515 n_local_interfaces = retbytes / sizeof(INTERFACE_INFO);
516 else
517 logevent(NULL, "Unable to get list of local IP addresses");
518 }
519 if (n_local_interfaces > 0) {
520 int i;
521 for (i = 0; i < n_local_interfaces; i++) {
522 SOCKADDR_IN *address =
523 (SOCKADDR_IN *)&local_interfaces[i].iiAddress;
524 if (address->sin_addr.s_addr == addr.s_addr)
525 return 1; /* this address is local */
526 }
527 }
528 return 0; /* this address is not local */
529 }
530
531 int sk_address_is_local(SockAddr addr)
532 {
533 #ifdef IPV6
534 if (addr->family == AF_INET6) {
535 FIXME; /* someone who can compile for IPV6 had better do this bit */
536 } else
537 #endif
538 if (addr->family == AF_INET) {
539 struct in_addr a;
540 a.s_addr = p_htonl(addr->address);
541 return ipv4_is_local_addr(a);
542 } else {
543 assert(addr->family == AF_UNSPEC);
544 return 0; /* we don't know; assume not */
545 }
546 }
547
548 int sk_addrtype(SockAddr addr)
549 {
550 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
551 #ifdef IPV6
552 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
553 #endif
554 ADDRTYPE_NAME);
555 }
556
557 void sk_addrcopy(SockAddr addr, char *buf)
558 {
559 assert(addr->family != AF_UNSPEC);
560 #ifdef IPV6
561 if (addr->family == AF_INET6) {
562 memcpy(buf, (char*) addr->ai, 16);
563 } else
564 #endif
565 if (addr->family == AF_INET) {
566 struct in_addr a;
567 a.s_addr = p_htonl(addr->address);
568 memcpy(buf, (char*) &a.s_addr, 4);
569 }
570 }
571
572 void sk_addr_free(SockAddr addr)
573 {
574 sfree(addr);
575 }
576
577 static Plug sk_tcp_plug(Socket sock, Plug p)
578 {
579 Actual_Socket s = (Actual_Socket) sock;
580 Plug ret = s->plug;
581 if (p)
582 s->plug = p;
583 return ret;
584 }
585
586 static void sk_tcp_flush(Socket s)
587 {
588 /*
589 * We send data to the socket as soon as we can anyway,
590 * so we don't need to do anything here. :-)
591 */
592 }
593
594 static void sk_tcp_close(Socket s);
595 static int sk_tcp_write(Socket s, const char *data, int len);
596 static int sk_tcp_write_oob(Socket s, const char *data, int len);
597 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
598 static void *sk_tcp_get_private_ptr(Socket s);
599 static void sk_tcp_set_frozen(Socket s, int is_frozen);
600 static const char *sk_tcp_socket_error(Socket s);
601
602 extern char *do_select(SOCKET skt, int startup);
603
604 Socket sk_register(void *sock, Plug plug)
605 {
606 static const struct socket_function_table fn_table = {
607 sk_tcp_plug,
608 sk_tcp_close,
609 sk_tcp_write,
610 sk_tcp_write_oob,
611 sk_tcp_flush,
612 sk_tcp_set_private_ptr,
613 sk_tcp_get_private_ptr,
614 sk_tcp_set_frozen,
615 sk_tcp_socket_error
616 };
617
618 DWORD err;
619 char *errstr;
620 Actual_Socket ret;
621
622 /*
623 * Create Socket structure.
624 */
625 ret = snew(struct Socket_tag);
626 ret->fn = &fn_table;
627 ret->error = NULL;
628 ret->plug = plug;
629 bufchain_init(&ret->output_data);
630 ret->writable = 1; /* to start with */
631 ret->sending_oob = 0;
632 ret->frozen = 1;
633 ret->frozen_readable = 0;
634 ret->localhost_only = 0; /* unused, but best init anyway */
635 ret->pending_error = 0;
636
637 ret->s = (SOCKET)sock;
638
639 if (ret->s == INVALID_SOCKET) {
640 err = p_WSAGetLastError();
641 ret->error = winsock_error_string(err);
642 return (Socket) ret;
643 }
644
645 ret->oobinline = 0;
646
647 /* Set up a select mechanism. This could be an AsyncSelect on a
648 * window, or an EventSelect on an event object. */
649 errstr = do_select(ret->s, 1);
650 if (errstr) {
651 ret->error = errstr;
652 return (Socket) ret;
653 }
654
655 add234(sktree, ret);
656
657 return (Socket) ret;
658 }
659
660 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
661 int nodelay, int keepalive, Plug plug)
662 {
663 static const struct socket_function_table fn_table = {
664 sk_tcp_plug,
665 sk_tcp_close,
666 sk_tcp_write,
667 sk_tcp_write_oob,
668 sk_tcp_flush,
669 sk_tcp_set_private_ptr,
670 sk_tcp_get_private_ptr,
671 sk_tcp_set_frozen,
672 sk_tcp_socket_error
673 };
674
675 SOCKET s;
676 #ifdef IPV6
677 SOCKADDR_IN6 a6;
678 #endif
679 SOCKADDR_IN a;
680 DWORD err;
681 char *errstr;
682 Actual_Socket ret;
683 short localport;
684
685 /*
686 * Create Socket structure.
687 */
688 ret = snew(struct Socket_tag);
689 ret->fn = &fn_table;
690 ret->error = NULL;
691 ret->plug = plug;
692 bufchain_init(&ret->output_data);
693 ret->connected = 0; /* to start with */
694 ret->writable = 0; /* to start with */
695 ret->sending_oob = 0;
696 ret->frozen = 0;
697 ret->frozen_readable = 0;
698 ret->localhost_only = 0; /* unused, but best init anyway */
699 ret->pending_error = 0;
700
701 /*
702 * Open socket.
703 */
704 assert(addr->family != AF_UNSPEC);
705 s = p_socket(addr->family, SOCK_STREAM, 0);
706 ret->s = s;
707
708 if (s == INVALID_SOCKET) {
709 err = p_WSAGetLastError();
710 ret->error = winsock_error_string(err);
711 return (Socket) ret;
712 }
713
714 ret->oobinline = oobinline;
715 if (oobinline) {
716 BOOL b = TRUE;
717 p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
718 }
719
720 if (nodelay) {
721 BOOL b = TRUE;
722 p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
723 }
724
725 if (keepalive) {
726 BOOL b = TRUE;
727 p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
728 }
729
730 /*
731 * Bind to local address.
732 */
733 if (privport)
734 localport = 1023; /* count from 1023 downwards */
735 else
736 localport = 0; /* just use port 0 (ie winsock picks) */
737
738 /* Loop round trying to bind */
739 while (1) {
740 int retcode;
741
742 #ifdef IPV6
743 if (addr->family == AF_INET6) {
744 memset(&a6, 0, sizeof(a6));
745 a6.sin6_family = AF_INET6;
746 /*a6.sin6_addr = in6addr_any; *//* == 0 */
747 a6.sin6_port = p_htons(localport);
748 } else
749 #endif
750 {
751 a.sin_family = AF_INET;
752 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
753 a.sin_port = p_htons(localport);
754 }
755 #ifdef IPV6
756 retcode = p_bind(s, (addr->family == AF_INET6 ?
757 (struct sockaddr *) &a6 :
758 (struct sockaddr *) &a),
759 (addr->family ==
760 AF_INET6 ? sizeof(a6) : sizeof(a)));
761 #else
762 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
763 #endif
764 if (retcode != SOCKET_ERROR) {
765 err = 0;
766 break; /* done */
767 } else {
768 err = p_WSAGetLastError();
769 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
770 break;
771 }
772
773 if (localport == 0)
774 break; /* we're only looping once */
775 localport--;
776 if (localport == 0)
777 break; /* we might have got to the end */
778 }
779
780 if (err) {
781 ret->error = winsock_error_string(err);
782 return (Socket) ret;
783 }
784
785 /*
786 * Connect to remote address.
787 */
788 #ifdef IPV6
789 if (addr->family == AF_INET6) {
790 memset(&a, 0, sizeof(a));
791 a6.sin6_family = AF_INET6;
792 a6.sin6_port = p_htons((short) port);
793 a6.sin6_addr =
794 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
795 } else
796 #endif
797 {
798 a.sin_family = AF_INET;
799 a.sin_addr.s_addr = p_htonl(addr->address);
800 a.sin_port = p_htons((short) port);
801 }
802
803 /* Set up a select mechanism. This could be an AsyncSelect on a
804 * window, or an EventSelect on an event object. */
805 errstr = do_select(s, 1);
806 if (errstr) {
807 ret->error = errstr;
808 return (Socket) ret;
809 }
810
811 if ((
812 #ifdef IPV6
813 p_connect(s, ((addr->family == AF_INET6) ?
814 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
815 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
816 #else
817 p_connect(s, (struct sockaddr *) &a, sizeof(a))
818 #endif
819 ) == SOCKET_ERROR) {
820 err = p_WSAGetLastError();
821 /*
822 * We expect a potential EWOULDBLOCK here, because the
823 * chances are the front end has done a select for
824 * FD_CONNECT, so that connect() will complete
825 * asynchronously.
826 */
827 if ( err != WSAEWOULDBLOCK ) {
828 ret->error = winsock_error_string(err);
829 return (Socket) ret;
830 }
831 } else {
832 /*
833 * If we _don't_ get EWOULDBLOCK, the connect has completed
834 * and we should set the socket as writable.
835 */
836 ret->writable = 1;
837 }
838
839 add234(sktree, ret);
840
841 /* We're done with 'addr' now. */
842 sk_addr_free(addr);
843
844 return (Socket) ret;
845 }
846
847 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
848 {
849 static const struct socket_function_table fn_table = {
850 sk_tcp_plug,
851 sk_tcp_close,
852 sk_tcp_write,
853 sk_tcp_write_oob,
854 sk_tcp_flush,
855 sk_tcp_set_private_ptr,
856 sk_tcp_get_private_ptr,
857 sk_tcp_set_frozen,
858 sk_tcp_socket_error
859 };
860
861 SOCKET s;
862 #ifdef IPV6
863 SOCKADDR_IN6 a6;
864 #endif
865 SOCKADDR_IN a;
866 DWORD err;
867 char *errstr;
868 Actual_Socket ret;
869 int retcode;
870 int on = 1;
871
872 /*
873 * Create Socket structure.
874 */
875 ret = snew(struct Socket_tag);
876 ret->fn = &fn_table;
877 ret->error = NULL;
878 ret->plug = plug;
879 bufchain_init(&ret->output_data);
880 ret->writable = 0; /* to start with */
881 ret->sending_oob = 0;
882 ret->frozen = 0;
883 ret->frozen_readable = 0;
884 ret->localhost_only = local_host_only;
885 ret->pending_error = 0;
886
887 /*
888 * Open socket.
889 */
890 s = p_socket(AF_INET, SOCK_STREAM, 0);
891 ret->s = s;
892
893 if (s == INVALID_SOCKET) {
894 err = p_WSAGetLastError();
895 ret->error = winsock_error_string(err);
896 return (Socket) ret;
897 }
898
899 ret->oobinline = 0;
900
901 p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
902
903 #ifdef IPV6
904 if (addr->family == AF_INET6) {
905 memset(&a6, 0, sizeof(a6));
906 a6.sin6_family = AF_INET6;
907 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
908 * know how to do it. :-) */
909 if (local_host_only)
910 a6.sin6_addr = in6addr_loopback;
911 else
912 a6.sin6_addr = in6addr_any;
913 a6.sin6_port = p_htons(port);
914 } else
915 #endif
916 {
917 int got_addr = 0;
918 a.sin_family = AF_INET;
919
920 /*
921 * Bind to source address. First try an explicitly
922 * specified one...
923 */
924 if (srcaddr) {
925 a.sin_addr.s_addr = p_inet_addr(srcaddr);
926 if (a.sin_addr.s_addr != INADDR_NONE) {
927 /* Override localhost_only with specified listen addr. */
928 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
929 got_addr = 1;
930 }
931 }
932
933 /*
934 * ... and failing that, go with one of the standard ones.
935 */
936 if (!got_addr) {
937 if (local_host_only)
938 a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
939 else
940 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
941 }
942
943 a.sin_port = p_htons((short)port);
944 }
945 #ifdef IPV6
946 retcode = p_bind(s, (addr->family == AF_INET6 ?
947 (struct sockaddr *) &a6 :
948 (struct sockaddr *) &a),
949 (addr->family ==
950 AF_INET6 ? sizeof(a6) : sizeof(a)));
951 #else
952 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
953 #endif
954 if (retcode != SOCKET_ERROR) {
955 err = 0;
956 } else {
957 err = p_WSAGetLastError();
958 }
959
960 if (err) {
961 ret->error = winsock_error_string(err);
962 return (Socket) ret;
963 }
964
965
966 if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
967 p_closesocket(s);
968 ret->error = winsock_error_string(err);
969 return (Socket) ret;
970 }
971
972 /* Set up a select mechanism. This could be an AsyncSelect on a
973 * window, or an EventSelect on an event object. */
974 errstr = do_select(s, 1);
975 if (errstr) {
976 ret->error = errstr;
977 return (Socket) ret;
978 }
979
980 add234(sktree, ret);
981
982 return (Socket) ret;
983 }
984
985 static void sk_tcp_close(Socket sock)
986 {
987 extern char *do_select(SOCKET skt, int startup);
988 Actual_Socket s = (Actual_Socket) sock;
989
990 del234(sktree, s);
991 do_select(s->s, 0);
992 p_closesocket(s->s);
993 sfree(s);
994 }
995
996 /*
997 * The function which tries to send on a socket once it's deemed
998 * writable.
999 */
1000 void try_send(Actual_Socket s)
1001 {
1002 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1003 int nsent;
1004 DWORD err;
1005 void *data;
1006 int len, urgentflag;
1007
1008 if (s->sending_oob) {
1009 urgentflag = MSG_OOB;
1010 len = s->sending_oob;
1011 data = &s->oobdata;
1012 } else {
1013 urgentflag = 0;
1014 bufchain_prefix(&s->output_data, &data, &len);
1015 }
1016 nsent = p_send(s->s, data, len, urgentflag);
1017 noise_ultralight(nsent);
1018 if (nsent <= 0) {
1019 err = (nsent < 0 ? p_WSAGetLastError() : 0);
1020 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
1021 /*
1022 * Perfectly normal: we've sent all we can for the moment.
1023 *
1024 * (Some WinSock send() implementations can return
1025 * <0 but leave no sensible error indication -
1026 * WSAGetLastError() is called but returns zero or
1027 * a small number - so we check that case and treat
1028 * it just like WSAEWOULDBLOCK.)
1029 */
1030 s->writable = FALSE;
1031 return;
1032 } else if (nsent == 0 ||
1033 err == WSAECONNABORTED || err == WSAECONNRESET) {
1034 /*
1035 * If send() returns CONNABORTED or CONNRESET, we
1036 * unfortunately can't just call plug_closing(),
1037 * because it's quite likely that we're currently
1038 * _in_ a call from the code we'd be calling back
1039 * to, so we'd have to make half the SSH code
1040 * reentrant. Instead we flag a pending error on
1041 * the socket, to be dealt with (by calling
1042 * plug_closing()) at some suitable future moment.
1043 */
1044 s->pending_error = err;
1045 return;
1046 } else {
1047 /* We're inside the Windows frontend here, so we know
1048 * that the frontend handle is unnecessary. */
1049 logevent(NULL, winsock_error_string(err));
1050 fatalbox("%s", winsock_error_string(err));
1051 }
1052 } else {
1053 if (s->sending_oob) {
1054 if (nsent < len) {
1055 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1056 s->sending_oob = len - nsent;
1057 } else {
1058 s->sending_oob = 0;
1059 }
1060 } else {
1061 bufchain_consume(&s->output_data, nsent);
1062 }
1063 }
1064 }
1065 }
1066
1067 static int sk_tcp_write(Socket sock, const char *buf, int len)
1068 {
1069 Actual_Socket s = (Actual_Socket) sock;
1070
1071 /*
1072 * Add the data to the buffer list on the socket.
1073 */
1074 bufchain_add(&s->output_data, buf, len);
1075
1076 /*
1077 * Now try sending from the start of the buffer list.
1078 */
1079 if (s->writable)
1080 try_send(s);
1081
1082 return bufchain_size(&s->output_data);
1083 }
1084
1085 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1086 {
1087 Actual_Socket s = (Actual_Socket) sock;
1088
1089 /*
1090 * Replace the buffer list on the socket with the data.
1091 */
1092 bufchain_clear(&s->output_data);
1093 assert(len <= sizeof(s->oobdata));
1094 memcpy(s->oobdata, buf, len);
1095 s->sending_oob = len;
1096
1097 /*
1098 * Now try sending from the start of the buffer list.
1099 */
1100 if (s->writable)
1101 try_send(s);
1102
1103 return s->sending_oob;
1104 }
1105
1106 int select_result(WPARAM wParam, LPARAM lParam)
1107 {
1108 int ret, open;
1109 DWORD err;
1110 char buf[20480]; /* nice big buffer for plenty of speed */
1111 Actual_Socket s;
1112 u_long atmark;
1113
1114 /* wParam is the socket itself */
1115
1116 if (wParam == 0)
1117 return 1; /* boggle */
1118
1119 s = find234(sktree, (void *) wParam, cmpforsearch);
1120 if (!s)
1121 return 1; /* boggle */
1122
1123 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
1124 /*
1125 * An error has occurred on this socket. Pass it to the
1126 * plug.
1127 */
1128 return plug_closing(s->plug, winsock_error_string(err), err, 0);
1129 }
1130
1131 noise_ultralight(lParam);
1132
1133 switch (WSAGETSELECTEVENT(lParam)) {
1134 case FD_CONNECT:
1135 s->connected = s->writable = 1;
1136 break;
1137 case FD_READ:
1138 /* In the case the socket is still frozen, we don't even bother */
1139 if (s->frozen) {
1140 s->frozen_readable = 1;
1141 break;
1142 }
1143
1144 /*
1145 * We have received data on the socket. For an oobinline
1146 * socket, this might be data _before_ an urgent pointer,
1147 * in which case we send it to the back end with type==1
1148 * (data prior to urgent).
1149 */
1150 if (s->oobinline) {
1151 atmark = 1;
1152 p_ioctlsocket(s->s, SIOCATMARK, &atmark);
1153 /*
1154 * Avoid checking the return value from ioctlsocket(),
1155 * on the grounds that some WinSock wrappers don't
1156 * support it. If it does nothing, we get atmark==1,
1157 * which is equivalent to `no OOB pending', so the
1158 * effect will be to non-OOB-ify any OOB data.
1159 */
1160 } else
1161 atmark = 1;
1162
1163 ret = p_recv(s->s, buf, sizeof(buf), 0);
1164 noise_ultralight(ret);
1165 if (ret < 0) {
1166 err = p_WSAGetLastError();
1167 if (err == WSAEWOULDBLOCK) {
1168 break;
1169 }
1170 }
1171 if (ret < 0) {
1172 return plug_closing(s->plug, winsock_error_string(err), err,
1173 0);
1174 } else if (0 == ret) {
1175 return plug_closing(s->plug, NULL, 0, 0);
1176 } else {
1177 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1178 }
1179 break;
1180 case FD_OOB:
1181 /*
1182 * This will only happen on a non-oobinline socket. It
1183 * indicates that we can immediately perform an OOB read
1184 * and get back OOB data, which we will send to the back
1185 * end with type==2 (urgent data).
1186 */
1187 ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
1188 noise_ultralight(ret);
1189 if (ret <= 0) {
1190 char *str = (ret == 0 ? "Internal networking trouble" :
1191 winsock_error_string(p_WSAGetLastError()));
1192 /* We're inside the Windows frontend here, so we know
1193 * that the frontend handle is unnecessary. */
1194 logevent(NULL, str);
1195 fatalbox("%s", str);
1196 } else {
1197 return plug_receive(s->plug, 2, buf, ret);
1198 }
1199 break;
1200 case FD_WRITE:
1201 {
1202 int bufsize_before, bufsize_after;
1203 s->writable = 1;
1204 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1205 try_send(s);
1206 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1207 if (bufsize_after < bufsize_before)
1208 plug_sent(s->plug, bufsize_after);
1209 }
1210 break;
1211 case FD_CLOSE:
1212 /* Signal a close on the socket. First read any outstanding data. */
1213 open = 1;
1214 do {
1215 ret = p_recv(s->s, buf, sizeof(buf), 0);
1216 if (ret < 0) {
1217 err = p_WSAGetLastError();
1218 if (err == WSAEWOULDBLOCK)
1219 break;
1220 return plug_closing(s->plug, winsock_error_string(err),
1221 err, 0);
1222 } else {
1223 if (ret)
1224 open &= plug_receive(s->plug, 0, buf, ret);
1225 else
1226 open &= plug_closing(s->plug, NULL, 0, 0);
1227 }
1228 } while (ret > 0);
1229 return open;
1230 case FD_ACCEPT:
1231 {
1232 struct sockaddr_in isa;
1233 int addrlen = sizeof(struct sockaddr_in);
1234 SOCKET t; /* socket of connection */
1235
1236 memset(&isa, 0, sizeof(struct sockaddr_in));
1237 err = 0;
1238 t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
1239 if (t == INVALID_SOCKET)
1240 {
1241 err = p_WSAGetLastError();
1242 if (err == WSATRY_AGAIN)
1243 break;
1244 }
1245
1246 if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr)) {
1247 p_closesocket(t); /* dodgy WinSock let nonlocal through */
1248 } else if (plug_accepting(s->plug, (void*)t)) {
1249 p_closesocket(t); /* denied or error */
1250 }
1251 }
1252 }
1253
1254 return 1;
1255 }
1256
1257 /*
1258 * Deal with socket errors detected in try_send().
1259 */
1260 void net_pending_errors(void)
1261 {
1262 int i;
1263 Actual_Socket s;
1264
1265 /*
1266 * This might be a fiddly business, because it's just possible
1267 * that handling a pending error on one socket might cause
1268 * others to be closed. (I can't think of any reason this might
1269 * happen in current SSH implementation, but to maintain
1270 * generality of this network layer I'll assume the worst.)
1271 *
1272 * So what we'll do is search the socket list for _one_ socket
1273 * with a pending error, and then handle it, and then search
1274 * the list again _from the beginning_. Repeat until we make a
1275 * pass with no socket errors present. That way we are
1276 * protected against the socket list changing under our feet.
1277 */
1278
1279 do {
1280 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1281 if (s->pending_error) {
1282 /*
1283 * An error has occurred on this socket. Pass it to the
1284 * plug.
1285 */
1286 plug_closing(s->plug,
1287 winsock_error_string(s->pending_error),
1288 s->pending_error, 0);
1289 break;
1290 }
1291 }
1292 } while (s);
1293 }
1294
1295 /*
1296 * Each socket abstraction contains a `void *' private field in
1297 * which the client can keep state.
1298 */
1299 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1300 {
1301 Actual_Socket s = (Actual_Socket) sock;
1302 s->private_ptr = ptr;
1303 }
1304
1305 static void *sk_tcp_get_private_ptr(Socket sock)
1306 {
1307 Actual_Socket s = (Actual_Socket) sock;
1308 return s->private_ptr;
1309 }
1310
1311 /*
1312 * Special error values are returned from sk_namelookup and sk_new
1313 * if there's a problem. These functions extract an error message,
1314 * or return NULL if there's no problem.
1315 */
1316 const char *sk_addr_error(SockAddr addr)
1317 {
1318 return addr->error;
1319 }
1320 static const char *sk_tcp_socket_error(Socket sock)
1321 {
1322 Actual_Socket s = (Actual_Socket) sock;
1323 return s->error;
1324 }
1325
1326 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1327 {
1328 Actual_Socket s = (Actual_Socket) sock;
1329 if (s->frozen == is_frozen)
1330 return;
1331 s->frozen = is_frozen;
1332 if (!is_frozen && s->frozen_readable) {
1333 char c;
1334 p_recv(s->s, &c, 1, MSG_PEEK);
1335 }
1336 s->frozen_readable = 0;
1337 }
1338
1339 /*
1340 * For Plink: enumerate all sockets currently active.
1341 */
1342 SOCKET first_socket(int *state)
1343 {
1344 Actual_Socket s;
1345 *state = 0;
1346 s = index234(sktree, (*state)++);
1347 return s ? s->s : INVALID_SOCKET;
1348 }
1349
1350 SOCKET next_socket(int *state)
1351 {
1352 Actual_Socket s = index234(sktree, (*state)++);
1353 return s ? s->s : INVALID_SOCKET;
1354 }
1355
1356 int net_service_lookup(char *service)
1357 {
1358 struct servent *se;
1359 se = p_getservbyname(service, NULL);
1360 if (se != NULL)
1361 return p_ntohs(se->s_port);
1362 else
1363 return 0;
1364 }
1365
1366 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1367 {
1368 SockAddr ret = snew(struct SockAddr_tag);
1369 memset(ret, 0, sizeof(struct SockAddr_tag));
1370 ret->error = "unix sockets not supported on this platform";
1371 return ret;
1372 }