Now that we have Subversion's file renaming ability, it's time at
[u/mdw/putty] / windows / winnet.c
CommitLineData
2f75bae1 1/*
2 * Windows networking abstraction.
c4d8e107 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 *
2f75bae1 32 */
33
c4d8e107 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
2f75bae1 41#include <stdio.h>
49bad831 42#include <stdlib.h>
5471d09a 43#include <assert.h>
2f75bae1 44
7e78000d 45#define DEFINE_PLUG_METHOD_MACROS
2f75bae1 46#include "putty.h"
47#include "network.h"
48#include "tree234.h"
49
7440fd44 50#include <ws2tcpip.h>
a143ea0a 51#ifdef IPV6
7440fd44 52#include <tpipv6.h>
53#endif
54
6ee9b735 55#define ipv4_is_loopback(addr) \
7440fd44 56 ((p_ntohl(addr.s_addr) & 0xFF000000L) == 0x7F000000L)
6ee9b735 57
2f75bae1 58struct Socket_tag {
c85623f9 59 const struct socket_function_table *fn;
7e78000d 60 /* the above variable absolutely *must* be the first in this structure */
2f75bae1 61 char *error;
62 SOCKET s;
7e78000d 63 Plug plug;
2f75bae1 64 void *private_ptr;
5471d09a 65 bufchain output_data;
3ad9d396 66 int connected;
2f75bae1 67 int writable;
5471d09a 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 */
bc4802a1 71 int localhost_only; /* for listening sockets */
5471d09a 72 char oobdata[1];
1ad4eb6f 73 int sending_oob;
4b1e8acc 74 int oobinline;
7732d38a 75 int pending_error; /* in case send() returns error */
2f75bae1 76};
77
7e78000d 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 */
86typedef struct Socket_tag *Actual_Socket;
87
2f75bae1 88struct SockAddr_tag {
89 char *error;
b7a189f3 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 */
32874aea 96 int family;
c4d8e107 97 unsigned long address; /* Address IPv4 style. */
98#ifdef IPV6
99 struct addrinfo *ai; /* Address IPv6 style. */
100#endif
b7a189f3 101 char hostname[512]; /* Store an unresolved host name. */
2f75bae1 102};
103
2f75bae1 104static tree234 *sktree;
105
32874aea 106static 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;
2f75bae1 114 return 0;
115}
116
32874aea 117static 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;
2f75bae1 125 return 0;
126}
127
7440fd44 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
135DECL_WINSOCK_FUNCTION(NOTHING, int, WSAAsyncSelect,
136 (SOCKET, HWND, u_int, long));
137DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEventSelect, (SOCKET, WSAEVENT, long));
138DECL_WINSOCK_FUNCTION(NOTHING, int, select,
139 (int, fd_set FAR *, fd_set FAR *,
140 fd_set FAR *, const struct timeval FAR *));
141DECL_WINSOCK_FUNCTION(NOTHING, int, WSAGetLastError, (void));
142DECL_WINSOCK_FUNCTION(NOTHING, int, WSAEnumNetworkEvents,
143 (SOCKET, WSAEVENT, LPWSANETWORKEVENTS));
144DECL_WINSOCK_FUNCTION(static, int, WSAStartup, (WORD, LPWSADATA));
145DECL_WINSOCK_FUNCTION(static, int, WSACleanup, (void));
146DECL_WINSOCK_FUNCTION(static, int, closesocket, (SOCKET));
147DECL_WINSOCK_FUNCTION(static, u_long, ntohl, (u_long));
148DECL_WINSOCK_FUNCTION(static, u_long, htonl, (u_long));
149DECL_WINSOCK_FUNCTION(static, u_short, htons, (u_short));
150DECL_WINSOCK_FUNCTION(static, u_short, ntohs, (u_short));
151DECL_WINSOCK_FUNCTION(static, struct hostent FAR *, gethostbyname,
152 (const char FAR *));
153DECL_WINSOCK_FUNCTION(static, struct servent FAR *, getservbyname,
154 (const char FAR *, const char FAR *));
155DECL_WINSOCK_FUNCTION(static, unsigned long, inet_addr, (const char FAR *));
156DECL_WINSOCK_FUNCTION(static, char FAR *, inet_ntoa, (struct in_addr));
157DECL_WINSOCK_FUNCTION(static, int, connect,
158 (SOCKET, const struct sockaddr FAR *, int));
159DECL_WINSOCK_FUNCTION(static, int, bind,
160 (SOCKET, const struct sockaddr FAR *, int));
161DECL_WINSOCK_FUNCTION(static, int, setsockopt,
162 (SOCKET, int, int, const char FAR *, int));
163DECL_WINSOCK_FUNCTION(static, SOCKET, socket, (int, int, int));
164DECL_WINSOCK_FUNCTION(static, int, listen, (SOCKET, int));
165DECL_WINSOCK_FUNCTION(static, int, send, (SOCKET, const char FAR *, int, int));
166DECL_WINSOCK_FUNCTION(static, int, ioctlsocket,
167 (SOCKET, long, u_long FAR *));
168DECL_WINSOCK_FUNCTION(static, SOCKET, accept,
169 (SOCKET, struct sockaddr FAR *, int FAR *));
170DECL_WINSOCK_FUNCTION(static, int, recv, (SOCKET, char FAR *, int, int));
a143ea0a 171DECL_WINSOCK_FUNCTION(static, int, WSAIoctl,
172 (SOCKET, DWORD, LPVOID, DWORD, LPVOID, DWORD,
173 LPDWORD, LPWSAOVERLAPPED,
174 LPWSAOVERLAPPED_COMPLETION_ROUTINE));
7440fd44 175
176static HMODULE winsock_module;
177
32874aea 178void sk_init(void)
179{
7440fd44 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);
a143ea0a 217 GET_WINSOCK_FUNCTION(WSAIoctl);
7440fd44 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
2f75bae1 228 sktree = newtree234(cmpfortree);
229}
230
93b581bd 231void 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++) {
7440fd44 238 p_closesocket(s->s);
93b581bd 239 }
679539d7 240 freetree234(sktree);
241 sktree = NULL;
93b581bd 242 }
7440fd44 243
244 p_WSACleanup();
245 if (winsock_module)
246 FreeLibrary(winsock_module);
93b581bd 247}
248
32874aea 249char *winsock_error_string(int error)
250{
e74fbad9 251 switch (error) {
32874aea 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";
e74fbad9 325 }
326}
327
e8fa8f62 328SockAddr sk_namelookup(const char *host, char **canonicalname)
c4d8e107 329{
3d88e64d 330 SockAddr ret = snew(struct SockAddr_tag);
2f75bae1 331 unsigned long a;
c4d8e107 332 struct hostent *h = NULL;
6e1ebb76 333 char realhost[8192];
2f75bae1 334
c4d8e107 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. */
6e1ebb76 338 *realhost = '\0';
c4d8e107 339
7440fd44 340 if ((a = p_inet_addr(host)) == (unsigned long) INADDR_NONE) {
c4d8e107 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. */
32874aea 346 typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
347 const char *servname,
348 const struct addrinfo *
349 hints,
350 struct addrinfo ** res);
c4d8e107 351 FGETADDRINFO fGetAddrInfo = NULL;
352
353 HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
354 if (dllWSHIP6)
32874aea 355 fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
356 "getaddrinfo");
c4d8e107 357
358 /*
359 * Use fGetAddrInfo when it's available (which usually also
360 * means IPv6 is installed...)
361 */
32874aea 362 if (fGetAddrInfo) {
c4d8e107 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;
32874aea 366 } else
c4d8e107 367#endif
32874aea 368 {
c4d8e107 369 /*
370 * Otherwise use the IPv4-only gethostbyname...
371 * (NOTE: we don't use gethostbyname as a
372 * fallback!)
373 */
32874aea 374 if (ret->family == 0) {
375 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
7440fd44 376 if ( (h = p_gethostbyname(host)) )
32874aea 377 ret->family = AF_INET;
378 }
c4d8e107 379 }
380 /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
381
32874aea 382 if (ret->family == 0) {
7440fd44 383 DWORD err = p_WSAGetLastError();
c4d8e107 384 ret->error = (err == WSAENETDOWN ? "Network is down" :
32874aea 385 err ==
386 WSAHOST_NOT_FOUND ? "Host does not exist" : err
387 == WSATRY_AGAIN ? "Host not found" :
c4d8e107 388#ifdef IPV6
389 fGetAddrInfo ? "getaddrinfo: unknown error" :
390#endif
391 "gethostbyname: unknown error");
392#ifdef DEBUG
393 {
394 LPVOID lpMsgBuf;
32874aea 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)); */
c4d8e107 401 /* Free the buffer. */
402 LocalFree(lpMsgBuf);
403 }
404#endif
32874aea 405 } else {
c4d8e107 406 ret->error = NULL;
407
408#ifdef IPV6
409 /* If we got an address info use that... */
32874aea 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);
c4d8e107 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)
32874aea 420 memcpy(&a,
421 (char *) &((SOCKADDR_IN *) ret->ai->
422 ai_addr)->sin_addr, sizeof(a));
c4d8e107 423
424 /* Now let's find that canonicalname... */
32874aea 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) :
6e1ebb76 433 sizeof(SOCKADDR_IN6), realhost,
434 sizeof(realhost), NULL, 0, 0) != 0) {
435 strncpy(realhost, host, sizeof(realhost));
c4d8e107 436 }
437 }
438 }
439 /* We used the IPv4-only gethostbyname()... */
440 else
c4d8e107 441#endif
32874aea 442 {
c4d8e107 443 memcpy(&a, h->h_addr, sizeof(a));
444 /* This way we are always sure the h->h_name is valid :) */
6e1ebb76 445 strncpy(realhost, h->h_name, sizeof(realhost));
c4d8e107 446 }
c4d8e107 447 }
448#ifdef IPV6
449 FreeLibrary(dllWSHIP6);
450#endif
32874aea 451 } else {
87ed061f 452 /*
453 * This must be a numeric IPv4 address because it caused a
454 * success return from inet_addr.
455 */
32874aea 456 ret->family = AF_INET;
6e1ebb76 457 strncpy(realhost, host, sizeof(realhost));
2f75bae1 458 }
7440fd44 459 ret->address = p_ntohl(a);
6e1ebb76 460 realhost[lenof(realhost)-1] = '\0';
3d88e64d 461 *canonicalname = snewn(1+strlen(realhost), char);
6e1ebb76 462 strcpy(*canonicalname, realhost);
2f75bae1 463 return ret;
464}
465
e8fa8f62 466SockAddr sk_nonamelookup(const char *host)
b7a189f3 467{
3d88e64d 468 SockAddr ret = snew(struct SockAddr_tag);
ab0873ab 469 ret->error = NULL;
b7a189f3 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
3ad9d396 476void sk_getaddr(SockAddr addr, char *buf, int buflen)
477{
478#ifdef IPV6
b7a189f3 479 if (addr->family == AF_INET6) {
480 FIXME; /* I don't know how to get a text form of an IPv6 address. */
481 } else
3ad9d396 482#endif
b7a189f3 483 if (addr->family == AF_INET) {
3ad9d396 484 struct in_addr a;
7440fd44 485 a.s_addr = p_htonl(addr->address);
486 strncpy(buf, p_inet_ntoa(a), buflen);
b7a189f3 487 buf[buflen-1] = '\0';
3ad9d396 488 } else {
b7a189f3 489 assert(addr->family == AF_UNSPEC);
490 strncpy(buf, addr->hostname, buflen);
491 buf[buflen-1] = '\0';
3ad9d396 492 }
3ad9d396 493}
494
b804e1e5 495int sk_hostname_is_local(char *name)
496{
497 return !strcmp(name, "localhost");
498}
499
a143ea0a 500static INTERFACE_INFO local_interfaces[16];
501static int n_local_interfaces; /* 0=not yet, -1=failed, >0=number */
502
503static 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
b804e1e5 531int sk_address_is_local(SockAddr addr)
532{
533#ifdef IPV6
b7a189f3 534 if (addr->family == AF_INET6) {
535 FIXME; /* someone who can compile for IPV6 had better do this bit */
536 } else
b804e1e5 537#endif
b7a189f3 538 if (addr->family == AF_INET) {
b804e1e5 539 struct in_addr a;
7440fd44 540 a.s_addr = p_htonl(addr->address);
a143ea0a 541 return ipv4_is_local_addr(a);
b804e1e5 542 } else {
b7a189f3 543 assert(addr->family == AF_UNSPEC);
544 return 0; /* we don't know; assume not */
b804e1e5 545 }
b804e1e5 546}
547
6971bbe7 548int sk_addrtype(SockAddr addr)
549{
b7a189f3 550 return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
551#ifdef IPV6
552 addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
553#endif
554 ADDRTYPE_NAME);
6971bbe7 555}
556
557void sk_addrcopy(SockAddr addr, char *buf)
558{
b7a189f3 559 assert(addr->family != AF_UNSPEC);
6971bbe7 560#ifdef IPV6
b7a189f3 561 if (addr->family == AF_INET6) {
562 memcpy(buf, (char*) addr->ai, 16);
563 } else
6971bbe7 564#endif
b7a189f3 565 if (addr->family == AF_INET) {
6971bbe7 566 struct in_addr a;
7440fd44 567 a.s_addr = p_htonl(addr->address);
96d9eb89 568 memcpy(buf, (char*) &a.s_addr, 4);
6971bbe7 569 }
6971bbe7 570}
571
32874aea 572void sk_addr_free(SockAddr addr)
573{
2f75bae1 574 sfree(addr);
575}
576
32874aea 577static Plug sk_tcp_plug(Socket sock, Plug p)
578{
7e78000d 579 Actual_Socket s = (Actual_Socket) sock;
580 Plug ret = s->plug;
32874aea 581 if (p)
582 s->plug = p;
7e78000d 583 return ret;
584}
585
32874aea 586static void sk_tcp_flush(Socket s)
587{
7e78000d 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
2d466ffd 594static void sk_tcp_close(Socket s);
e0e7dff8 595static int sk_tcp_write(Socket s, const char *data, int len);
596static int sk_tcp_write_oob(Socket s, const char *data, int len);
8eebd221 597static void sk_tcp_set_private_ptr(Socket s, void *ptr);
598static void *sk_tcp_get_private_ptr(Socket s);
599static void sk_tcp_set_frozen(Socket s, int is_frozen);
cbe2d68f 600static const char *sk_tcp_socket_error(Socket s);
7e78000d 601
d74d141c 602extern char *do_select(SOCKET skt, int startup);
603
604Socket sk_register(void *sock, Plug plug)
605{
c85623f9 606 static const struct socket_function_table fn_table = {
d74d141c 607 sk_tcp_plug,
608 sk_tcp_close,
609 sk_tcp_write,
610 sk_tcp_write_oob,
611 sk_tcp_flush,
8eebd221 612 sk_tcp_set_private_ptr,
613 sk_tcp_get_private_ptr,
614 sk_tcp_set_frozen,
d74d141c 615 sk_tcp_socket_error
616 };
617
618 DWORD err;
619 char *errstr;
620 Actual_Socket ret;
621
622 /*
623 * Create Socket structure.
624 */
3d88e64d 625 ret = snew(struct Socket_tag);
d74d141c 626 ret->fn = &fn_table;
627 ret->error = NULL;
628 ret->plug = plug;
5471d09a 629 bufchain_init(&ret->output_data);
d74d141c 630 ret->writable = 1; /* to start with */
631 ret->sending_oob = 0;
632 ret->frozen = 1;
5471d09a 633 ret->frozen_readable = 0;
bc4802a1 634 ret->localhost_only = 0; /* unused, but best init anyway */
7732d38a 635 ret->pending_error = 0;
d74d141c 636
637 ret->s = (SOCKET)sock;
638
639 if (ret->s == INVALID_SOCKET) {
7440fd44 640 err = p_WSAGetLastError();
d74d141c 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
4b1e8acc 660Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
79bf227b 661 int nodelay, int keepalive, Plug plug)
7e78000d 662{
c85623f9 663 static const struct socket_function_table fn_table = {
7e78000d 664 sk_tcp_plug,
665 sk_tcp_close,
666 sk_tcp_write,
667 sk_tcp_write_oob,
668 sk_tcp_flush,
8eebd221 669 sk_tcp_set_private_ptr,
670 sk_tcp_get_private_ptr,
671 sk_tcp_set_frozen,
7e78000d 672 sk_tcp_socket_error
673 };
674
2f75bae1 675 SOCKET s;
c4d8e107 676#ifdef IPV6
677 SOCKADDR_IN6 a6;
678#endif
2f75bae1 679 SOCKADDR_IN a;
680 DWORD err;
681 char *errstr;
7e78000d 682 Actual_Socket ret;
c91409da 683 short localport;
2f75bae1 684
685 /*
686 * Create Socket structure.
687 */
3d88e64d 688 ret = snew(struct Socket_tag);
7e78000d 689 ret->fn = &fn_table;
2f75bae1 690 ret->error = NULL;
7e78000d 691 ret->plug = plug;
5471d09a 692 bufchain_init(&ret->output_data);
3ad9d396 693 ret->connected = 0; /* to start with */
694 ret->writable = 0; /* to start with */
33232c8f 695 ret->sending_oob = 0;
d74d141c 696 ret->frozen = 0;
5471d09a 697 ret->frozen_readable = 0;
bc4802a1 698 ret->localhost_only = 0; /* unused, but best init anyway */
7732d38a 699 ret->pending_error = 0;
2f75bae1 700
701 /*
702 * Open socket.
703 */
b7a189f3 704 assert(addr->family != AF_UNSPEC);
7440fd44 705 s = p_socket(addr->family, SOCK_STREAM, 0);
2f75bae1 706 ret->s = s;
707
708 if (s == INVALID_SOCKET) {
7440fd44 709 err = p_WSAGetLastError();
32874aea 710 ret->error = winsock_error_string(err);
7e78000d 711 return (Socket) ret;
2f75bae1 712 }
4b1e8acc 713
714 ret->oobinline = oobinline;
715 if (oobinline) {
1ad4eb6f 716 BOOL b = TRUE;
7440fd44 717 p_setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
1ad4eb6f 718 }
2f75bae1 719
2184a5d9 720 if (nodelay) {
721 BOOL b = TRUE;
7440fd44 722 p_setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
2184a5d9 723 }
724
79bf227b 725 if (keepalive) {
726 BOOL b = TRUE;
727 p_setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
728 }
729
2f75bae1 730 /*
731 * Bind to local address.
732 */
c91409da 733 if (privport)
32874aea 734 localport = 1023; /* count from 1023 downwards */
c4d8e107 735 else
32874aea 736 localport = 0; /* just use port 0 (ie winsock picks) */
c91409da 737
738 /* Loop round trying to bind */
739 while (1) {
32874aea 740 int retcode;
c91409da 741
742#ifdef IPV6
32874aea 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 */
7440fd44 747 a6.sin6_port = p_htons(localport);
32874aea 748 } else
c4d8e107 749#endif
32874aea 750 {
751 a.sin_family = AF_INET;
7440fd44 752 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
753 a.sin_port = p_htons(localport);
32874aea 754 }
c4d8e107 755#ifdef IPV6
7440fd44 756 retcode = p_bind(s, (addr->family == AF_INET6 ?
32874aea 757 (struct sockaddr *) &a6 :
758 (struct sockaddr *) &a),
759 (addr->family ==
760 AF_INET6 ? sizeof(a6) : sizeof(a)));
c4d8e107 761#else
7440fd44 762 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
c4d8e107 763#endif
32874aea 764 if (retcode != SOCKET_ERROR) {
765 err = 0;
766 break; /* done */
767 } else {
7440fd44 768 err = p_WSAGetLastError();
32874aea 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 */
c91409da 778 }
779
32874aea 780 if (err) {
c4d8e107 781 ret->error = winsock_error_string(err);
7e78000d 782 return (Socket) ret;
2f75bae1 783 }
784
785 /*
786 * Connect to remote address.
787 */
c4d8e107 788#ifdef IPV6
32874aea 789 if (addr->family == AF_INET6) {
790 memset(&a, 0, sizeof(a));
c4d8e107 791 a6.sin6_family = AF_INET6;
7440fd44 792 a6.sin6_port = p_htons((short) port);
32874aea 793 a6.sin6_addr =
794 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
795 } else
c4d8e107 796#endif
32874aea 797 {
c4d8e107 798 a.sin_family = AF_INET;
7440fd44 799 a.sin_addr.s_addr = p_htonl(addr->address);
800 a.sin_port = p_htons((short) port);
c4d8e107 801 }
3ad9d396 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
32874aea 811 if ((
812#ifdef IPV6
7440fd44 813 p_connect(s, ((addr->family == AF_INET6) ?
32874aea 814 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
815 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
c4d8e107 816#else
7440fd44 817 p_connect(s, (struct sockaddr *) &a, sizeof(a))
c4d8e107 818#endif
32874aea 819 ) == SOCKET_ERROR) {
7440fd44 820 err = p_WSAGetLastError();
3ad9d396 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;
2f75bae1 837 }
838
839 add234(sktree, ret);
840
f85e6f6e 841 /* We're done with 'addr' now. */
842 sk_addr_free(addr);
843
7e78000d 844 return (Socket) ret;
2f75bae1 845}
846
6ee9b735 847Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
d74d141c 848{
c85623f9 849 static const struct socket_function_table fn_table = {
d74d141c 850 sk_tcp_plug,
851 sk_tcp_close,
852 sk_tcp_write,
853 sk_tcp_write_oob,
854 sk_tcp_flush,
8eebd221 855 sk_tcp_set_private_ptr,
856 sk_tcp_get_private_ptr,
857 sk_tcp_set_frozen,
d74d141c 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 */
3d88e64d 875 ret = snew(struct Socket_tag);
d74d141c 876 ret->fn = &fn_table;
877 ret->error = NULL;
878 ret->plug = plug;
5471d09a 879 bufchain_init(&ret->output_data);
d74d141c 880 ret->writable = 0; /* to start with */
881 ret->sending_oob = 0;
882 ret->frozen = 0;
5471d09a 883 ret->frozen_readable = 0;
bc4802a1 884 ret->localhost_only = local_host_only;
7732d38a 885 ret->pending_error = 0;
d74d141c 886
887 /*
888 * Open socket.
889 */
7440fd44 890 s = p_socket(AF_INET, SOCK_STREAM, 0);
d74d141c 891 ret->s = s;
892
893 if (s == INVALID_SOCKET) {
7440fd44 894 err = p_WSAGetLastError();
d74d141c 895 ret->error = winsock_error_string(err);
896 return (Socket) ret;
897 }
898
899 ret->oobinline = 0;
900
7440fd44 901 p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
d74d141c 902
d74d141c 903#ifdef IPV6
904 if (addr->family == AF_INET6) {
905 memset(&a6, 0, sizeof(a6));
906 a6.sin6_family = AF_INET6;
6ee9b735 907 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
908 * know how to do it. :-) */
bcce45ed 909 if (local_host_only)
910 a6.sin6_addr = in6addr_loopback;
911 else
912 a6.sin6_addr = in6addr_any;
7440fd44 913 a6.sin6_port = p_htons(port);
d74d141c 914 } else
915#endif
916 {
6ee9b735 917 int got_addr = 0;
d74d141c 918 a.sin_family = AF_INET;
6ee9b735 919
920 /*
921 * Bind to source address. First try an explicitly
922 * specified one...
923 */
924 if (srcaddr) {
7440fd44 925 a.sin_addr.s_addr = p_inet_addr(srcaddr);
6ee9b735 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)
7440fd44 938 a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
6ee9b735 939 else
7440fd44 940 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
6ee9b735 941 }
942
7440fd44 943 a.sin_port = p_htons((short)port);
d74d141c 944 }
945#ifdef IPV6
7440fd44 946 retcode = p_bind(s, (addr->family == AF_INET6 ?
d74d141c 947 (struct sockaddr *) &a6 :
948 (struct sockaddr *) &a),
949 (addr->family ==
950 AF_INET6 ? sizeof(a6) : sizeof(a)));
951#else
7440fd44 952 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
d74d141c 953#endif
954 if (retcode != SOCKET_ERROR) {
955 err = 0;
956 } else {
7440fd44 957 err = p_WSAGetLastError();
d74d141c 958 }
959
960 if (err) {
961 ret->error = winsock_error_string(err);
962 return (Socket) ret;
963 }
964
965
7440fd44 966 if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
967 p_closesocket(s);
d74d141c 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
32874aea 985static void sk_tcp_close(Socket sock)
986{
9c964e85 987 extern char *do_select(SOCKET skt, int startup);
7e78000d 988 Actual_Socket s = (Actual_Socket) sock;
9c964e85 989
2f75bae1 990 del234(sktree, s);
991 do_select(s->s, 0);
7440fd44 992 p_closesocket(s->s);
dcbde236 993 sfree(s);
2f75bae1 994}
995
2f75bae1 996/*
997 * The function which tries to send on a socket once it's deemed
998 * writable.
999 */
32874aea 1000void try_send(Actual_Socket s)
1001{
5471d09a 1002 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
2f75bae1 1003 int nsent;
1004 DWORD err;
5471d09a 1005 void *data;
32874aea 1006 int len, urgentflag;
1007
1008 if (s->sending_oob) {
1009 urgentflag = MSG_OOB;
1010 len = s->sending_oob;
5471d09a 1011 data = &s->oobdata;
32874aea 1012 } else {
1013 urgentflag = 0;
5471d09a 1014 bufchain_prefix(&s->output_data, &data, &len);
32874aea 1015 }
7440fd44 1016 nsent = p_send(s->s, data, len, urgentflag);
32874aea 1017 noise_ultralight(nsent);
2f75bae1 1018 if (nsent <= 0) {
7440fd44 1019 err = (nsent < 0 ? p_WSAGetLastError() : 0);
e5eb3a1c 1020 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
d40a94b9 1021 /*
1022 * Perfectly normal: we've sent all we can for the moment.
1023 *
e5eb3a1c 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.)
d40a94b9 1029 */
2f75bae1 1030 s->writable = FALSE;
32874aea 1031 return;
2f75bae1 1032 } else if (nsent == 0 ||
32874aea 1033 err == WSAECONNABORTED || err == WSAECONNRESET) {
1034 /*
7732d38a 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.
32874aea 1043 */
7732d38a 1044 s->pending_error = err;
1045 return;
2f75bae1 1046 } else {
a8327734 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));
247308b5 1050 fatalbox("%s", winsock_error_string(err));
2f75bae1 1051 }
1052 } else {
5471d09a 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);
2f75bae1 1062 }
1063 }
1064 }
1065}
1066
e0e7dff8 1067static int sk_tcp_write(Socket sock, const char *buf, int len)
32874aea 1068{
7e78000d 1069 Actual_Socket s = (Actual_Socket) sock;
1070
2f75bae1 1071 /*
1072 * Add the data to the buffer list on the socket.
1073 */
5471d09a 1074 bufchain_add(&s->output_data, buf, len);
2f75bae1 1075
1076 /*
1077 * Now try sending from the start of the buffer list.
1078 */
1079 if (s->writable)
1080 try_send(s);
5471d09a 1081
1082 return bufchain_size(&s->output_data);
2f75bae1 1083}
1084
e0e7dff8 1085static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
32874aea 1086{
7e78000d 1087 Actual_Socket s = (Actual_Socket) sock;
1088
2f75bae1 1089 /*
1090 * Replace the buffer list on the socket with the data.
1091 */
5471d09a 1092 bufchain_clear(&s->output_data);
1093 assert(len <= sizeof(s->oobdata));
1094 memcpy(s->oobdata, buf, len);
2f75bae1 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);
5471d09a 1102
1103 return s->sending_oob;
2f75bae1 1104}
1105
32874aea 1106int select_result(WPARAM wParam, LPARAM lParam)
1107{
f9d3f227 1108 int ret, open;
2f75bae1 1109 DWORD err;
b675c612 1110 char buf[20480]; /* nice big buffer for plenty of speed */
7e78000d 1111 Actual_Socket s;
49bad831 1112 u_long atmark;
2f75bae1 1113
1114 /* wParam is the socket itself */
cc8b0ee9 1115
ce6fcfa5 1116 if (wParam == 0)
1117 return 1; /* boggle */
cc8b0ee9 1118
32874aea 1119 s = find234(sktree, (void *) wParam, cmpforsearch);
2f75bae1 1120 if (!s)
1121 return 1; /* boggle */
1122
1123 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
32874aea 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);
2f75bae1 1129 }
1130
7d6ee6ff 1131 noise_ultralight(lParam);
1132
2f75bae1 1133 switch (WSAGETSELECTEVENT(lParam)) {
3ad9d396 1134 case FD_CONNECT:
1135 s->connected = s->writable = 1;
1136 break;
2f75bae1 1137 case FD_READ:
d74d141c 1138 /* In the case the socket is still frozen, we don't even bother */
5471d09a 1139 if (s->frozen) {
1140 s->frozen_readable = 1;
d74d141c 1141 break;
5471d09a 1142 }
d74d141c 1143
32874aea 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;
7440fd44 1152 p_ioctlsocket(s->s, SIOCATMARK, &atmark);
32874aea 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;
4b1e8acc 1162
7440fd44 1163 ret = p_recv(s->s, buf, sizeof(buf), 0);
32874aea 1164 noise_ultralight(ret);
2f75bae1 1165 if (ret < 0) {
7440fd44 1166 err = p_WSAGetLastError();
2f75bae1 1167 if (err == WSAEWOULDBLOCK) {
1168 break;
1169 }
1170 }
1171 if (ret < 0) {
32874aea 1172 return plug_closing(s->plug, winsock_error_string(err), err,
1173 0);
7e78000d 1174 } else if (0 == ret) {
32874aea 1175 return plug_closing(s->plug, NULL, 0, 0);
2f75bae1 1176 } else {
32874aea 1177 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
2f75bae1 1178 }
1179 break;
1180 case FD_OOB:
32874aea 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 */
7440fd44 1187 ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
32874aea 1188 noise_ultralight(ret);
1189 if (ret <= 0) {
247308b5 1190 char *str = (ret == 0 ? "Internal networking trouble" :
7440fd44 1191 winsock_error_string(p_WSAGetLastError()));
a8327734 1192 /* We're inside the Windows frontend here, so we know
1193 * that the frontend handle is unnecessary. */
1194 logevent(NULL, str);
247308b5 1195 fatalbox("%s", str);
32874aea 1196 } else {
1197 return plug_receive(s->plug, 2, buf, ret);
1198 }
1199 break;
2f75bae1 1200 case FD_WRITE:
5471d09a 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 }
2f75bae1 1210 break;
1211 case FD_CLOSE:
f9d3f227 1212 /* Signal a close on the socket. First read any outstanding data. */
32874aea 1213 open = 1;
1214 do {
7440fd44 1215 ret = p_recv(s->s, buf, sizeof(buf), 0);
32874aea 1216 if (ret < 0) {
7440fd44 1217 err = p_WSAGetLastError();
32874aea 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);
7e78000d 1227 }
f9d3f227 1228 } while (ret > 0);
32874aea 1229 return open;
d74d141c 1230 case FD_ACCEPT:
1231 {
bc4802a1 1232 struct sockaddr_in isa;
1233 int addrlen = sizeof(struct sockaddr_in);
bcce45ed 1234 SOCKET t; /* socket of connection */
1235
bc4802a1 1236 memset(&isa, 0, sizeof(struct sockaddr_in));
bcce45ed 1237 err = 0;
7440fd44 1238 t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
bcce45ed 1239 if (t == INVALID_SOCKET)
1240 {
7440fd44 1241 err = p_WSAGetLastError();
bcce45ed 1242 if (err == WSATRY_AGAIN)
1243 break;
1244 }
1245
a143ea0a 1246 if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr)) {
7440fd44 1247 p_closesocket(t); /* dodgy WinSock let nonlocal through */
bc4802a1 1248 } else if (plug_accepting(s->plug, (void*)t)) {
7440fd44 1249 p_closesocket(t); /* denied or error */
bcce45ed 1250 }
d74d141c 1251 }
2f75bae1 1252 }
1253
1254 return 1;
1255}
1256
1257/*
7732d38a 1258 * Deal with socket errors detected in try_send().
1259 */
1260void 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/*
2f75bae1 1296 * Each socket abstraction contains a `void *' private field in
1297 * which the client can keep state.
1298 */
8eebd221 1299static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
32874aea 1300{
7e78000d 1301 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1302 s->private_ptr = ptr;
1303}
32874aea 1304
8eebd221 1305static void *sk_tcp_get_private_ptr(Socket sock)
32874aea 1306{
7e78000d 1307 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 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 */
cbe2d68f 1316const char *sk_addr_error(SockAddr addr)
32874aea 1317{
2f75bae1 1318 return addr->error;
1319}
cbe2d68f 1320static const char *sk_tcp_socket_error(Socket sock)
32874aea 1321{
7e78000d 1322 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1323 return s->error;
1324}
1325
8eebd221 1326static void sk_tcp_set_frozen(Socket sock, int is_frozen)
d74d141c 1327{
1328 Actual_Socket s = (Actual_Socket) sock;
5471d09a 1329 if (s->frozen == is_frozen)
1330 return;
d74d141c 1331 s->frozen = is_frozen;
5471d09a 1332 if (!is_frozen && s->frozen_readable) {
d74d141c 1333 char c;
7440fd44 1334 p_recv(s->s, &c, 1, MSG_PEEK);
d74d141c 1335 }
5471d09a 1336 s->frozen_readable = 0;
d74d141c 1337}
1338
2f75bae1 1339/*
1340 * For Plink: enumerate all sockets currently active.
1341 */
32874aea 1342SOCKET first_socket(int *state)
1343{
d2371c81 1344 Actual_Socket s;
1345 *state = 0;
1346 s = index234(sktree, (*state)++);
2f75bae1 1347 return s ? s->s : INVALID_SOCKET;
1348}
32874aea 1349
1350SOCKET next_socket(int *state)
1351{
d2371c81 1352 Actual_Socket s = index234(sktree, (*state)++);
2f75bae1 1353 return s ? s->s : INVALID_SOCKET;
1354}
68a49acb 1355
1356int net_service_lookup(char *service)
1357{
1358 struct servent *se;
7440fd44 1359 se = p_getservbyname(service, NULL);
68a49acb 1360 if (se != NULL)
7440fd44 1361 return p_ntohs(se->s_port);
68a49acb 1362 else
1363 return 0;
1364}
fc0f17db 1365
1366SockAddr 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}