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