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