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