]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - winnet.c
Add single-DES support in SSH2
[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 #ifdef IPV6
42 #include <winsock2.h>
43 #include <ws2tcpip.h>
44 #include <tpipv6.h>
45 #else
46 #include <winsock.h>
47 #endif
48 #include <windows.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <assert.h>
52
53 #define DEFINE_PLUG_METHOD_MACROS
54 #include "putty.h"
55 #include "network.h"
56 #include "tree234.h"
57
58 struct Socket_tag {
59     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     /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
91     int family;
92     unsigned long address;             /* Address IPv4 style. */
93 #ifdef IPV6
94     struct addrinfo *ai;               /* Address IPv6 style. */
95 #endif
96 };
97
98 static tree234 *sktree;
99
100 static int cmpfortree(void *av, void *bv)
101 {
102     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
103     unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
104     if (as < bs)
105         return -1;
106     if (as > bs)
107         return +1;
108     return 0;
109 }
110
111 static int cmpforsearch(void *av, void *bv)
112 {
113     Actual_Socket b = (Actual_Socket) bv;
114     unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
115     if (as < bs)
116         return -1;
117     if (as > bs)
118         return +1;
119     return 0;
120 }
121
122 void sk_init(void)
123 {
124     sktree = newtree234(cmpfortree);
125 }
126
127 char *winsock_error_string(int error)
128 {
129     switch (error) {
130       case WSAEACCES:
131         return "Network error: Permission denied";
132       case WSAEADDRINUSE:
133         return "Network error: Address already in use";
134       case WSAEADDRNOTAVAIL:
135         return "Network error: Cannot assign requested address";
136       case WSAEAFNOSUPPORT:
137         return
138             "Network error: Address family not supported by protocol family";
139       case WSAEALREADY:
140         return "Network error: Operation already in progress";
141       case WSAECONNABORTED:
142         return "Network error: Software caused connection abort";
143       case WSAECONNREFUSED:
144         return "Network error: Connection refused";
145       case WSAECONNRESET:
146         return "Network error: Connection reset by peer";
147       case WSAEDESTADDRREQ:
148         return "Network error: Destination address required";
149       case WSAEFAULT:
150         return "Network error: Bad address";
151       case WSAEHOSTDOWN:
152         return "Network error: Host is down";
153       case WSAEHOSTUNREACH:
154         return "Network error: No route to host";
155       case WSAEINPROGRESS:
156         return "Network error: Operation now in progress";
157       case WSAEINTR:
158         return "Network error: Interrupted function call";
159       case WSAEINVAL:
160         return "Network error: Invalid argument";
161       case WSAEISCONN:
162         return "Network error: Socket is already connected";
163       case WSAEMFILE:
164         return "Network error: Too many open files";
165       case WSAEMSGSIZE:
166         return "Network error: Message too long";
167       case WSAENETDOWN:
168         return "Network error: Network is down";
169       case WSAENETRESET:
170         return "Network error: Network dropped connection on reset";
171       case WSAENETUNREACH:
172         return "Network error: Network is unreachable";
173       case WSAENOBUFS:
174         return "Network error: No buffer space available";
175       case WSAENOPROTOOPT:
176         return "Network error: Bad protocol option";
177       case WSAENOTCONN:
178         return "Network error: Socket is not connected";
179       case WSAENOTSOCK:
180         return "Network error: Socket operation on non-socket";
181       case WSAEOPNOTSUPP:
182         return "Network error: Operation not supported";
183       case WSAEPFNOSUPPORT:
184         return "Network error: Protocol family not supported";
185       case WSAEPROCLIM:
186         return "Network error: Too many processes";
187       case WSAEPROTONOSUPPORT:
188         return "Network error: Protocol not supported";
189       case WSAEPROTOTYPE:
190         return "Network error: Protocol wrong type for socket";
191       case WSAESHUTDOWN:
192         return "Network error: Cannot send after socket shutdown";
193       case WSAESOCKTNOSUPPORT:
194         return "Network error: Socket type not supported";
195       case WSAETIMEDOUT:
196         return "Network error: Connection timed out";
197       case WSAEWOULDBLOCK:
198         return "Network error: Resource temporarily unavailable";
199       case WSAEDISCON:
200         return "Network error: Graceful shutdown in progress";
201       default:
202         return "Unknown network error";
203     }
204 }
205
206 SockAddr sk_namelookup(char *host, char **canonicalname)
207 {
208     SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
209     unsigned long a;
210     struct hostent *h = NULL;
211     char realhost[8192];
212
213     /* Clear the structure and default to IPv4. */
214     memset(ret, 0, sizeof(struct SockAddr_tag));
215     ret->family = 0;                   /* We set this one when we have resolved the host. */
216     *realhost = '\0';
217
218     if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
219 #ifdef IPV6
220
221         /* Try to get the getaddrinfo() function from wship6.dll */
222         /* This way one doesn't need to have IPv6 dll's to use PuTTY and
223          * it will fallback to IPv4. */
224         typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
225                                                const char *servname,
226                                                const struct addrinfo *
227                                                hints,
228                                                struct addrinfo ** res);
229         FGETADDRINFO fGetAddrInfo = NULL;
230
231         HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
232         if (dllWSHIP6)
233             fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
234                                                          "getaddrinfo");
235
236         /*
237          * Use fGetAddrInfo when it's available (which usually also
238          * means IPv6 is installed...)
239          */
240         if (fGetAddrInfo) {
241             /*debug(("Resolving \"%s\" with getaddrinfo()  (IPv4+IPv6 capable)...\n", host)); */
242             if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
243                 ret->family = ret->ai->ai_family;
244         } else
245 #endif
246         {
247             /*
248              * Otherwise use the IPv4-only gethostbyname...
249              * (NOTE: we don't use gethostbyname as a
250              * fallback!)
251              */
252             if (ret->family == 0) {
253                 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
254                 if ( (h = gethostbyname(host)) )
255                     ret->family = AF_INET;
256             }
257         }
258         /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
259
260         if (ret->family == 0) {
261             DWORD err = WSAGetLastError();
262             ret->error = (err == WSAENETDOWN ? "Network is down" :
263                           err ==
264                           WSAHOST_NOT_FOUND ? "Host does not exist" : err
265                           == WSATRY_AGAIN ? "Host not found" :
266 #ifdef IPV6
267                           fGetAddrInfo ? "getaddrinfo: unknown error" :
268 #endif
269                           "gethostbyname: unknown error");
270 #ifdef DEBUG
271             {
272                 LPVOID lpMsgBuf;
273                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
274                               FORMAT_MESSAGE_FROM_SYSTEM |
275                               FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
276                               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
277                               (LPTSTR) & lpMsgBuf, 0, NULL);
278                 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
279                 /* Free the buffer. */
280                 LocalFree(lpMsgBuf);
281             }
282 #endif
283         } else {
284             ret->error = NULL;
285
286 #ifdef IPV6
287             /* If we got an address info use that... */
288             if (ret->ai) {
289                 typedef int (CALLBACK * FGETNAMEINFO)
290                  (const struct sockaddr FAR * sa, socklen_t salen,
291                   char FAR * host, size_t hostlen, char FAR * serv,
292                   size_t servlen, int flags);
293                 FGETNAMEINFO fGetNameInfo = NULL;
294
295                 /* Are we in IPv4 fallback mode? */
296                 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
297                 if (ret->family == AF_INET)
298                     memcpy(&a,
299                            (char *) &((SOCKADDR_IN *) ret->ai->
300                                       ai_addr)->sin_addr, sizeof(a));
301
302                 /* Now let's find that canonicalname... */
303                 if ((dllWSHIP6)
304                     && (fGetNameInfo =
305                         (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
306                                                       "getnameinfo"))) {
307                     if (fGetNameInfo
308                         ((struct sockaddr *) ret->ai->ai_addr,
309                          ret->family ==
310                          AF_INET ? sizeof(SOCKADDR_IN) :
311                          sizeof(SOCKADDR_IN6), realhost,
312                          sizeof(realhost), NULL, 0, 0) != 0) {
313                         strncpy(realhost, host, sizeof(realhost));
314                     }
315                 }
316             }
317             /* We used the IPv4-only gethostbyname()... */
318             else
319 #endif
320             {
321                 memcpy(&a, h->h_addr, sizeof(a));
322                 /* This way we are always sure the h->h_name is valid :) */
323                 strncpy(realhost, h->h_name, sizeof(realhost));
324             }
325         }
326 #ifdef IPV6
327         FreeLibrary(dllWSHIP6);
328 #endif
329     } else {
330         /*
331          * This must be a numeric IPv4 address because it caused a
332          * success return from inet_addr.
333          */
334         ret->family = AF_INET;
335         strncpy(realhost, host, sizeof(realhost));
336     }
337     ret->address = ntohl(a);
338     realhost[lenof(realhost)-1] = '\0';
339     *canonicalname = smalloc(1+strlen(realhost));
340     strcpy(*canonicalname, realhost);
341     return ret;
342 }
343
344 void sk_getaddr(SockAddr addr, char *buf, int buflen)
345 {
346 #ifdef IPV6
347     if (addr->family == AF_INET) {
348 #endif
349         struct in_addr a;
350         a.s_addr = htonl(addr->address);
351         strncpy(buf, inet_ntoa(a), buflen);
352 #ifdef IPV6
353     } else {
354         FIXME; /* I don't know how to get a text form of an IPv6 address. */
355     }
356 #endif
357 }
358
359 void sk_addr_free(SockAddr addr)
360 {
361     sfree(addr);
362 }
363
364 static Plug sk_tcp_plug(Socket sock, Plug p)
365 {
366     Actual_Socket s = (Actual_Socket) sock;
367     Plug ret = s->plug;
368     if (p)
369         s->plug = p;
370     return ret;
371 }
372
373 static void sk_tcp_flush(Socket s)
374 {
375     /*
376      * We send data to the socket as soon as we can anyway,
377      * so we don't need to do anything here.  :-)
378      */
379 }
380
381 static void sk_tcp_close(Socket s);
382 static int sk_tcp_write(Socket s, char *data, int len);
383 static int sk_tcp_write_oob(Socket s, char *data, int len);
384 static char *sk_tcp_socket_error(Socket s);
385
386 extern char *do_select(SOCKET skt, int startup);
387
388 Socket sk_register(void *sock, Plug plug)
389 {
390     static struct socket_function_table fn_table = {
391         sk_tcp_plug,
392         sk_tcp_close,
393         sk_tcp_write,
394         sk_tcp_write_oob,
395         sk_tcp_flush,
396         sk_tcp_socket_error
397     };
398
399     DWORD err;
400     char *errstr;
401     Actual_Socket ret;
402
403     /*
404      * Create Socket structure.
405      */
406     ret = smalloc(sizeof(struct Socket_tag));
407     ret->fn = &fn_table;
408     ret->error = NULL;
409     ret->plug = plug;
410     bufchain_init(&ret->output_data);
411     ret->writable = 1;                 /* to start with */
412     ret->sending_oob = 0;
413     ret->frozen = 1;
414     ret->frozen_readable = 0;
415     ret->localhost_only = 0;           /* unused, but best init anyway */
416     ret->pending_error = 0;
417
418     ret->s = (SOCKET)sock;
419
420     if (ret->s == INVALID_SOCKET) {
421         err = WSAGetLastError();
422         ret->error = winsock_error_string(err);
423         return (Socket) ret;
424     }
425
426     ret->oobinline = 0;
427
428     /* Set up a select mechanism. This could be an AsyncSelect on a
429      * window, or an EventSelect on an event object. */
430     errstr = do_select(ret->s, 1);
431     if (errstr) {
432         ret->error = errstr;
433         return (Socket) ret;
434     }
435
436     add234(sktree, ret);
437
438     return (Socket) ret;
439 }
440
441 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
442               Plug plug)
443 {
444     static struct socket_function_table fn_table = {
445         sk_tcp_plug,
446         sk_tcp_close,
447         sk_tcp_write,
448         sk_tcp_write_oob,
449         sk_tcp_flush,
450         sk_tcp_socket_error
451     };
452
453     SOCKET s;
454 #ifdef IPV6
455     SOCKADDR_IN6 a6;
456 #endif
457     SOCKADDR_IN a;
458     DWORD err;
459     char *errstr;
460     Actual_Socket ret;
461     short localport;
462
463     /*
464      * Create Socket structure.
465      */
466     ret = smalloc(sizeof(struct Socket_tag));
467     ret->fn = &fn_table;
468     ret->error = NULL;
469     ret->plug = plug;
470     bufchain_init(&ret->output_data);
471     ret->connected = 0;                /* to start with */
472     ret->writable = 0;                 /* to start with */
473     ret->sending_oob = 0;
474     ret->frozen = 0;
475     ret->frozen_readable = 0;
476     ret->localhost_only = 0;           /* unused, but best init anyway */
477     ret->pending_error = 0;
478
479     /*
480      * Open socket.
481      */
482     s = socket(addr->family, SOCK_STREAM, 0);
483     ret->s = s;
484
485     if (s == INVALID_SOCKET) {
486         err = WSAGetLastError();
487         ret->error = winsock_error_string(err);
488         return (Socket) ret;
489     }
490
491     ret->oobinline = oobinline;
492     if (oobinline) {
493         BOOL b = TRUE;
494         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
495     }
496
497     /*
498      * Bind to local address.
499      */
500     if (privport)
501         localport = 1023;              /* count from 1023 downwards */
502     else
503         localport = 0;                 /* just use port 0 (ie winsock picks) */
504
505     /* Loop round trying to bind */
506     while (1) {
507         int retcode;
508
509 #ifdef IPV6
510         if (addr->family == AF_INET6) {
511             memset(&a6, 0, sizeof(a6));
512             a6.sin6_family = AF_INET6;
513 /*a6.sin6_addr      = in6addr_any; *//* == 0 */
514             a6.sin6_port = htons(localport);
515         } else
516 #endif
517         {
518             a.sin_family = AF_INET;
519             a.sin_addr.s_addr = htonl(INADDR_ANY);
520             a.sin_port = htons(localport);
521         }
522 #ifdef IPV6
523         retcode = bind(s, (addr->family == AF_INET6 ?
524                            (struct sockaddr *) &a6 :
525                            (struct sockaddr *) &a),
526                        (addr->family ==
527                         AF_INET6 ? sizeof(a6) : sizeof(a)));
528 #else
529         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
530 #endif
531         if (retcode != SOCKET_ERROR) {
532             err = 0;
533             break;                     /* done */
534         } else {
535             err = WSAGetLastError();
536             if (err != WSAEADDRINUSE)  /* failed, for a bad reason */
537                 break;
538         }
539
540         if (localport == 0)
541             break;                     /* we're only looping once */
542         localport--;
543         if (localport == 0)
544             break;                     /* we might have got to the end */
545     }
546
547     if (err) {
548         ret->error = winsock_error_string(err);
549         return (Socket) ret;
550     }
551
552     /*
553      * Connect to remote address.
554      */
555 #ifdef IPV6
556     if (addr->family == AF_INET6) {
557         memset(&a, 0, sizeof(a));
558         a6.sin6_family = AF_INET6;
559         a6.sin6_port = htons((short) port);
560         a6.sin6_addr =
561             ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
562     } else
563 #endif
564     {
565         a.sin_family = AF_INET;
566         a.sin_addr.s_addr = htonl(addr->address);
567         a.sin_port = htons((short) port);
568     }
569
570     /* Set up a select mechanism. This could be an AsyncSelect on a
571      * window, or an EventSelect on an event object. */
572     errstr = do_select(s, 1);
573     if (errstr) {
574         ret->error = errstr;
575         return (Socket) ret;
576     }
577
578     if ((
579 #ifdef IPV6
580             connect(s, ((addr->family == AF_INET6) ?
581                         (struct sockaddr *) &a6 : (struct sockaddr *) &a),
582                     (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
583 #else
584             connect(s, (struct sockaddr *) &a, sizeof(a))
585 #endif
586         ) == SOCKET_ERROR) {
587         err = WSAGetLastError();
588         /*
589          * We expect a potential EWOULDBLOCK here, because the
590          * chances are the front end has done a select for
591          * FD_CONNECT, so that connect() will complete
592          * asynchronously.
593          */
594         if ( err != WSAEWOULDBLOCK ) {
595             ret->error = winsock_error_string(err);
596             return (Socket) ret;
597         }
598     } else {
599         /*
600          * If we _don't_ get EWOULDBLOCK, the connect has completed
601          * and we should set the socket as writable.
602          */
603         ret->writable = 1;
604     }
605
606     add234(sktree, ret);
607
608     return (Socket) ret;
609 }
610
611 Socket sk_newlistener(int port, Plug plug, int local_host_only)
612 {
613     static struct socket_function_table fn_table = {
614         sk_tcp_plug,
615         sk_tcp_close,
616         sk_tcp_write,
617         sk_tcp_write_oob,
618         sk_tcp_flush,
619         sk_tcp_socket_error
620     };
621
622     SOCKET s;
623 #ifdef IPV6
624     SOCKADDR_IN6 a6;
625 #endif
626     SOCKADDR_IN a;
627     DWORD err;
628     char *errstr;
629     Actual_Socket ret;
630     int retcode;
631     int on = 1;
632
633     /*
634      * Create Socket structure.
635      */
636     ret = smalloc(sizeof(struct Socket_tag));
637     ret->fn = &fn_table;
638     ret->error = NULL;
639     ret->plug = plug;
640     bufchain_init(&ret->output_data);
641     ret->writable = 0;                 /* to start with */
642     ret->sending_oob = 0;
643     ret->frozen = 0;
644     ret->frozen_readable = 0;
645     ret->localhost_only = local_host_only;
646     ret->pending_error = 0;
647
648     /*
649      * Open socket.
650      */
651     s = socket(AF_INET, SOCK_STREAM, 0);
652     ret->s = s;
653
654     if (s == INVALID_SOCKET) {
655         err = WSAGetLastError();
656         ret->error = winsock_error_string(err);
657         return (Socket) ret;
658     }
659
660     ret->oobinline = 0;
661
662
663     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
664
665
666 #ifdef IPV6
667         if (addr->family == AF_INET6) {
668             memset(&a6, 0, sizeof(a6));
669             a6.sin6_family = AF_INET6;
670             if (local_host_only)
671                 a6.sin6_addr = in6addr_loopback;
672             else
673                 a6.sin6_addr = in6addr_any;
674             a6.sin6_port = htons(port);
675         } else
676 #endif
677         {
678             a.sin_family = AF_INET;
679             if (local_host_only)
680                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
681             else
682                 a.sin_addr.s_addr = htonl(INADDR_ANY);
683             a.sin_port = htons((short)port);
684         }
685 #ifdef IPV6
686         retcode = bind(s, (addr->family == AF_INET6 ?
687                            (struct sockaddr *) &a6 :
688                            (struct sockaddr *) &a),
689                        (addr->family ==
690                         AF_INET6 ? sizeof(a6) : sizeof(a)));
691 #else
692         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
693 #endif
694         if (retcode != SOCKET_ERROR) {
695             err = 0;
696         } else {
697             err = WSAGetLastError();
698         }
699
700     if (err) {
701         ret->error = winsock_error_string(err);
702         return (Socket) ret;
703     }
704
705
706     if (listen(s, SOMAXCONN) == SOCKET_ERROR) {
707         closesocket(s);
708         ret->error = winsock_error_string(err);
709         return (Socket) ret;
710     }
711
712     /* Set up a select mechanism. This could be an AsyncSelect on a
713      * window, or an EventSelect on an event object. */
714     errstr = do_select(s, 1);
715     if (errstr) {
716         ret->error = errstr;
717         return (Socket) ret;
718     }
719
720     add234(sktree, ret);
721
722     return (Socket) ret;
723 }
724
725 static void sk_tcp_close(Socket sock)
726 {
727     extern char *do_select(SOCKET skt, int startup);
728     Actual_Socket s = (Actual_Socket) sock;
729
730     del234(sktree, s);
731     do_select(s->s, 0);
732     closesocket(s->s);
733     sfree(s);
734 }
735
736 /*
737  * The function which tries to send on a socket once it's deemed
738  * writable.
739  */
740 void try_send(Actual_Socket s)
741 {
742     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
743         int nsent;
744         DWORD err;
745         void *data;
746         int len, urgentflag;
747
748         if (s->sending_oob) {
749             urgentflag = MSG_OOB;
750             len = s->sending_oob;
751             data = &s->oobdata;
752         } else {
753             urgentflag = 0;
754             bufchain_prefix(&s->output_data, &data, &len);
755         }
756         nsent = send(s->s, data, len, urgentflag);
757         noise_ultralight(nsent);
758         if (nsent <= 0) {
759             err = (nsent < 0 ? WSAGetLastError() : 0);
760             if ((err < WSABASEERR && nsent < 0) || err == WSAEWOULDBLOCK) {
761                 /*
762                  * Perfectly normal: we've sent all we can for the moment.
763                  * 
764                  * (Some WinSock send() implementations can return
765                  * <0 but leave no sensible error indication -
766                  * WSAGetLastError() is called but returns zero or
767                  * a small number - so we check that case and treat
768                  * it just like WSAEWOULDBLOCK.)
769                  */
770                 s->writable = FALSE;
771                 return;
772             } else if (nsent == 0 ||
773                        err == WSAECONNABORTED || err == WSAECONNRESET) {
774                 /*
775                  * If send() returns CONNABORTED or CONNRESET, we
776                  * unfortunately can't just call plug_closing(),
777                  * because it's quite likely that we're currently
778                  * _in_ a call from the code we'd be calling back
779                  * to, so we'd have to make half the SSH code
780                  * reentrant. Instead we flag a pending error on
781                  * the socket, to be dealt with (by calling
782                  * plug_closing()) at some suitable future moment.
783                  */
784                 s->pending_error = err;
785                 return;
786             } else {
787                 fatalbox(winsock_error_string(err));
788             }
789         } else {
790             if (s->sending_oob) {
791                 if (nsent < len) {
792                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
793                     s->sending_oob = len - nsent;
794                 } else {
795                     s->sending_oob = 0;
796                 }
797             } else {
798                 bufchain_consume(&s->output_data, nsent);
799             }
800         }
801     }
802 }
803
804 static int sk_tcp_write(Socket sock, char *buf, int len)
805 {
806     Actual_Socket s = (Actual_Socket) sock;
807
808     /*
809      * Add the data to the buffer list on the socket.
810      */
811     bufchain_add(&s->output_data, buf, len);
812
813     /*
814      * Now try sending from the start of the buffer list.
815      */
816     if (s->writable)
817         try_send(s);
818
819     return bufchain_size(&s->output_data);
820 }
821
822 static int sk_tcp_write_oob(Socket sock, char *buf, int len)
823 {
824     Actual_Socket s = (Actual_Socket) sock;
825
826     /*
827      * Replace the buffer list on the socket with the data.
828      */
829     bufchain_clear(&s->output_data);
830     assert(len <= sizeof(s->oobdata));
831     memcpy(s->oobdata, buf, len);
832     s->sending_oob = len;
833
834     /*
835      * Now try sending from the start of the buffer list.
836      */
837     if (s->writable)
838         try_send(s);
839
840     return s->sending_oob;
841 }
842
843 int select_result(WPARAM wParam, LPARAM lParam)
844 {
845     int ret, open;
846     DWORD err;
847     char buf[20480];                   /* nice big buffer for plenty of speed */
848     Actual_Socket s;
849     u_long atmark;
850
851     /* wParam is the socket itself */
852     s = find234(sktree, (void *) wParam, cmpforsearch);
853     if (!s)
854         return 1;                      /* boggle */
855
856     if ((err = WSAGETSELECTERROR(lParam)) != 0) {
857         /*
858          * An error has occurred on this socket. Pass it to the
859          * plug.
860          */
861         return plug_closing(s->plug, winsock_error_string(err), err, 0);
862     }
863
864     noise_ultralight(lParam);
865
866     switch (WSAGETSELECTEVENT(lParam)) {
867       case FD_CONNECT:
868         s->connected = s->writable = 1;
869         break;
870       case FD_READ:
871         /* In the case the socket is still frozen, we don't even bother */
872         if (s->frozen) {
873             s->frozen_readable = 1;
874             break;
875         }
876
877         /*
878          * We have received data on the socket. For an oobinline
879          * socket, this might be data _before_ an urgent pointer,
880          * in which case we send it to the back end with type==1
881          * (data prior to urgent).
882          */
883         if (s->oobinline) {
884             atmark = 1;
885             ioctlsocket(s->s, SIOCATMARK, &atmark);
886             /*
887              * Avoid checking the return value from ioctlsocket(),
888              * on the grounds that some WinSock wrappers don't
889              * support it. If it does nothing, we get atmark==1,
890              * which is equivalent to `no OOB pending', so the
891              * effect will be to non-OOB-ify any OOB data.
892              */
893         } else
894             atmark = 1;
895
896         ret = recv(s->s, buf, sizeof(buf), 0);
897         noise_ultralight(ret);
898         if (ret < 0) {
899             err = WSAGetLastError();
900             if (err == WSAEWOULDBLOCK) {
901                 break;
902             }
903         }
904         if (ret < 0) {
905             return plug_closing(s->plug, winsock_error_string(err), err,
906                                 0);
907         } else if (0 == ret) {
908             return plug_closing(s->plug, NULL, 0, 0);
909         } else {
910             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
911         }
912         break;
913       case FD_OOB:
914         /*
915          * This will only happen on a non-oobinline socket. It
916          * indicates that we can immediately perform an OOB read
917          * and get back OOB data, which we will send to the back
918          * end with type==2 (urgent data).
919          */
920         ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
921         noise_ultralight(ret);
922         if (ret <= 0) {
923             fatalbox(ret == 0 ? "Internal networking trouble" :
924                      winsock_error_string(WSAGetLastError()));
925         } else {
926             return plug_receive(s->plug, 2, buf, ret);
927         }
928         break;
929       case FD_WRITE:
930         {
931             int bufsize_before, bufsize_after;
932             s->writable = 1;
933             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
934             try_send(s);
935             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
936             if (bufsize_after < bufsize_before)
937                 plug_sent(s->plug, bufsize_after);
938         }
939         break;
940       case FD_CLOSE:
941         /* Signal a close on the socket. First read any outstanding data. */
942         open = 1;
943         do {
944             ret = recv(s->s, buf, sizeof(buf), 0);
945             if (ret < 0) {
946                 err = WSAGetLastError();
947                 if (err == WSAEWOULDBLOCK)
948                     break;
949                 return plug_closing(s->plug, winsock_error_string(err),
950                                     err, 0);
951             } else {
952                 if (ret)
953                     open &= plug_receive(s->plug, 0, buf, ret);
954                 else
955                     open &= plug_closing(s->plug, NULL, 0, 0);
956             }
957         } while (ret > 0);
958         return open;
959        case FD_ACCEPT:
960         {
961             struct sockaddr_in isa;
962             int addrlen = sizeof(struct sockaddr_in);
963             SOCKET t;  /* socket of connection */
964
965             memset(&isa, 0, sizeof(struct sockaddr_in));
966             err = 0;
967             t = accept(s->s,&isa,&addrlen);
968             if (t == INVALID_SOCKET)
969             {
970                 err = WSAGetLastError();
971                 if (err == WSATRY_AGAIN)
972                     break;
973             }
974
975             if (s->localhost_only &&
976                 ntohl(isa.sin_addr.s_addr) != INADDR_LOOPBACK) {
977                 closesocket(t);        /* dodgy WinSock let nonlocal through */
978             } else if (plug_accepting(s->plug, (void*)t)) {
979                 closesocket(t);        /* denied or error */
980             }
981         }
982     }
983
984     return 1;
985 }
986
987 /*
988  * Deal with socket errors detected in try_send().
989  */
990 void net_pending_errors(void)
991 {
992     int i;
993     Actual_Socket s;
994
995     /*
996      * This might be a fiddly business, because it's just possible
997      * that handling a pending error on one socket might cause
998      * others to be closed. (I can't think of any reason this might
999      * happen in current SSH implementation, but to maintain
1000      * generality of this network layer I'll assume the worst.)
1001      * 
1002      * So what we'll do is search the socket list for _one_ socket
1003      * with a pending error, and then handle it, and then search
1004      * the list again _from the beginning_. Repeat until we make a
1005      * pass with no socket errors present. That way we are
1006      * protected against the socket list changing under our feet.
1007      */
1008
1009     do {
1010         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1011             if (s->pending_error) {
1012                 /*
1013                  * An error has occurred on this socket. Pass it to the
1014                  * plug.
1015                  */
1016                 plug_closing(s->plug,
1017                              winsock_error_string(s->pending_error),
1018                              s->pending_error, 0);
1019                 break;
1020             }
1021         }
1022     } while (s);
1023 }
1024
1025 /*
1026  * Each socket abstraction contains a `void *' private field in
1027  * which the client can keep state.
1028  */
1029 void sk_set_private_ptr(Socket sock, void *ptr)
1030 {
1031     Actual_Socket s = (Actual_Socket) sock;
1032     s->private_ptr = ptr;
1033 }
1034
1035 void *sk_get_private_ptr(Socket sock)
1036 {
1037     Actual_Socket s = (Actual_Socket) sock;
1038     return s->private_ptr;
1039 }
1040
1041 /*
1042  * Special error values are returned from sk_namelookup and sk_new
1043  * if there's a problem. These functions extract an error message,
1044  * or return NULL if there's no problem.
1045  */
1046 char *sk_addr_error(SockAddr addr)
1047 {
1048     return addr->error;
1049 }
1050 static char *sk_tcp_socket_error(Socket sock)
1051 {
1052     Actual_Socket s = (Actual_Socket) sock;
1053     return s->error;
1054 }
1055
1056 void sk_set_frozen(Socket sock, int is_frozen)
1057 {
1058     Actual_Socket s = (Actual_Socket) sock;
1059     if (s->frozen == is_frozen)
1060         return;
1061     s->frozen = is_frozen;
1062     if (!is_frozen && s->frozen_readable) {
1063         char c;
1064         recv(s->s, &c, 1, MSG_PEEK);
1065     }
1066     s->frozen_readable = 0;
1067 }
1068
1069 /*
1070  * For Plink: enumerate all sockets currently active.
1071  */
1072 SOCKET first_socket(int *state)
1073 {
1074     Actual_Socket s;
1075     *state = 0;
1076     s = index234(sktree, (*state)++);
1077     return s ? s->s : INVALID_SOCKET;
1078 }
1079
1080 SOCKET next_socket(int *state)
1081 {
1082     Actual_Socket s = index234(sktree, (*state)++);
1083     return s ? s->s : INVALID_SOCKET;
1084 }