]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
Integrate unfix.org's IPv6 patches up to level 10, with rather a lot
[PuTTY.git] / unix / uxnet.c
1 /*
2  * Unix networking abstraction.
3  */
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <assert.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <unistd.h>
11 #include <sys/types.h>
12 #include <sys/socket.h>
13 #include <sys/ioctl.h>
14 #include <arpa/inet.h>
15 #include <netinet/in.h>
16 #include <netinet/tcp.h>
17 #include <netdb.h>
18 #include <sys/un.h>
19
20 #define DEFINE_PLUG_METHOD_MACROS
21 #include "putty.h"
22 #include "network.h"
23 #include "tree234.h"
24
25 #ifndef X11_UNIX_PATH
26 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
27 #endif
28
29 #define ipv4_is_loopback(addr) (inet_netof(addr) == IN_LOOPBACKNET)
30
31 struct Socket_tag {
32     struct socket_function_table *fn;
33     /* the above variable absolutely *must* be the first in this structure */
34     const char *error;
35     int s;
36     Plug plug;
37     void *private_ptr;
38     bufchain output_data;
39     int connected;
40     int writable;
41     int frozen; /* this causes readability notifications to be ignored */
42     int frozen_readable; /* this means we missed at least one readability
43                           * notification while we were frozen */
44     int localhost_only;                /* for listening sockets */
45     char oobdata[1];
46     int sending_oob;
47     int oobpending;                    /* is there OOB data available to read? */
48     int oobinline;
49     int pending_error;                 /* in case send() returns error */
50     int listener;
51 };
52
53 /*
54  * We used to typedef struct Socket_tag *Socket.
55  *
56  * Since we have made the networking abstraction slightly more
57  * abstract, Socket no longer means a tcp socket (it could mean
58  * an ssl socket).  So now we must use Actual_Socket when we know
59  * we are talking about a tcp socket.
60  */
61 typedef struct Socket_tag *Actual_Socket;
62
63 struct SockAddr_tag {
64     const char *error;
65     /*
66      * Which address family this address belongs to. AF_INET for
67      * IPv4; AF_INET6 for IPv6; AF_UNSPEC indicates that name
68      * resolution has not been done and a simple host name is held
69      * in this SockAddr structure.
70      */
71     int family;
72 #ifndef NO_IPV6
73     struct addrinfo *ai;               /* Address IPv6 style. */
74 #else
75     unsigned long address;             /* Address IPv4 style. */
76 #endif
77     char hostname[512];                /* Store an unresolved host name. */
78 };
79
80 static tree234 *sktree;
81
82 static void uxsel_tell(Actual_Socket s);
83
84 static int cmpfortree(void *av, void *bv)
85 {
86     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
87     int as = a->s, bs = b->s;
88     if (as < bs)
89         return -1;
90     if (as > bs)
91         return +1;
92     return 0;
93 }
94
95 static int cmpforsearch(void *av, void *bv)
96 {
97     Actual_Socket b = (Actual_Socket) bv;
98     int as = *(int *)av, bs = b->s;
99     if (as < bs)
100         return -1;
101     if (as > bs)
102         return +1;
103     return 0;
104 }
105
106 void sk_init(void)
107 {
108     sktree = newtree234(cmpfortree);
109 }
110
111 void sk_cleanup(void)
112 {
113     Actual_Socket s;
114     int i;
115
116     if (sktree) {
117         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
118             close(s->s);
119         }
120     }
121 }
122
123 const char *error_string(int error)
124 {
125     return strerror(error);
126 }
127
128 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
129 {
130     SockAddr ret = snew(struct SockAddr_tag);
131 #ifndef NO_IPV6
132     struct addrinfo hints;
133     int err;
134 #else
135     unsigned long a;
136     struct hostent *h = NULL;
137 #endif
138     char realhost[8192];
139
140     /* Clear the structure and default to IPv4. */
141     memset(ret, 0, sizeof(struct SockAddr_tag));
142     ret->family = 0;                   /* We set this one when we have resolved the host. */
143     *realhost = '\0';
144     ret->error = NULL;
145
146 #ifndef NO_IPV6
147     hints.ai_flags = AI_CANONNAME;
148     hints.ai_family = address_family;
149     hints.ai_socktype = 0;
150     hints.ai_protocol = 0;
151     hints.ai_addrlen = 0;
152     hints.ai_addr = NULL;
153     hints.ai_canonname = NULL;
154     hints.ai_next = NULL;
155     err = getaddrinfo(host, NULL, NULL, &ret->ai);
156     if (err != 0) {
157         ret->error = gai_strerror(err);
158         return ret;
159     }
160     ret->family = ret->ai->ai_family;
161     *realhost = '\0';
162     if (ret->ai->ai_canonname != NULL)
163         strncat(realhost, ret->ai->ai_canonname, sizeof(realhost) - 1);
164     else
165         strncat(realhost, host, sizeof(realhost) - 1);
166 #else
167     if ((a = inet_addr(host)) == (unsigned long) INADDR_NONE) {
168         /*
169          * Otherwise use the IPv4-only gethostbyname... (NOTE:
170          * we don't use gethostbyname as a fallback!)
171          */
172         if (ret->family == 0) {
173                 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
174                 if ( (h = gethostbyname(host)) )
175                         ret->family = AF_INET;
176         }
177         if (ret->family == 0) {
178                 ret->error = (h_errno == HOST_NOT_FOUND ||
179                     h_errno == NO_DATA ||
180                     h_errno == NO_ADDRESS ? "Host does not exist" :
181                     h_errno == TRY_AGAIN ?
182                     "Temporary name service failure" :
183                     "gethostbyname: unknown error");
184                 return ret;
185         }
186         memcpy(&a, h->h_addr, sizeof(a));
187         /* This way we are always sure the h->h_name is valid :) */
188         strncpy(realhost, h->h_name, sizeof(realhost));
189     } else {
190         /*
191          * This must be a numeric IPv4 address because it caused a
192          * success return from inet_addr.
193          */
194         ret->family = AF_INET;
195         strncpy(realhost, host, sizeof(realhost));
196     }
197     ret->address = ntohl(a);
198 #endif
199     realhost[lenof(realhost)-1] = '\0';
200     *canonicalname = snewn(1+strlen(realhost), char);
201     strcpy(*canonicalname, realhost);
202     return ret;
203 }
204
205 SockAddr sk_nonamelookup(const char *host)
206 {
207     SockAddr ret = snew(struct SockAddr_tag);
208     ret->error = NULL;
209     ret->family = AF_UNSPEC;
210     strncpy(ret->hostname, host, lenof(ret->hostname));
211     ret->hostname[lenof(ret->hostname)-1] = '\0';
212     return ret;
213 }
214
215 void sk_getaddr(SockAddr addr, char *buf, int buflen)
216 {
217
218     if (addr->family == AF_UNSPEC) {
219         strncpy(buf, addr->hostname, buflen);
220         buf[buflen-1] = '\0';
221     } else {
222 #ifndef NO_IPV6
223         if (getnameinfo(addr->ai->ai_addr, addr->ai->ai_addrlen, buf, buflen,
224                         NULL, 0, NI_NUMERICHOST) != 0) {
225             buf[0] = '\0';
226             strncat(buf, "<unknown>", buflen - 1);
227         }
228 #else
229         struct in_addr a;
230         assert(addr->family == AF_INET);
231         a.s_addr = htonl(addr->address);
232         strncpy(buf, inet_ntoa(a), buflen);
233         buf[buflen-1] = '\0';
234 #endif
235     }
236 }
237
238 int sk_hostname_is_local(char *name)
239 {
240     return !strcmp(name, "localhost");
241 }
242
243 int sk_address_is_local(SockAddr addr)
244 {
245
246     if (addr->family == AF_UNSPEC)
247         return 0;                      /* we don't know; assume not */
248     else {
249 #ifndef NO_IPV6
250         if (addr->family == AF_INET)
251             return ipv4_is_loopback(
252                 ((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr);
253         else if (addr->family == AF_INET6)
254             return IN6_IS_ADDR_LOOPBACK(
255                 &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr);
256         else
257             return 0;
258 #else
259         struct in_addr a;
260         assert(addr->family == AF_INET);
261         a.s_addr = htonl(addr->address);
262         return ipv4_is_loopback(a);
263 #endif
264     }
265 }
266
267 int sk_addrtype(SockAddr addr)
268 {
269     return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
270 #ifndef NO_IPV6
271             addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
272 #endif
273             ADDRTYPE_NAME);
274 }
275
276 void sk_addrcopy(SockAddr addr, char *buf)
277 {
278
279 #ifndef NO_IPV6
280     if (addr->family == AF_INET)
281         memcpy(buf, &((struct sockaddr_in *)addr->ai->ai_addr)->sin_addr,
282                sizeof(struct in_addr));
283     else if (addr->family == AF_INET6)
284         memcpy(buf, &((struct sockaddr_in6 *)addr->ai->ai_addr)->sin6_addr,
285                sizeof(struct in6_addr));
286     else
287         assert(FALSE);
288 #else
289     struct in_addr a;
290
291     assert(addr->family == AF_INET);
292     a.s_addr = htonl(addr->address);
293     memcpy(buf, (char*) &a.s_addr, 4);
294 #endif
295 }
296
297 void sk_addr_free(SockAddr addr)
298 {
299
300 #ifndef NO_IPV6
301     if (addr->ai != NULL)
302         freeaddrinfo(addr->ai);
303 #endif
304     sfree(addr);
305 }
306
307 static Plug sk_tcp_plug(Socket sock, Plug p)
308 {
309     Actual_Socket s = (Actual_Socket) sock;
310     Plug ret = s->plug;
311     if (p)
312         s->plug = p;
313     return ret;
314 }
315
316 static void sk_tcp_flush(Socket s)
317 {
318     /*
319      * We send data to the socket as soon as we can anyway,
320      * so we don't need to do anything here.  :-)
321      */
322 }
323
324 static void sk_tcp_close(Socket s);
325 static int sk_tcp_write(Socket s, const char *data, int len);
326 static int sk_tcp_write_oob(Socket s, const char *data, int len);
327 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
328 static void *sk_tcp_get_private_ptr(Socket s);
329 static void sk_tcp_set_frozen(Socket s, int is_frozen);
330 static const char *sk_tcp_socket_error(Socket s);
331
332 static struct socket_function_table tcp_fn_table = {
333     sk_tcp_plug,
334     sk_tcp_close,
335     sk_tcp_write,
336     sk_tcp_write_oob,
337     sk_tcp_flush,
338     sk_tcp_set_private_ptr,
339     sk_tcp_get_private_ptr,
340     sk_tcp_set_frozen,
341     sk_tcp_socket_error
342 };
343
344 Socket sk_register(OSSocket sockfd, Plug plug)
345 {
346     Actual_Socket ret;
347
348     /*
349      * Create Socket structure.
350      */
351     ret = snew(struct Socket_tag);
352     ret->fn = &tcp_fn_table;
353     ret->error = NULL;
354     ret->plug = plug;
355     bufchain_init(&ret->output_data);
356     ret->writable = 1;                 /* to start with */
357     ret->sending_oob = 0;
358     ret->frozen = 1;
359     ret->frozen_readable = 0;
360     ret->localhost_only = 0;           /* unused, but best init anyway */
361     ret->pending_error = 0;
362     ret->oobpending = FALSE;
363     ret->listener = 0;
364
365     ret->s = sockfd;
366
367     if (ret->s < 0) {
368         ret->error = error_string(errno);
369         return (Socket) ret;
370     }
371
372     ret->oobinline = 0;
373
374     uxsel_tell(ret);
375     add234(sktree, ret);
376
377     return (Socket) ret;
378 }
379
380 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
381               int nodelay, int keepalive, Plug plug)
382 {
383     int s;
384 #ifndef NO_IPV6
385     struct sockaddr_in6 a6;
386 #endif
387     struct sockaddr_in a;
388     struct sockaddr_un au;
389     const struct sockaddr *sa;
390     int err;
391     Actual_Socket ret;
392     short localport;
393     int fl, salen;
394
395     /*
396      * Create Socket structure.
397      */
398     ret = snew(struct Socket_tag);
399     ret->fn = &tcp_fn_table;
400     ret->error = NULL;
401     ret->plug = plug;
402     bufchain_init(&ret->output_data);
403     ret->connected = 0;                /* to start with */
404     ret->writable = 0;                 /* to start with */
405     ret->sending_oob = 0;
406     ret->frozen = 0;
407     ret->frozen_readable = 0;
408     ret->localhost_only = 0;           /* unused, but best init anyway */
409     ret->pending_error = 0;
410     ret->oobpending = FALSE;
411     ret->listener = 0;
412
413     /*
414      * Open socket.
415      */
416     assert(addr->family != AF_UNSPEC);
417     s = socket(addr->family, SOCK_STREAM, 0);
418     ret->s = s;
419
420     if (s < 0) {
421         ret->error = error_string(errno);
422         return (Socket) ret;
423     }
424
425     ret->oobinline = oobinline;
426     if (oobinline) {
427         int b = TRUE;
428         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
429     }
430
431     if (nodelay) {
432         int b = TRUE;
433         setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
434     }
435
436     if (keepalive) {
437         int b = TRUE;
438         setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
439     }
440
441     /*
442      * Bind to local address.
443      */
444     if (privport)
445         localport = 1023;              /* count from 1023 downwards */
446     else
447         localport = 0;                 /* just use port 0 (ie kernel picks) */
448
449     /* BSD IP stacks need sockaddr_in zeroed before filling in */
450     memset(&a,'\0',sizeof(struct sockaddr_in));
451 #ifndef NO_IPV6
452     memset(&a6,'\0',sizeof(struct sockaddr_in6));
453 #endif
454
455     /* We don't try to bind to a local address for UNIX domain sockets.  (Why
456      * do we bother doing the bind when localport == 0 anyway?) */
457     if(addr->family != AF_UNIX) {
458         /* Loop round trying to bind */
459         while (1) {
460             int retcode;
461
462 #ifndef NO_IPV6
463             if (addr->family == AF_INET6) {
464                 /* XXX use getaddrinfo to get a local address? */
465                 a6.sin6_family = AF_INET6;
466                 a6.sin6_addr = in6addr_any;
467                 a6.sin6_port = htons(localport);
468                 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
469             } else
470 #endif
471             {
472                 assert(addr->family == AF_INET);
473                 a.sin_family = AF_INET;
474                 a.sin_addr.s_addr = htonl(INADDR_ANY);
475                 a.sin_port = htons(localport);
476                 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
477             }
478             if (retcode >= 0) {
479                 err = 0;
480                 break;                 /* done */
481             } else {
482                 err = errno;
483                 if (err != EADDRINUSE) /* failed, for a bad reason */
484                   break;
485             }
486             
487             if (localport == 0)
488               break;                   /* we're only looping once */
489             localport--;
490             if (localport == 0)
491               break;                   /* we might have got to the end */
492         }
493         
494         if (err) {
495             ret->error = error_string(err);
496             return (Socket) ret;
497         }
498     }
499
500     /*
501      * Connect to remote address.
502      */
503     switch(addr->family) {
504 #ifndef NO_IPV6
505       case AF_INET:
506         /* XXX would be better to have got getaddrinfo() to fill in the port. */
507         ((struct sockaddr_in *)addr->ai->ai_addr)->sin_port =
508             htons(port);
509         sa = (const struct sockaddr *)addr->ai->ai_addr;
510         salen = addr->ai->ai_addrlen;
511         break;
512       case AF_INET6:
513         ((struct sockaddr_in *)addr->ai->ai_addr)->sin_port =
514             htons(port);
515         sa = (const struct sockaddr *)addr->ai->ai_addr;
516         salen = addr->ai->ai_addrlen;
517         break;
518 #else
519       case AF_INET:
520         a.sin_family = AF_INET;
521         a.sin_addr.s_addr = htonl(addr->address);
522         a.sin_port = htons((short) port);
523         sa = (const struct sockaddr *)&a;
524         salen = sizeof a;
525         break;
526 #endif
527       case AF_UNIX:
528         assert(port == 0);      /* to catch confused people */
529         assert(strlen(addr->hostname) < sizeof au.sun_path);
530         memset(&au, 0, sizeof au);
531         au.sun_family = AF_UNIX;
532         strcpy(au.sun_path, addr->hostname);
533         sa = (const struct sockaddr *)&au;
534         salen = sizeof au;
535         break;
536
537       default:
538         assert(0 && "unknown address family");
539     }
540
541     fl = fcntl(s, F_GETFL);
542     if (fl != -1)
543         fcntl(s, F_SETFL, fl | O_NONBLOCK);
544
545     if ((connect(s, sa, salen)) < 0) {
546         if ( errno != EINPROGRESS ) {
547             ret->error = error_string(errno);
548             return (Socket) ret;
549         }
550     } else {
551         /*
552          * If we _don't_ get EWOULDBLOCK, the connect has completed
553          * and we should set the socket as connected and writable.
554          */
555         ret->connected = 1;
556         ret->writable = 1;
557     }
558
559     uxsel_tell(ret);
560     add234(sktree, ret);
561
562     sk_addr_free(addr);
563
564     return (Socket) ret;
565 }
566
567 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int address_family)
568 {
569     int s;
570 #ifndef NO_IPV6
571     struct addrinfo hints, *ai;
572     char portstr[6];
573 #endif
574     struct sockaddr_in a;
575     int err;
576     Actual_Socket ret;
577     int retcode;
578     int on = 1;
579
580     /*
581      * Create Socket structure.
582      */
583     ret = snew(struct Socket_tag);
584     ret->fn = &tcp_fn_table;
585     ret->error = NULL;
586     ret->plug = plug;
587     bufchain_init(&ret->output_data);
588     ret->writable = 0;                 /* to start with */
589     ret->sending_oob = 0;
590     ret->frozen = 0;
591     ret->frozen_readable = 0;
592     ret->localhost_only = local_host_only;
593     ret->pending_error = 0;
594     ret->oobpending = FALSE;
595     ret->listener = 1;
596
597     /*
598      * Translate address_family from platform-independent constants
599      * into local reality.
600      */
601     address_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
602                       address_family == ADDRTYPE_IPV6 ? AF_INET6 : AF_UNSPEC);
603
604 #ifndef NO_IPV6
605     /* Let's default to IPv6.
606      * If the stack doesn't support IPv6, we will fall back to IPv4. */
607     if (address_family == AF_UNSPEC) address_family = AF_INET6;
608 #else
609     /* No other choice, default to IPv4 */
610     if (address_family == AF_UNSPEC)  address_family = AF_INET;
611 #endif
612
613     /*
614      * Open socket.
615      */
616     s = socket(address_family, SOCK_STREAM, 0);
617
618     /* If the host doesn't support IPv6 try fallback to IPv4. */
619     if (s < 0 && address_family == AF_INET6) {
620         address_family = AF_INET;
621         s = socket(address_family, SOCK_STREAM, 0);
622     }
623     ret->s = s;
624
625     if (s < 0) {
626         ret->error = error_string(errno);
627         return (Socket) ret;
628     }
629
630     ret->oobinline = 0;
631
632     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
633
634     /* BSD IP stacks need sockaddr_in zeroed before filling in */
635     memset(&a,'\0',sizeof(struct sockaddr_in));
636 #ifndef NO_IPV6
637 #if 0
638     memset(&a6,'\0',sizeof(struct sockaddr_in6));
639 #endif
640     hints.ai_flags = AI_NUMERICHOST;
641     hints.ai_family = address_family;
642     hints.ai_socktype = 0;
643     hints.ai_protocol = 0;
644     hints.ai_addrlen = 0;
645     hints.ai_addr = NULL;
646     hints.ai_canonname = NULL;
647     hints.ai_next = NULL;
648     sprintf(portstr, "%d", port);
649     if (srcaddr != NULL && getaddrinfo(srcaddr, portstr, &hints, &ai) == 0)
650         retcode = bind(s, ai->ai_addr, ai->ai_addrlen);
651     else
652 #if 0
653     {
654         /*
655          * FIXME: Need two listening sockets, in principle, one for v4
656          * and one for v6
657          */
658         if (local_host_only)
659             a6.sin6_addr = in6addr_loopback;
660         else
661             a6.sin6_addr = in6addr_any;
662         a6.sin6_port = htons(port);
663     } else
664 #endif
665 #endif
666     {
667         int got_addr = 0;
668         a.sin_family = AF_INET;
669
670         /*
671          * Bind to source address. First try an explicitly
672          * specified one...
673          */
674         if (srcaddr) {
675             a.sin_addr.s_addr = inet_addr(srcaddr);
676             if (a.sin_addr.s_addr != INADDR_NONE) {
677                 /* Override localhost_only with specified listen addr. */
678                 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
679                 got_addr = 1;
680             }
681         }
682
683         /*
684          * ... and failing that, go with one of the standard ones.
685          */
686         if (!got_addr) {
687             if (local_host_only)
688                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
689             else
690                 a.sin_addr.s_addr = htonl(INADDR_ANY);
691         }
692
693         a.sin_port = htons((short)port);
694         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
695     }
696
697     if (retcode >= 0) {
698         err = 0;
699     } else {
700         err = errno;
701     }
702
703     if (err) {
704         ret->error = error_string(err);
705         return (Socket) ret;
706     }
707
708
709     if (listen(s, SOMAXCONN) < 0) {
710         close(s);
711         ret->error = error_string(errno);
712         return (Socket) ret;
713     }
714
715     uxsel_tell(ret);
716     add234(sktree, ret);
717
718     return (Socket) ret;
719 }
720
721 static void sk_tcp_close(Socket sock)
722 {
723     Actual_Socket s = (Actual_Socket) sock;
724
725     uxsel_del(s->s);
726     del234(sktree, s);
727     close(s->s);
728     sfree(s);
729 }
730
731 int sk_getxdmdata(void *sock, unsigned long *ip, int *port)
732 {
733     Actual_Socket s = (Actual_Socket) sock;
734     struct sockaddr_in addr;
735     socklen_t addrlen;
736
737     /*
738      * We must check that this socket really _is_ an Actual_Socket.
739      */
740     if (s->fn != &tcp_fn_table)
741         return 0;                      /* failure */
742
743     addrlen = sizeof(addr);
744     if (getsockname(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
745         return 0;
746     switch(addr.sin_family) {
747       case AF_INET:
748         *ip = ntohl(addr.sin_addr.s_addr);
749         *port = ntohs(addr.sin_port);
750         break;
751       case AF_UNIX:
752         /*
753          * For a Unix socket, we return 0xFFFFFFFF for the IP address and
754          * our current pid for the port. Bizarre, but such is life.
755          */
756         *ip = ntohl(0xFFFFFFFF);
757         *port = getpid();
758         break;
759
760         /* XXX IPV6 */
761
762       default:
763         return 0;
764     }
765
766     return 1;
767 }
768
769 /*
770  * The function which tries to send on a socket once it's deemed
771  * writable.
772  */
773 void try_send(Actual_Socket s)
774 {
775     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
776         int nsent;
777         int err;
778         void *data;
779         int len, urgentflag;
780
781         if (s->sending_oob) {
782             urgentflag = MSG_OOB;
783             len = s->sending_oob;
784             data = &s->oobdata;
785         } else {
786             urgentflag = 0;
787             bufchain_prefix(&s->output_data, &data, &len);
788         }
789         nsent = send(s->s, data, len, urgentflag);
790         noise_ultralight(nsent);
791         if (nsent <= 0) {
792             err = (nsent < 0 ? errno : 0);
793             if (err == EWOULDBLOCK) {
794                 /*
795                  * Perfectly normal: we've sent all we can for the moment.
796                  */
797                 s->writable = FALSE;
798                 return;
799             } else if (nsent == 0 ||
800                        err == ECONNABORTED || err == ECONNRESET) {
801                 /*
802                  * If send() returns CONNABORTED or CONNRESET, we
803                  * unfortunately can't just call plug_closing(),
804                  * because it's quite likely that we're currently
805                  * _in_ a call from the code we'd be calling back
806                  * to, so we'd have to make half the SSH code
807                  * reentrant. Instead we flag a pending error on
808                  * the socket, to be dealt with (by calling
809                  * plug_closing()) at some suitable future moment.
810                  */
811                 s->pending_error = err;
812                 return;
813             } else {
814                 /* We're inside the Unix frontend here, so we know
815                  * that the frontend handle is unnecessary. */
816                 logevent(NULL, error_string(err));
817                 fatalbox("%s", error_string(err));
818             }
819         } else {
820             if (s->sending_oob) {
821                 if (nsent < len) {
822                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
823                     s->sending_oob = len - nsent;
824                 } else {
825                     s->sending_oob = 0;
826                 }
827             } else {
828                 bufchain_consume(&s->output_data, nsent);
829             }
830         }
831     }
832     uxsel_tell(s);
833 }
834
835 static int sk_tcp_write(Socket sock, const char *buf, int len)
836 {
837     Actual_Socket s = (Actual_Socket) sock;
838
839     /*
840      * Add the data to the buffer list on the socket.
841      */
842     bufchain_add(&s->output_data, buf, len);
843
844     /*
845      * Now try sending from the start of the buffer list.
846      */
847     if (s->writable)
848         try_send(s);
849
850     /*
851      * Update the select() status to correctly reflect whether or
852      * not we should be selecting for write.
853      */
854     uxsel_tell(s);
855
856     return bufchain_size(&s->output_data);
857 }
858
859 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
860 {
861     Actual_Socket s = (Actual_Socket) sock;
862
863     /*
864      * Replace the buffer list on the socket with the data.
865      */
866     bufchain_clear(&s->output_data);
867     assert(len <= sizeof(s->oobdata));
868     memcpy(s->oobdata, buf, len);
869     s->sending_oob = len;
870
871     /*
872      * Now try sending from the start of the buffer list.
873      */
874     if (s->writable)
875         try_send(s);
876
877     /*
878      * Update the select() status to correctly reflect whether or
879      * not we should be selecting for write.
880      */
881     uxsel_tell(s);
882
883     return s->sending_oob;
884 }
885
886 static int net_select_result(int fd, int event)
887 {
888     int ret;
889     int err;
890     char buf[20480];                   /* nice big buffer for plenty of speed */
891     Actual_Socket s;
892     u_long atmark;
893
894     /* Find the Socket structure */
895     s = find234(sktree, &fd, cmpforsearch);
896     if (!s)
897         return 1;                      /* boggle */
898
899     noise_ultralight(event);
900
901     switch (event) {
902       case 4:                          /* exceptional */
903         if (!s->oobinline) {
904             /*
905              * On a non-oobinline socket, this indicates that we
906              * can immediately perform an OOB read and get back OOB
907              * data, which we will send to the back end with
908              * type==2 (urgent data).
909              */
910             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
911             noise_ultralight(ret);
912             if (ret <= 0) {
913                 const char *str = (ret == 0 ? "Internal networking trouble" :
914                                    error_string(errno));
915                 /* We're inside the Unix frontend here, so we know
916                  * that the frontend handle is unnecessary. */
917                 logevent(NULL, str);
918                 fatalbox("%s", str);
919             } else {
920                 return plug_receive(s->plug, 2, buf, ret);
921             }
922             break;
923         }
924
925         /*
926          * If we reach here, this is an oobinline socket, which
927          * means we should set s->oobpending and then deal with it
928          * when we get called for the readability event (which
929          * should also occur).
930          */
931         s->oobpending = TRUE;
932         break;
933       case 1:                          /* readable; also acceptance */
934         if (s->listener) {
935             /*
936              * On a listening socket, the readability event means a
937              * connection is ready to be accepted.
938              */
939             struct sockaddr_in isa;
940             int addrlen = sizeof(struct sockaddr_in);
941             int t;  /* socket of connection */
942
943             memset(&isa, 0, sizeof(struct sockaddr_in));
944             err = 0;
945             t = accept(s->s,(struct sockaddr *)&isa,(socklen_t *) &addrlen);
946             if (t < 0) {
947                 break;
948             }
949
950             if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
951                 close(t);              /* someone let nonlocal through?! */
952             } else if (plug_accepting(s->plug, t)) {
953                 close(t);              /* denied or error */
954             }
955             break;
956         }
957
958         /*
959          * If we reach here, this is not a listening socket, so
960          * readability really means readability.
961          */
962
963         /* In the case the socket is still frozen, we don't even bother */
964         if (s->frozen) {
965             s->frozen_readable = 1;
966             break;
967         }
968
969         /*
970          * We have received data on the socket. For an oobinline
971          * socket, this might be data _before_ an urgent pointer,
972          * in which case we send it to the back end with type==1
973          * (data prior to urgent).
974          */
975         if (s->oobinline && s->oobpending) {
976             atmark = 1;
977             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
978                 s->oobpending = FALSE; /* clear this indicator */
979         } else
980             atmark = 1;
981
982         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
983         noise_ultralight(ret);
984         if (ret < 0) {
985             if (errno == EWOULDBLOCK) {
986                 break;
987             }
988         }
989         if (ret < 0) {
990             return plug_closing(s->plug, error_string(errno), errno, 0);
991         } else if (0 == ret) {
992             return plug_closing(s->plug, NULL, 0, 0);
993         } else {
994             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
995         }
996         break;
997       case 2:                          /* writable */
998         if (!s->connected) {
999             /*
1000              * select() reports a socket as _writable_ when an
1001              * asynchronous connection is completed.
1002              */
1003             s->connected = s->writable = 1;
1004             uxsel_tell(s);
1005             break;
1006         } else {
1007             int bufsize_before, bufsize_after;
1008             s->writable = 1;
1009             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1010             try_send(s);
1011             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1012             if (bufsize_after < bufsize_before)
1013                 plug_sent(s->plug, bufsize_after);
1014         }
1015         break;
1016     }
1017
1018     return 1;
1019 }
1020
1021 /*
1022  * Deal with socket errors detected in try_send().
1023  */
1024 void net_pending_errors(void)
1025 {
1026     int i;
1027     Actual_Socket s;
1028
1029     /*
1030      * This might be a fiddly business, because it's just possible
1031      * that handling a pending error on one socket might cause
1032      * others to be closed. (I can't think of any reason this might
1033      * happen in current SSH implementation, but to maintain
1034      * generality of this network layer I'll assume the worst.)
1035      * 
1036      * So what we'll do is search the socket list for _one_ socket
1037      * with a pending error, and then handle it, and then search
1038      * the list again _from the beginning_. Repeat until we make a
1039      * pass with no socket errors present. That way we are
1040      * protected against the socket list changing under our feet.
1041      */
1042
1043     do {
1044         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1045             if (s->pending_error) {
1046                 /*
1047                  * An error has occurred on this socket. Pass it to the
1048                  * plug.
1049                  */
1050                 plug_closing(s->plug, error_string(s->pending_error),
1051                              s->pending_error, 0);
1052                 break;
1053             }
1054         }
1055     } while (s);
1056 }
1057
1058 /*
1059  * Each socket abstraction contains a `void *' private field in
1060  * which the client can keep state.
1061  */
1062 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1063 {
1064     Actual_Socket s = (Actual_Socket) sock;
1065     s->private_ptr = ptr;
1066 }
1067
1068 static void *sk_tcp_get_private_ptr(Socket sock)
1069 {
1070     Actual_Socket s = (Actual_Socket) sock;
1071     return s->private_ptr;
1072 }
1073
1074 /*
1075  * Special error values are returned from sk_namelookup and sk_new
1076  * if there's a problem. These functions extract an error message,
1077  * or return NULL if there's no problem.
1078  */
1079 const char *sk_addr_error(SockAddr addr)
1080 {
1081     return addr->error;
1082 }
1083 static const char *sk_tcp_socket_error(Socket sock)
1084 {
1085     Actual_Socket s = (Actual_Socket) sock;
1086     return s->error;
1087 }
1088
1089 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1090 {
1091     Actual_Socket s = (Actual_Socket) sock;
1092     if (s->frozen == is_frozen)
1093         return;
1094     s->frozen = is_frozen;
1095     if (!is_frozen && s->frozen_readable) {
1096         char c;
1097         recv(s->s, &c, 1, MSG_PEEK);
1098     }
1099     s->frozen_readable = 0;
1100     uxsel_tell(s);
1101 }
1102
1103 static void uxsel_tell(Actual_Socket s)
1104 {
1105     int rwx = 0;
1106     if (!s->connected)
1107         rwx |= 2;                      /* write == connect */
1108     if (s->connected && !s->frozen)
1109         rwx |= 1 | 4;                  /* read, except */
1110     if (bufchain_size(&s->output_data))
1111         rwx |= 2;                      /* write */
1112     if (s->listener)
1113         rwx |= 1;                      /* read == accept */
1114     uxsel_set(s->s, rwx, net_select_result);
1115 }
1116
1117 int net_service_lookup(char *service)
1118 {
1119     struct servent *se;
1120     se = getservbyname(service, NULL);
1121     if (se != NULL)
1122         return ntohs(se->s_port);
1123     else
1124         return 0;
1125 }
1126
1127 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1128 {
1129     SockAddr ret = snew(struct SockAddr_tag);
1130     int n;
1131
1132     memset(ret, 0, sizeof *ret);
1133     ret->family = AF_UNIX;
1134     n = snprintf(ret->hostname, sizeof ret->hostname,
1135                  "%s%d", X11_UNIX_PATH, displaynum);
1136     if(n < 0)
1137         ret->error = "snprintf failed";
1138     else if(n >= sizeof ret->hostname)
1139         ret->error = "X11 UNIX name too long";
1140     else
1141         *canonicalname = dupstr(ret->hostname);
1142     return ret;
1143 }