Joe Yates's memory leak patches.
[u/mdw/putty] / 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,
2184a5d9 661 int nodelay, 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
2f75bae1 725 /*
726 * Bind to local address.
727 */
c91409da 728 if (privport)
32874aea 729 localport = 1023; /* count from 1023 downwards */
c4d8e107 730 else
32874aea 731 localport = 0; /* just use port 0 (ie winsock picks) */
c91409da 732
733 /* Loop round trying to bind */
734 while (1) {
32874aea 735 int retcode;
c91409da 736
737#ifdef IPV6
32874aea 738 if (addr->family == AF_INET6) {
739 memset(&a6, 0, sizeof(a6));
740 a6.sin6_family = AF_INET6;
741/*a6.sin6_addr = in6addr_any; *//* == 0 */
7440fd44 742 a6.sin6_port = p_htons(localport);
32874aea 743 } else
c4d8e107 744#endif
32874aea 745 {
746 a.sin_family = AF_INET;
7440fd44 747 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
748 a.sin_port = p_htons(localport);
32874aea 749 }
c4d8e107 750#ifdef IPV6
7440fd44 751 retcode = p_bind(s, (addr->family == AF_INET6 ?
32874aea 752 (struct sockaddr *) &a6 :
753 (struct sockaddr *) &a),
754 (addr->family ==
755 AF_INET6 ? sizeof(a6) : sizeof(a)));
c4d8e107 756#else
7440fd44 757 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
c4d8e107 758#endif
32874aea 759 if (retcode != SOCKET_ERROR) {
760 err = 0;
761 break; /* done */
762 } else {
7440fd44 763 err = p_WSAGetLastError();
32874aea 764 if (err != WSAEADDRINUSE) /* failed, for a bad reason */
765 break;
766 }
767
768 if (localport == 0)
769 break; /* we're only looping once */
770 localport--;
771 if (localport == 0)
772 break; /* we might have got to the end */
c91409da 773 }
774
32874aea 775 if (err) {
c4d8e107 776 ret->error = winsock_error_string(err);
7e78000d 777 return (Socket) ret;
2f75bae1 778 }
779
780 /*
781 * Connect to remote address.
782 */
c4d8e107 783#ifdef IPV6
32874aea 784 if (addr->family == AF_INET6) {
785 memset(&a, 0, sizeof(a));
c4d8e107 786 a6.sin6_family = AF_INET6;
7440fd44 787 a6.sin6_port = p_htons((short) port);
32874aea 788 a6.sin6_addr =
789 ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
790 } else
c4d8e107 791#endif
32874aea 792 {
c4d8e107 793 a.sin_family = AF_INET;
7440fd44 794 a.sin_addr.s_addr = p_htonl(addr->address);
795 a.sin_port = p_htons((short) port);
c4d8e107 796 }
3ad9d396 797
798 /* Set up a select mechanism. This could be an AsyncSelect on a
799 * window, or an EventSelect on an event object. */
800 errstr = do_select(s, 1);
801 if (errstr) {
802 ret->error = errstr;
803 return (Socket) ret;
804 }
805
32874aea 806 if ((
807#ifdef IPV6
7440fd44 808 p_connect(s, ((addr->family == AF_INET6) ?
32874aea 809 (struct sockaddr *) &a6 : (struct sockaddr *) &a),
810 (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
c4d8e107 811#else
7440fd44 812 p_connect(s, (struct sockaddr *) &a, sizeof(a))
c4d8e107 813#endif
32874aea 814 ) == SOCKET_ERROR) {
7440fd44 815 err = p_WSAGetLastError();
3ad9d396 816 /*
817 * We expect a potential EWOULDBLOCK here, because the
818 * chances are the front end has done a select for
819 * FD_CONNECT, so that connect() will complete
820 * asynchronously.
821 */
822 if ( err != WSAEWOULDBLOCK ) {
823 ret->error = winsock_error_string(err);
824 return (Socket) ret;
825 }
826 } else {
827 /*
828 * If we _don't_ get EWOULDBLOCK, the connect has completed
829 * and we should set the socket as writable.
830 */
831 ret->writable = 1;
2f75bae1 832 }
833
834 add234(sktree, ret);
835
f85e6f6e 836 /* We're done with 'addr' now. */
837 sk_addr_free(addr);
838
7e78000d 839 return (Socket) ret;
2f75bae1 840}
841
6ee9b735 842Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
d74d141c 843{
c85623f9 844 static const struct socket_function_table fn_table = {
d74d141c 845 sk_tcp_plug,
846 sk_tcp_close,
847 sk_tcp_write,
848 sk_tcp_write_oob,
849 sk_tcp_flush,
8eebd221 850 sk_tcp_set_private_ptr,
851 sk_tcp_get_private_ptr,
852 sk_tcp_set_frozen,
d74d141c 853 sk_tcp_socket_error
854 };
855
856 SOCKET s;
857#ifdef IPV6
858 SOCKADDR_IN6 a6;
859#endif
860 SOCKADDR_IN a;
861 DWORD err;
862 char *errstr;
863 Actual_Socket ret;
864 int retcode;
865 int on = 1;
866
867 /*
868 * Create Socket structure.
869 */
3d88e64d 870 ret = snew(struct Socket_tag);
d74d141c 871 ret->fn = &fn_table;
872 ret->error = NULL;
873 ret->plug = plug;
5471d09a 874 bufchain_init(&ret->output_data);
d74d141c 875 ret->writable = 0; /* to start with */
876 ret->sending_oob = 0;
877 ret->frozen = 0;
5471d09a 878 ret->frozen_readable = 0;
bc4802a1 879 ret->localhost_only = local_host_only;
7732d38a 880 ret->pending_error = 0;
d74d141c 881
882 /*
883 * Open socket.
884 */
7440fd44 885 s = p_socket(AF_INET, SOCK_STREAM, 0);
d74d141c 886 ret->s = s;
887
888 if (s == INVALID_SOCKET) {
7440fd44 889 err = p_WSAGetLastError();
d74d141c 890 ret->error = winsock_error_string(err);
891 return (Socket) ret;
892 }
893
894 ret->oobinline = 0;
895
7440fd44 896 p_setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
d74d141c 897
d74d141c 898#ifdef IPV6
899 if (addr->family == AF_INET6) {
900 memset(&a6, 0, sizeof(a6));
901 a6.sin6_family = AF_INET6;
6ee9b735 902 /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
903 * know how to do it. :-) */
bcce45ed 904 if (local_host_only)
905 a6.sin6_addr = in6addr_loopback;
906 else
907 a6.sin6_addr = in6addr_any;
7440fd44 908 a6.sin6_port = p_htons(port);
d74d141c 909 } else
910#endif
911 {
6ee9b735 912 int got_addr = 0;
d74d141c 913 a.sin_family = AF_INET;
6ee9b735 914
915 /*
916 * Bind to source address. First try an explicitly
917 * specified one...
918 */
919 if (srcaddr) {
7440fd44 920 a.sin_addr.s_addr = p_inet_addr(srcaddr);
6ee9b735 921 if (a.sin_addr.s_addr != INADDR_NONE) {
922 /* Override localhost_only with specified listen addr. */
923 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
924 got_addr = 1;
925 }
926 }
927
928 /*
929 * ... and failing that, go with one of the standard ones.
930 */
931 if (!got_addr) {
932 if (local_host_only)
7440fd44 933 a.sin_addr.s_addr = p_htonl(INADDR_LOOPBACK);
6ee9b735 934 else
7440fd44 935 a.sin_addr.s_addr = p_htonl(INADDR_ANY);
6ee9b735 936 }
937
7440fd44 938 a.sin_port = p_htons((short)port);
d74d141c 939 }
940#ifdef IPV6
7440fd44 941 retcode = p_bind(s, (addr->family == AF_INET6 ?
d74d141c 942 (struct sockaddr *) &a6 :
943 (struct sockaddr *) &a),
944 (addr->family ==
945 AF_INET6 ? sizeof(a6) : sizeof(a)));
946#else
7440fd44 947 retcode = p_bind(s, (struct sockaddr *) &a, sizeof(a));
d74d141c 948#endif
949 if (retcode != SOCKET_ERROR) {
950 err = 0;
951 } else {
7440fd44 952 err = p_WSAGetLastError();
d74d141c 953 }
954
955 if (err) {
956 ret->error = winsock_error_string(err);
957 return (Socket) ret;
958 }
959
960
7440fd44 961 if (p_listen(s, SOMAXCONN) == SOCKET_ERROR) {
962 p_closesocket(s);
d74d141c 963 ret->error = winsock_error_string(err);
964 return (Socket) ret;
965 }
966
967 /* Set up a select mechanism. This could be an AsyncSelect on a
968 * window, or an EventSelect on an event object. */
969 errstr = do_select(s, 1);
970 if (errstr) {
971 ret->error = errstr;
972 return (Socket) ret;
973 }
974
975 add234(sktree, ret);
976
977 return (Socket) ret;
978}
979
32874aea 980static void sk_tcp_close(Socket sock)
981{
9c964e85 982 extern char *do_select(SOCKET skt, int startup);
7e78000d 983 Actual_Socket s = (Actual_Socket) sock;
9c964e85 984
2f75bae1 985 del234(sktree, s);
986 do_select(s->s, 0);
7440fd44 987 p_closesocket(s->s);
dcbde236 988 sfree(s);
2f75bae1 989}
990
2f75bae1 991/*
992 * The function which tries to send on a socket once it's deemed
993 * writable.
994 */
32874aea 995void try_send(Actual_Socket s)
996{
5471d09a 997 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
2f75bae1 998 int nsent;
999 DWORD err;
5471d09a 1000 void *data;
32874aea 1001 int len, urgentflag;
1002
1003 if (s->sending_oob) {
1004 urgentflag = MSG_OOB;
1005 len = s->sending_oob;
5471d09a 1006 data = &s->oobdata;
32874aea 1007 } else {
1008 urgentflag = 0;
5471d09a 1009 bufchain_prefix(&s->output_data, &data, &len);
32874aea 1010 }
7440fd44 1011 nsent = p_send(s->s, data, len, urgentflag);
32874aea 1012 noise_ultralight(nsent);
2f75bae1 1013 if (nsent <= 0) {
7440fd44 1014 err = (nsent < 0 ? p_WSAGetLastError() : 0);
e5eb3a1c 1015 if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
d40a94b9 1016 /*
1017 * Perfectly normal: we've sent all we can for the moment.
1018 *
e5eb3a1c 1019 * (Some WinSock send() implementations can return
1020 * <0 but leave no sensible error indication -
1021 * WSAGetLastError() is called but returns zero or
1022 * a small number - so we check that case and treat
1023 * it just like WSAEWOULDBLOCK.)
d40a94b9 1024 */
2f75bae1 1025 s->writable = FALSE;
32874aea 1026 return;
2f75bae1 1027 } else if (nsent == 0 ||
32874aea 1028 err == WSAECONNABORTED || err == WSAECONNRESET) {
1029 /*
7732d38a 1030 * If send() returns CONNABORTED or CONNRESET, we
1031 * unfortunately can't just call plug_closing(),
1032 * because it's quite likely that we're currently
1033 * _in_ a call from the code we'd be calling back
1034 * to, so we'd have to make half the SSH code
1035 * reentrant. Instead we flag a pending error on
1036 * the socket, to be dealt with (by calling
1037 * plug_closing()) at some suitable future moment.
32874aea 1038 */
7732d38a 1039 s->pending_error = err;
1040 return;
2f75bae1 1041 } else {
a8327734 1042 /* We're inside the Windows frontend here, so we know
1043 * that the frontend handle is unnecessary. */
1044 logevent(NULL, winsock_error_string(err));
247308b5 1045 fatalbox("%s", winsock_error_string(err));
2f75bae1 1046 }
1047 } else {
5471d09a 1048 if (s->sending_oob) {
1049 if (nsent < len) {
1050 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1051 s->sending_oob = len - nsent;
1052 } else {
1053 s->sending_oob = 0;
1054 }
1055 } else {
1056 bufchain_consume(&s->output_data, nsent);
2f75bae1 1057 }
1058 }
1059 }
1060}
1061
e0e7dff8 1062static int sk_tcp_write(Socket sock, const char *buf, int len)
32874aea 1063{
7e78000d 1064 Actual_Socket s = (Actual_Socket) sock;
1065
2f75bae1 1066 /*
1067 * Add the data to the buffer list on the socket.
1068 */
5471d09a 1069 bufchain_add(&s->output_data, buf, len);
2f75bae1 1070
1071 /*
1072 * Now try sending from the start of the buffer list.
1073 */
1074 if (s->writable)
1075 try_send(s);
5471d09a 1076
1077 return bufchain_size(&s->output_data);
2f75bae1 1078}
1079
e0e7dff8 1080static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
32874aea 1081{
7e78000d 1082 Actual_Socket s = (Actual_Socket) sock;
1083
2f75bae1 1084 /*
1085 * Replace the buffer list on the socket with the data.
1086 */
5471d09a 1087 bufchain_clear(&s->output_data);
1088 assert(len <= sizeof(s->oobdata));
1089 memcpy(s->oobdata, buf, len);
2f75bae1 1090 s->sending_oob = len;
1091
1092 /*
1093 * Now try sending from the start of the buffer list.
1094 */
1095 if (s->writable)
1096 try_send(s);
5471d09a 1097
1098 return s->sending_oob;
2f75bae1 1099}
1100
32874aea 1101int select_result(WPARAM wParam, LPARAM lParam)
1102{
f9d3f227 1103 int ret, open;
2f75bae1 1104 DWORD err;
b675c612 1105 char buf[20480]; /* nice big buffer for plenty of speed */
7e78000d 1106 Actual_Socket s;
49bad831 1107 u_long atmark;
2f75bae1 1108
1109 /* wParam is the socket itself */
cc8b0ee9 1110
ce6fcfa5 1111 if (wParam == 0)
1112 return 1; /* boggle */
cc8b0ee9 1113
32874aea 1114 s = find234(sktree, (void *) wParam, cmpforsearch);
2f75bae1 1115 if (!s)
1116 return 1; /* boggle */
1117
1118 if ((err = WSAGETSELECTERROR(lParam)) != 0) {
32874aea 1119 /*
1120 * An error has occurred on this socket. Pass it to the
1121 * plug.
1122 */
1123 return plug_closing(s->plug, winsock_error_string(err), err, 0);
2f75bae1 1124 }
1125
7d6ee6ff 1126 noise_ultralight(lParam);
1127
2f75bae1 1128 switch (WSAGETSELECTEVENT(lParam)) {
3ad9d396 1129 case FD_CONNECT:
1130 s->connected = s->writable = 1;
1131 break;
2f75bae1 1132 case FD_READ:
d74d141c 1133 /* In the case the socket is still frozen, we don't even bother */
5471d09a 1134 if (s->frozen) {
1135 s->frozen_readable = 1;
d74d141c 1136 break;
5471d09a 1137 }
d74d141c 1138
32874aea 1139 /*
1140 * We have received data on the socket. For an oobinline
1141 * socket, this might be data _before_ an urgent pointer,
1142 * in which case we send it to the back end with type==1
1143 * (data prior to urgent).
1144 */
1145 if (s->oobinline) {
1146 atmark = 1;
7440fd44 1147 p_ioctlsocket(s->s, SIOCATMARK, &atmark);
32874aea 1148 /*
1149 * Avoid checking the return value from ioctlsocket(),
1150 * on the grounds that some WinSock wrappers don't
1151 * support it. If it does nothing, we get atmark==1,
1152 * which is equivalent to `no OOB pending', so the
1153 * effect will be to non-OOB-ify any OOB data.
1154 */
1155 } else
1156 atmark = 1;
4b1e8acc 1157
7440fd44 1158 ret = p_recv(s->s, buf, sizeof(buf), 0);
32874aea 1159 noise_ultralight(ret);
2f75bae1 1160 if (ret < 0) {
7440fd44 1161 err = p_WSAGetLastError();
2f75bae1 1162 if (err == WSAEWOULDBLOCK) {
1163 break;
1164 }
1165 }
1166 if (ret < 0) {
32874aea 1167 return plug_closing(s->plug, winsock_error_string(err), err,
1168 0);
7e78000d 1169 } else if (0 == ret) {
32874aea 1170 return plug_closing(s->plug, NULL, 0, 0);
2f75bae1 1171 } else {
32874aea 1172 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
2f75bae1 1173 }
1174 break;
1175 case FD_OOB:
32874aea 1176 /*
1177 * This will only happen on a non-oobinline socket. It
1178 * indicates that we can immediately perform an OOB read
1179 * and get back OOB data, which we will send to the back
1180 * end with type==2 (urgent data).
1181 */
7440fd44 1182 ret = p_recv(s->s, buf, sizeof(buf), MSG_OOB);
32874aea 1183 noise_ultralight(ret);
1184 if (ret <= 0) {
247308b5 1185 char *str = (ret == 0 ? "Internal networking trouble" :
7440fd44 1186 winsock_error_string(p_WSAGetLastError()));
a8327734 1187 /* We're inside the Windows frontend here, so we know
1188 * that the frontend handle is unnecessary. */
1189 logevent(NULL, str);
247308b5 1190 fatalbox("%s", str);
32874aea 1191 } else {
1192 return plug_receive(s->plug, 2, buf, ret);
1193 }
1194 break;
2f75bae1 1195 case FD_WRITE:
5471d09a 1196 {
1197 int bufsize_before, bufsize_after;
1198 s->writable = 1;
1199 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1200 try_send(s);
1201 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1202 if (bufsize_after < bufsize_before)
1203 plug_sent(s->plug, bufsize_after);
1204 }
2f75bae1 1205 break;
1206 case FD_CLOSE:
f9d3f227 1207 /* Signal a close on the socket. First read any outstanding data. */
32874aea 1208 open = 1;
1209 do {
7440fd44 1210 ret = p_recv(s->s, buf, sizeof(buf), 0);
32874aea 1211 if (ret < 0) {
7440fd44 1212 err = p_WSAGetLastError();
32874aea 1213 if (err == WSAEWOULDBLOCK)
1214 break;
1215 return plug_closing(s->plug, winsock_error_string(err),
1216 err, 0);
1217 } else {
1218 if (ret)
1219 open &= plug_receive(s->plug, 0, buf, ret);
1220 else
1221 open &= plug_closing(s->plug, NULL, 0, 0);
7e78000d 1222 }
f9d3f227 1223 } while (ret > 0);
32874aea 1224 return open;
d74d141c 1225 case FD_ACCEPT:
1226 {
bc4802a1 1227 struct sockaddr_in isa;
1228 int addrlen = sizeof(struct sockaddr_in);
bcce45ed 1229 SOCKET t; /* socket of connection */
1230
bc4802a1 1231 memset(&isa, 0, sizeof(struct sockaddr_in));
bcce45ed 1232 err = 0;
7440fd44 1233 t = p_accept(s->s,(struct sockaddr *)&isa,&addrlen);
bcce45ed 1234 if (t == INVALID_SOCKET)
1235 {
7440fd44 1236 err = p_WSAGetLastError();
bcce45ed 1237 if (err == WSATRY_AGAIN)
1238 break;
1239 }
1240
a143ea0a 1241 if (s->localhost_only && !ipv4_is_local_addr(isa.sin_addr)) {
7440fd44 1242 p_closesocket(t); /* dodgy WinSock let nonlocal through */
bc4802a1 1243 } else if (plug_accepting(s->plug, (void*)t)) {
7440fd44 1244 p_closesocket(t); /* denied or error */
bcce45ed 1245 }
d74d141c 1246 }
2f75bae1 1247 }
1248
1249 return 1;
1250}
1251
1252/*
7732d38a 1253 * Deal with socket errors detected in try_send().
1254 */
1255void net_pending_errors(void)
1256{
1257 int i;
1258 Actual_Socket s;
1259
1260 /*
1261 * This might be a fiddly business, because it's just possible
1262 * that handling a pending error on one socket might cause
1263 * others to be closed. (I can't think of any reason this might
1264 * happen in current SSH implementation, but to maintain
1265 * generality of this network layer I'll assume the worst.)
1266 *
1267 * So what we'll do is search the socket list for _one_ socket
1268 * with a pending error, and then handle it, and then search
1269 * the list again _from the beginning_. Repeat until we make a
1270 * pass with no socket errors present. That way we are
1271 * protected against the socket list changing under our feet.
1272 */
1273
1274 do {
1275 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1276 if (s->pending_error) {
1277 /*
1278 * An error has occurred on this socket. Pass it to the
1279 * plug.
1280 */
1281 plug_closing(s->plug,
1282 winsock_error_string(s->pending_error),
1283 s->pending_error, 0);
1284 break;
1285 }
1286 }
1287 } while (s);
1288}
1289
1290/*
2f75bae1 1291 * Each socket abstraction contains a `void *' private field in
1292 * which the client can keep state.
1293 */
8eebd221 1294static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
32874aea 1295{
7e78000d 1296 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1297 s->private_ptr = ptr;
1298}
32874aea 1299
8eebd221 1300static void *sk_tcp_get_private_ptr(Socket sock)
32874aea 1301{
7e78000d 1302 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1303 return s->private_ptr;
1304}
1305
1306/*
1307 * Special error values are returned from sk_namelookup and sk_new
1308 * if there's a problem. These functions extract an error message,
1309 * or return NULL if there's no problem.
1310 */
cbe2d68f 1311const char *sk_addr_error(SockAddr addr)
32874aea 1312{
2f75bae1 1313 return addr->error;
1314}
cbe2d68f 1315static const char *sk_tcp_socket_error(Socket sock)
32874aea 1316{
7e78000d 1317 Actual_Socket s = (Actual_Socket) sock;
2f75bae1 1318 return s->error;
1319}
1320
8eebd221 1321static void sk_tcp_set_frozen(Socket sock, int is_frozen)
d74d141c 1322{
1323 Actual_Socket s = (Actual_Socket) sock;
5471d09a 1324 if (s->frozen == is_frozen)
1325 return;
d74d141c 1326 s->frozen = is_frozen;
5471d09a 1327 if (!is_frozen && s->frozen_readable) {
d74d141c 1328 char c;
7440fd44 1329 p_recv(s->s, &c, 1, MSG_PEEK);
d74d141c 1330 }
5471d09a 1331 s->frozen_readable = 0;
d74d141c 1332}
1333
2f75bae1 1334/*
1335 * For Plink: enumerate all sockets currently active.
1336 */
32874aea 1337SOCKET first_socket(int *state)
1338{
d2371c81 1339 Actual_Socket s;
1340 *state = 0;
1341 s = index234(sktree, (*state)++);
2f75bae1 1342 return s ? s->s : INVALID_SOCKET;
1343}
32874aea 1344
1345SOCKET next_socket(int *state)
1346{
d2371c81 1347 Actual_Socket s = index234(sktree, (*state)++);
2f75bae1 1348 return s ? s->s : INVALID_SOCKET;
1349}
68a49acb 1350
1351int net_service_lookup(char *service)
1352{
1353 struct servent *se;
7440fd44 1354 se = p_getservbyname(service, NULL);
68a49acb 1355 if (se != NULL)
7440fd44 1356 return p_ntohs(se->s_port);
68a49acb 1357 else
1358 return 0;
1359}