]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - winnet.c
Run entire source base through GNU indent to tidy up the varying
[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
52 #define DEFINE_PLUG_METHOD_MACROS
53 #include "putty.h"
54 #include "network.h"
55 #include "tree234.h"
56
57 #define BUFFER_GRANULE  512
58
59 struct Socket_tag {
60     struct socket_function_table *fn;
61     /* the above variable absolutely *must* be the first in this structure */
62     char *error;
63     SOCKET s;
64     Plug plug;
65     void *private_ptr;
66     struct buffer *head, *tail;
67     int writable;
68     int sending_oob;
69     int oobinline;
70 };
71
72 /*
73  * We used to typedef struct Socket_tag *Socket.
74  *
75  * Since we have made the networking abstraction slightly more
76  * abstract, Socket no longer means a tcp socket (it could mean
77  * an ssl socket).  So now we must use Actual_Socket when we know
78  * we are talking about a tcp socket.
79  */
80 typedef struct Socket_tag *Actual_Socket;
81
82 struct SockAddr_tag {
83     char *error;
84     /* address family this belongs to, AF_INET for IPv4, AF_INET6 for IPv6. */
85     int family;
86     unsigned long address;             /* Address IPv4 style. */
87 #ifdef IPV6
88     struct addrinfo *ai;               /* Address IPv6 style. */
89 #endif
90     /*
91      * We need to have this lengthy enough to hold *any* hostname
92      * (including IPv6 reverse...)
93      */
94     char realhost[8192];
95 };
96
97 struct buffer {
98     struct buffer *next;
99     int buflen, bufpos;
100     char buf[BUFFER_GRANULE];
101 };
102
103 static tree234 *sktree;
104
105 static int cmpfortree(void *av, void *bv)
106 {
107     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
108     unsigned long as = (unsigned long) a->s, bs = (unsigned long) b->s;
109     if (as < bs)
110         return -1;
111     if (as > bs)
112         return +1;
113     return 0;
114 }
115
116 static int cmpforsearch(void *av, void *bv)
117 {
118     Actual_Socket b = (Actual_Socket) bv;
119     unsigned long as = (unsigned long) av, bs = (unsigned long) b->s;
120     if (as < bs)
121         return -1;
122     if (as > bs)
123         return +1;
124     return 0;
125 }
126
127 void sk_init(void)
128 {
129     sktree = newtree234(cmpfortree);
130 }
131
132 char *winsock_error_string(int error)
133 {
134     switch (error) {
135       case WSAEACCES:
136         return "Network error: Permission denied";
137       case WSAEADDRINUSE:
138         return "Network error: Address already in use";
139       case WSAEADDRNOTAVAIL:
140         return "Network error: Cannot assign requested address";
141       case WSAEAFNOSUPPORT:
142         return
143             "Network error: Address family not supported by protocol family";
144       case WSAEALREADY:
145         return "Network error: Operation already in progress";
146       case WSAECONNABORTED:
147         return "Network error: Software caused connection abort";
148       case WSAECONNREFUSED:
149         return "Network error: Connection refused";
150       case WSAECONNRESET:
151         return "Network error: Connection reset by peer";
152       case WSAEDESTADDRREQ:
153         return "Network error: Destination address required";
154       case WSAEFAULT:
155         return "Network error: Bad address";
156       case WSAEHOSTDOWN:
157         return "Network error: Host is down";
158       case WSAEHOSTUNREACH:
159         return "Network error: No route to host";
160       case WSAEINPROGRESS:
161         return "Network error: Operation now in progress";
162       case WSAEINTR:
163         return "Network error: Interrupted function call";
164       case WSAEINVAL:
165         return "Network error: Invalid argument";
166       case WSAEISCONN:
167         return "Network error: Socket is already connected";
168       case WSAEMFILE:
169         return "Network error: Too many open files";
170       case WSAEMSGSIZE:
171         return "Network error: Message too long";
172       case WSAENETDOWN:
173         return "Network error: Network is down";
174       case WSAENETRESET:
175         return "Network error: Network dropped connection on reset";
176       case WSAENETUNREACH:
177         return "Network error: Network is unreachable";
178       case WSAENOBUFS:
179         return "Network error: No buffer space available";
180       case WSAENOPROTOOPT:
181         return "Network error: Bad protocol option";
182       case WSAENOTCONN:
183         return "Network error: Socket is not connected";
184       case WSAENOTSOCK:
185         return "Network error: Socket operation on non-socket";
186       case WSAEOPNOTSUPP:
187         return "Network error: Operation not supported";
188       case WSAEPFNOSUPPORT:
189         return "Network error: Protocol family not supported";
190       case WSAEPROCLIM:
191         return "Network error: Too many processes";
192       case WSAEPROTONOSUPPORT:
193         return "Network error: Protocol not supported";
194       case WSAEPROTOTYPE:
195         return "Network error: Protocol wrong type for socket";
196       case WSAESHUTDOWN:
197         return "Network error: Cannot send after socket shutdown";
198       case WSAESOCKTNOSUPPORT:
199         return "Network error: Socket type not supported";
200       case WSAETIMEDOUT:
201         return "Network error: Connection timed out";
202       case WSAEWOULDBLOCK:
203         return "Network error: Resource temporarily unavailable";
204       case WSAEDISCON:
205         return "Network error: Graceful shutdown in progress";
206       default:
207         return "Unknown network error";
208     }
209 }
210
211 SockAddr sk_namelookup(char *host, char **canonicalname)
212 {
213     SockAddr ret = smalloc(sizeof(struct SockAddr_tag));
214     unsigned long a;
215     struct hostent *h = NULL;
216
217     /* Clear the structure and default to IPv4. */
218     memset(ret, 0, sizeof(struct SockAddr_tag));
219     ret->family = 0;                   /* We set this one when we have resolved the host. */
220     *canonicalname = ret->realhost;    /* This makes sure we always have a hostname to return. */
221
222     if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
223 #ifdef IPV6
224
225         /* Try to get the getaddrinfo() function from wship6.dll */
226         /* This way one doesn't need to have IPv6 dll's to use PuTTY and
227          * it will fallback to IPv4. */
228         typedef int (CALLBACK * FGETADDRINFO) (const char *nodename,
229                                                const char *servname,
230                                                const struct addrinfo *
231                                                hints,
232                                                struct addrinfo ** res);
233         FGETADDRINFO fGetAddrInfo = NULL;
234
235         HINSTANCE dllWSHIP6 = LoadLibrary("wship6.dll");
236         if (dllWSHIP6)
237             fGetAddrInfo = (FGETADDRINFO) GetProcAddress(dllWSHIP6,
238                                                          "getaddrinfo");
239
240         /*
241          * Use fGetAddrInfo when it's available (which usually also
242          * means IPv6 is installed...)
243          */
244         if (fGetAddrInfo) {
245             /*debug(("Resolving \"%s\" with getaddrinfo()  (IPv4+IPv6 capable)...\n", host)); */
246             if (fGetAddrInfo(host, NULL, NULL, &ret->ai) == 0)
247                 ret->family = ret->ai->ai_family;
248         } else
249 #endif
250         {
251             /*
252              * Otherwise use the IPv4-only gethostbyname...
253              * (NOTE: we don't use gethostbyname as a
254              * fallback!)
255              */
256             if (ret->family == 0) {
257                 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
258                 if (h = gethostbyname(host))
259                     ret->family = AF_INET;
260             }
261         }
262         /*debug(("Done resolving...(family is %d) AF_INET = %d, AF_INET6 = %d\n", ret->family, AF_INET, AF_INET6)); */
263
264         if (ret->family == 0) {
265             DWORD err = WSAGetLastError();
266             ret->error = (err == WSAENETDOWN ? "Network is down" :
267                           err ==
268                           WSAHOST_NOT_FOUND ? "Host does not exist" : err
269                           == WSATRY_AGAIN ? "Host not found" :
270 #ifdef IPV6
271                           fGetAddrInfo ? "getaddrinfo: unknown error" :
272 #endif
273                           "gethostbyname: unknown error");
274 #ifdef DEBUG
275             {
276                 LPVOID lpMsgBuf;
277                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
278                               FORMAT_MESSAGE_FROM_SYSTEM |
279                               FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err,
280                               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
281                               (LPTSTR) & lpMsgBuf, 0, NULL);
282                 /*debug(("Error %ld: %s (h=%lx)\n", err, lpMsgBuf, h)); */
283                 /* Free the buffer. */
284                 LocalFree(lpMsgBuf);
285             }
286 #endif
287         } else {
288             ret->error = NULL;
289
290 #ifdef IPV6
291             /* If we got an address info use that... */
292             if (ret->ai) {
293                 typedef int (CALLBACK * FGETNAMEINFO)
294                  (const struct sockaddr FAR * sa, socklen_t salen,
295                   char FAR * host, size_t hostlen, char FAR * serv,
296                   size_t servlen, int flags);
297                 FGETNAMEINFO fGetNameInfo = NULL;
298
299                 /* Are we in IPv4 fallback mode? */
300                 /* We put the IPv4 address into the a variable so we can further-on use the IPv4 code... */
301                 if (ret->family == AF_INET)
302                     memcpy(&a,
303                            (char *) &((SOCKADDR_IN *) ret->ai->
304                                       ai_addr)->sin_addr, sizeof(a));
305
306                 /* Now let's find that canonicalname... */
307                 if ((dllWSHIP6)
308                     && (fGetNameInfo =
309                         (FGETNAMEINFO) GetProcAddress(dllWSHIP6,
310                                                       "getnameinfo"))) {
311                     if (fGetNameInfo
312                         ((struct sockaddr *) ret->ai->ai_addr,
313                          ret->family ==
314                          AF_INET ? sizeof(SOCKADDR_IN) :
315                          sizeof(SOCKADDR_IN6), ret->realhost,
316                          sizeof(ret->realhost), NULL, 0, 0) != 0) {
317                         strncpy(ret->realhost, host,
318                                 sizeof(ret->realhost));
319                     }
320                 }
321             }
322             /* We used the IPv4-only gethostbyname()... */
323             else
324 #endif
325             {
326                 memcpy(&a, h->h_addr, sizeof(a));
327                 /* This way we are always sure the h->h_name is valid :) */
328                 strncpy(ret->realhost, h->h_name, sizeof(ret->realhost));
329             }
330         }
331 #ifdef IPV6
332         FreeLibrary(dllWSHIP6);
333 #endif
334     } else {
335         /*
336          * This must be a numeric IPv4 address because it caused a
337          * success return from inet_addr.
338          */
339         ret->family = AF_INET;
340         *canonicalname = host;
341     }
342     ret->address = ntohl(a);
343     return ret;
344 }
345
346 void sk_addr_free(SockAddr addr)
347 {
348     sfree(addr);
349 }
350
351 static Plug sk_tcp_plug(Socket sock, Plug p)
352 {
353     Actual_Socket s = (Actual_Socket) sock;
354     Plug ret = s->plug;
355     if (p)
356         s->plug = p;
357     return ret;
358 }
359
360 static void sk_tcp_flush(Socket s)
361 {
362     /*
363      * We send data to the socket as soon as we can anyway,
364      * so we don't need to do anything here.  :-)
365      */
366 }
367
368 void sk_tcp_close(Socket s);
369 void sk_tcp_write(Socket s, char *data, int len);
370 void sk_tcp_write_oob(Socket s, char *data, int len);
371 char *sk_tcp_socket_error(Socket s);
372
373 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
374               Plug plug)
375 {
376     static struct socket_function_table fn_table = {
377         sk_tcp_plug,
378         sk_tcp_close,
379         sk_tcp_write,
380         sk_tcp_write_oob,
381         sk_tcp_flush,
382         sk_tcp_socket_error
383     };
384
385     SOCKET s;
386 #ifdef IPV6
387     SOCKADDR_IN6 a6;
388 #endif
389     SOCKADDR_IN a;
390     DWORD err;
391     char *errstr;
392     Actual_Socket ret;
393     extern char *do_select(SOCKET skt, int startup);
394     short localport;
395
396     /*
397      * Create Socket structure.
398      */
399     ret = smalloc(sizeof(struct Socket_tag));
400     ret->fn = &fn_table;
401     ret->error = NULL;
402     ret->plug = plug;
403     ret->head = ret->tail = NULL;
404     ret->writable = 1;                 /* to start with */
405     ret->sending_oob = 0;
406
407     /*
408      * Open socket.
409      */
410     s = socket(addr->family, SOCK_STREAM, 0);
411     ret->s = s;
412
413     if (s == INVALID_SOCKET) {
414         err = WSAGetLastError();
415         ret->error = winsock_error_string(err);
416         return (Socket) ret;
417     }
418
419     ret->oobinline = oobinline;
420     if (oobinline) {
421         BOOL b = TRUE;
422         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
423     }
424
425     /*
426      * Bind to local address.
427      */
428     if (privport)
429         localport = 1023;              /* count from 1023 downwards */
430     else
431         localport = 0;                 /* just use port 0 (ie winsock picks) */
432
433     /* Loop round trying to bind */
434     while (1) {
435         int retcode;
436
437 #ifdef IPV6
438         if (addr->family == AF_INET6) {
439             memset(&a6, 0, sizeof(a6));
440             a6.sin6_family = AF_INET6;
441 /*a6.sin6_addr      = in6addr_any; *//* == 0 */
442             a6.sin6_port = htons(localport);
443         } else
444 #endif
445         {
446             a.sin_family = AF_INET;
447             a.sin_addr.s_addr = htonl(INADDR_ANY);
448             a.sin_port = htons(localport);
449         }
450 #ifdef IPV6
451         retcode = bind(s, (addr->family == AF_INET6 ?
452                            (struct sockaddr *) &a6 :
453                            (struct sockaddr *) &a),
454                        (addr->family ==
455                         AF_INET6 ? sizeof(a6) : sizeof(a)));
456 #else
457         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
458 #endif
459         if (retcode != SOCKET_ERROR) {
460             err = 0;
461             break;                     /* done */
462         } else {
463             err = WSAGetLastError();
464             if (err != WSAEADDRINUSE)  /* failed, for a bad reason */
465                 break;
466         }
467
468         if (localport == 0)
469             break;                     /* we're only looping once */
470         localport--;
471         if (localport == 0)
472             break;                     /* we might have got to the end */
473     }
474
475     if (err) {
476         ret->error = winsock_error_string(err);
477         return (Socket) ret;
478     }
479
480     /*
481      * Connect to remote address.
482      */
483 #ifdef IPV6
484     if (addr->family == AF_INET6) {
485         memset(&a, 0, sizeof(a));
486         a6.sin6_family = AF_INET6;
487         a6.sin6_port = htons((short) port);
488         a6.sin6_addr =
489             ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
490     } else
491 #endif
492     {
493         a.sin_family = AF_INET;
494         a.sin_addr.s_addr = htonl(addr->address);
495         a.sin_port = htons((short) port);
496     }
497     if ((
498 #ifdef IPV6
499             connect(s, ((addr->family == AF_INET6) ?
500                         (struct sockaddr *) &a6 : (struct sockaddr *) &a),
501                     (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
502 #else
503             connect(s, (struct sockaddr *) &a, sizeof(a))
504 #endif
505         ) == SOCKET_ERROR) {
506         err = WSAGetLastError();
507         ret->error = winsock_error_string(err);
508         return (Socket) ret;
509     }
510
511     /* Set up a select mechanism. This could be an AsyncSelect on a
512      * window, or an EventSelect on an event object. */
513     errstr = do_select(s, 1);
514     if (errstr) {
515         ret->error = errstr;
516         return (Socket) ret;
517     }
518
519     add234(sktree, ret);
520
521     return (Socket) ret;
522 }
523
524 static void sk_tcp_close(Socket sock)
525 {
526     extern char *do_select(SOCKET skt, int startup);
527     Actual_Socket s = (Actual_Socket) sock;
528
529     del234(sktree, s);
530     do_select(s->s, 0);
531     closesocket(s->s);
532     sfree(s);
533 }
534
535 /*
536  * The function which tries to send on a socket once it's deemed
537  * writable.
538  */
539 void try_send(Actual_Socket s)
540 {
541     while (s->head) {
542         int nsent;
543         DWORD err;
544         int len, urgentflag;
545
546         if (s->sending_oob) {
547             urgentflag = MSG_OOB;
548             len = s->sending_oob;
549         } else {
550             urgentflag = 0;
551             len = s->head->buflen - s->head->bufpos;
552         }
553
554         nsent =
555             send(s->s, s->head->buf + s->head->bufpos, len, urgentflag);
556         noise_ultralight(nsent);
557         if (nsent <= 0) {
558             err = (nsent < 0 ? WSAGetLastError() : 0);
559             if ((err == 0 && nsent < 0) || err == WSAEWOULDBLOCK) {
560                 /*
561                  * Perfectly normal: we've sent all we can for the moment.
562                  * 
563                  * (Apparently some WinSocks can return <0 but
564                  * leave no error indication - WSAGetLastError() is
565                  * called but returns zero - so we check that case
566                  * and treat it just like WSAEWOULDBLOCK.)
567                  */
568                 s->writable = FALSE;
569                 return;
570             } else if (nsent == 0 ||
571                        err == WSAECONNABORTED || err == WSAECONNRESET) {
572                 /*
573                  * FIXME. This will have to be done better when we
574                  * start managing multiple sockets (e.g. SSH port
575                  * forwarding), because if we get CONNRESET while
576                  * trying to write a particular forwarded socket
577                  * then it isn't necessarily the end of the world.
578                  * Ideally I'd like to pass the error code back to
579                  * somewhere the next select_result() will see it,
580                  * but that might be hard. Perhaps I should pass it
581                  * back to be queued in the Windows front end bit.
582                  */
583                 fatalbox(winsock_error_string(err));
584             } else {
585                 fatalbox(winsock_error_string(err));
586             }
587         } else {
588             s->head->bufpos += nsent;
589             if (s->sending_oob)
590                 s->sending_oob -= nsent;
591             if (s->head->bufpos >= s->head->buflen) {
592                 struct buffer *tmp = s->head;
593                 s->head = tmp->next;
594                 sfree(tmp);
595                 if (!s->head)
596                     s->tail = NULL;
597             }
598         }
599     }
600 }
601
602 static void sk_tcp_write(Socket sock, char *buf, int len)
603 {
604     Actual_Socket s = (Actual_Socket) sock;
605
606     /*
607      * Add the data to the buffer list on the socket.
608      */
609     if (s->tail && s->tail->buflen < BUFFER_GRANULE) {
610         int copylen = min(len, BUFFER_GRANULE - s->tail->buflen);
611         memcpy(s->tail->buf + s->tail->buflen, buf, copylen);
612         buf += copylen;
613         len -= copylen;
614         s->tail->buflen += copylen;
615     }
616     while (len > 0) {
617         int grainlen = min(len, BUFFER_GRANULE);
618         struct buffer *newbuf;
619         newbuf = smalloc(sizeof(struct buffer));
620         newbuf->bufpos = 0;
621         newbuf->buflen = grainlen;
622         memcpy(newbuf->buf, buf, grainlen);
623         buf += grainlen;
624         len -= grainlen;
625         if (s->tail)
626             s->tail->next = newbuf;
627         else
628             s->head = s->tail = newbuf;
629         newbuf->next = NULL;
630         s->tail = newbuf;
631     }
632
633     /*
634      * Now try sending from the start of the buffer list.
635      */
636     if (s->writable)
637         try_send(s);
638 }
639
640 static void sk_tcp_write_oob(Socket sock, char *buf, int len)
641 {
642     Actual_Socket s = (Actual_Socket) sock;
643
644     /*
645      * Replace the buffer list on the socket with the data.
646      */
647     if (!s->head) {
648         s->head = smalloc(sizeof(struct buffer));
649     } else {
650         struct buffer *walk = s->head->next;
651         while (walk) {
652             struct buffer *tmp = walk;
653             walk = tmp->next;
654             sfree(tmp);
655         }
656     }
657     s->head->next = NULL;
658     s->tail = s->head;
659     s->head->buflen = len;
660     memcpy(s->head->buf, buf, len);
661
662     /*
663      * Set the Urgent marker.
664      */
665     s->sending_oob = len;
666
667     /*
668      * Now try sending from the start of the buffer list.
669      */
670     if (s->writable)
671         try_send(s);
672 }
673
674 int select_result(WPARAM wParam, LPARAM lParam)
675 {
676     int ret, open;
677     DWORD err;
678     char buf[20480];                   /* nice big buffer for plenty of speed */
679     Actual_Socket s;
680     u_long atmark;
681
682     /* wParam is the socket itself */
683     s = find234(sktree, (void *) wParam, cmpforsearch);
684     if (!s)
685         return 1;                      /* boggle */
686
687     if ((err = WSAGETSELECTERROR(lParam)) != 0) {
688         /*
689          * An error has occurred on this socket. Pass it to the
690          * plug.
691          */
692         return plug_closing(s->plug, winsock_error_string(err), err, 0);
693     }
694
695     noise_ultralight(lParam);
696
697     switch (WSAGETSELECTEVENT(lParam)) {
698       case FD_READ:
699         /*
700          * We have received data on the socket. For an oobinline
701          * socket, this might be data _before_ an urgent pointer,
702          * in which case we send it to the back end with type==1
703          * (data prior to urgent).
704          */
705         if (s->oobinline) {
706             atmark = 1;
707             ioctlsocket(s->s, SIOCATMARK, &atmark);
708             /*
709              * Avoid checking the return value from ioctlsocket(),
710              * on the grounds that some WinSock wrappers don't
711              * support it. If it does nothing, we get atmark==1,
712              * which is equivalent to `no OOB pending', so the
713              * effect will be to non-OOB-ify any OOB data.
714              */
715         } else
716             atmark = 1;
717
718         ret = recv(s->s, buf, sizeof(buf), 0);
719         noise_ultralight(ret);
720         if (ret < 0) {
721             err = WSAGetLastError();
722             if (err == WSAEWOULDBLOCK) {
723                 break;
724             }
725         }
726         if (ret < 0) {
727             return plug_closing(s->plug, winsock_error_string(err), err,
728                                 0);
729         } else if (0 == ret) {
730             return plug_closing(s->plug, NULL, 0, 0);
731         } else {
732             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
733         }
734         break;
735       case FD_OOB:
736         /*
737          * This will only happen on a non-oobinline socket. It
738          * indicates that we can immediately perform an OOB read
739          * and get back OOB data, which we will send to the back
740          * end with type==2 (urgent data).
741          */
742         ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
743         noise_ultralight(ret);
744         if (ret <= 0) {
745             fatalbox(ret == 0 ? "Internal networking trouble" :
746                      winsock_error_string(WSAGetLastError()));
747         } else {
748             return plug_receive(s->plug, 2, buf, ret);
749         }
750         break;
751       case FD_WRITE:
752         s->writable = 1;
753         try_send(s);
754         break;
755       case FD_CLOSE:
756         /* Signal a close on the socket. First read any outstanding data. */
757         open = 1;
758         do {
759             ret = recv(s->s, buf, sizeof(buf), 0);
760             if (ret < 0) {
761                 err = WSAGetLastError();
762                 if (err == WSAEWOULDBLOCK)
763                     break;
764                 return plug_closing(s->plug, winsock_error_string(err),
765                                     err, 0);
766             } else {
767                 if (ret)
768                     open &= plug_receive(s->plug, 0, buf, ret);
769                 else
770                     open &= plug_closing(s->plug, NULL, 0, 0);
771             }
772         } while (ret > 0);
773         return open;
774     }
775
776     return 1;
777 }
778
779 /*
780  * Each socket abstraction contains a `void *' private field in
781  * which the client can keep state.
782  */
783 void sk_set_private_ptr(Socket sock, void *ptr)
784 {
785     Actual_Socket s = (Actual_Socket) sock;
786     s->private_ptr = ptr;
787 }
788
789 void *sk_get_private_ptr(Socket sock)
790 {
791     Actual_Socket s = (Actual_Socket) sock;
792     return s->private_ptr;
793 }
794
795 /*
796  * Special error values are returned from sk_namelookup and sk_new
797  * if there's a problem. These functions extract an error message,
798  * or return NULL if there's no problem.
799  */
800 char *sk_addr_error(SockAddr addr)
801 {
802     return addr->error;
803 }
804 static char *sk_tcp_socket_error(Socket sock)
805 {
806     Actual_Socket s = (Actual_Socket) sock;
807     return s->error;
808 }
809
810 /*
811  * For Plink: enumerate all sockets currently active.
812  */
813 SOCKET first_socket(int *state)
814 {
815     Actual_Socket s;
816     *state = 0;
817     s = index234(sktree, (*state)++);
818     return s ? s->s : INVALID_SOCKET;
819 }
820
821 SOCKET next_socket(int *state)
822 {
823     Actual_Socket s = index234(sktree, (*state)++);
824     return s ? s->s : INVALID_SOCKET;
825 }