]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
RJK's patch to enable PuTTY's X forwarding to connect to local X
[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 #ifdef 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)
129 {
130     SockAddr ret = snew(struct SockAddr_tag);
131 #ifdef 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 #ifdef IPV6
147     hints.ai_flags = AI_CANONNAME;
148     hints.ai_family = AF_UNSPEC;
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 #ifdef 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 #ifdef 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 #ifdef 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 #ifdef 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 #ifdef 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, Plug plug)
382 {
383     int s;
384 #ifdef 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     /*
437      * Bind to local address.
438      */
439     if (privport)
440         localport = 1023;              /* count from 1023 downwards */
441     else
442         localport = 0;                 /* just use port 0 (ie kernel picks) */
443
444     /* BSD IP stacks need sockaddr_in zeroed before filling in */
445     memset(&a,'\0',sizeof(struct sockaddr_in));
446 #ifdef IPV6
447     memset(&a6,'\0',sizeof(struct sockaddr_in6));
448 #endif
449
450     /* We don't try to bind to a local address for UNIX domain sockets.  (Why
451      * do we bother doing the bind when localport == 0 anyway?) */
452     if(addr->family != AF_UNIX) {
453         /* Loop round trying to bind */
454         while (1) {
455             int retcode;
456
457 #ifdef IPV6
458             if (addr->family == AF_INET6) {
459                 /* XXX use getaddrinfo to get a local address? */
460                 a6.sin6_family = AF_INET6;
461                 a6.sin6_addr = in6addr_any;
462                 a6.sin6_port = htons(localport);
463                 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
464             } else
465 #endif
466             {
467                 assert(addr->family == AF_INET);
468                 a.sin_family = AF_INET;
469                 a.sin_addr.s_addr = htonl(INADDR_ANY);
470                 a.sin_port = htons(localport);
471                 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
472             }
473             if (retcode >= 0) {
474                 err = 0;
475                 break;                 /* done */
476             } else {
477                 err = errno;
478                 if (err != EADDRINUSE) /* failed, for a bad reason */
479                   break;
480             }
481             
482             if (localport == 0)
483               break;                   /* we're only looping once */
484             localport--;
485             if (localport == 0)
486               break;                   /* we might have got to the end */
487         }
488         
489         if (err) {
490             ret->error = error_string(err);
491             return (Socket) ret;
492         }
493     }
494
495     /*
496      * Connect to remote address.
497      */
498     switch(addr->family) {
499 #ifdef IPV6
500       case AF_INET:
501         /* XXX would be better to have got getaddrinfo() to fill in the port. */
502         ((struct sockaddr_in *)addr->ai->ai_addr)->sin_port =
503             htons(port);
504         sa = (const struct sockaddr *)addr->ai->ai_addr;
505         salen = addr->ai->ai_addrlen;
506         break;
507       case AF_INET6:
508         ((struct sockaddr_in *)addr->ai->ai_addr)->sin_port =
509             htons(port);
510         sa = (const struct sockaddr *)addr->ai->ai_addr;
511         salen = addr->ai->ai_addrlen;
512         break;
513 #else
514       case AF_INET:
515         a.sin_family = AF_INET;
516         a.sin_addr.s_addr = htonl(addr->address);
517         a.sin_port = htons((short) port);
518         sa = (const struct sockaddr *)&a;
519         salen = sizeof a;
520         break;
521 #endif
522       case AF_UNIX:
523         assert(port == 0);      /* to catch confused people */
524         assert(strlen(addr->hostname) < sizeof au.sun_path);
525         memset(&au, 0, sizeof au);
526         au.sun_family = AF_UNIX;
527         strcpy(au.sun_path, addr->hostname);
528         sa = (const struct sockaddr *)&au;
529         salen = sizeof au;
530         break;
531
532       default:
533         assert(0 && "unknown address family");
534     }
535
536     fl = fcntl(s, F_GETFL);
537     if (fl != -1)
538         fcntl(s, F_SETFL, fl | O_NONBLOCK);
539
540     if ((connect(s, sa, salen)) < 0) {
541         if ( errno != EINPROGRESS ) {
542             ret->error = error_string(errno);
543             return (Socket) ret;
544         }
545     } else {
546         /*
547          * If we _don't_ get EWOULDBLOCK, the connect has completed
548          * and we should set the socket as connected and writable.
549          */
550         ret->connected = 1;
551         ret->writable = 1;
552     }
553
554     uxsel_tell(ret);
555     add234(sktree, ret);
556
557     sk_addr_free(addr);
558
559     return (Socket) ret;
560 }
561
562 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
563 {
564     int s;
565 #ifdef IPV6
566 #if 0
567     struct sockaddr_in6 a6;
568 #endif
569     struct addrinfo hints, *ai;
570     char portstr[6];
571 #endif
572     struct sockaddr_in a;
573     int err;
574     Actual_Socket ret;
575     int retcode;
576     int on = 1;
577
578     /*
579      * Create Socket structure.
580      */
581     ret = snew(struct Socket_tag);
582     ret->fn = &tcp_fn_table;
583     ret->error = NULL;
584     ret->plug = plug;
585     bufchain_init(&ret->output_data);
586     ret->writable = 0;                 /* to start with */
587     ret->sending_oob = 0;
588     ret->frozen = 0;
589     ret->frozen_readable = 0;
590     ret->localhost_only = local_host_only;
591     ret->pending_error = 0;
592     ret->oobpending = FALSE;
593     ret->listener = 1;
594
595     /*
596      * Open socket.
597      */
598     s = socket(AF_INET, SOCK_STREAM, 0);
599     ret->s = s;
600
601     if (s < 0) {
602         ret->error = error_string(errno);
603         return (Socket) ret;
604     }
605
606     ret->oobinline = 0;
607
608     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
609
610     /* BSD IP stacks need sockaddr_in zeroed before filling in */
611     memset(&a,'\0',sizeof(struct sockaddr_in));
612 #ifdef IPV6
613 #if 0
614     memset(&a6,'\0',sizeof(struct sockaddr_in6));
615 #endif
616     hints.ai_flags = AI_NUMERICHOST;
617     hints.ai_family = AF_UNSPEC;
618     hints.ai_socktype = 0;
619     hints.ai_protocol = 0;
620     hints.ai_addrlen = 0;
621     hints.ai_addr = NULL;
622     hints.ai_canonname = NULL;
623     hints.ai_next = NULL;
624     sprintf(portstr, "%d", port);
625     if (srcaddr != NULL && getaddrinfo(srcaddr, portstr, &hints, &ai) == 0)
626         retcode = bind(s, ai->ai_addr, ai->ai_addrlen);
627     else
628 #if 0
629     {
630         /*
631          * FIXME: Need two listening sockets, in principle, one for v4
632          * and one for v6
633          */
634         if (local_host_only)
635             a6.sin6_addr = in6addr_loopback;
636         else
637             a6.sin6_addr = in6addr_any;
638         a6.sin6_port = htons(port);
639     } else
640 #endif
641 #endif
642     {
643         int got_addr = 0;
644         a.sin_family = AF_INET;
645
646         /*
647          * Bind to source address. First try an explicitly
648          * specified one...
649          */
650         if (srcaddr) {
651             a.sin_addr.s_addr = inet_addr(srcaddr);
652             if (a.sin_addr.s_addr != INADDR_NONE) {
653                 /* Override localhost_only with specified listen addr. */
654                 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
655                 got_addr = 1;
656             }
657         }
658
659         /*
660          * ... and failing that, go with one of the standard ones.
661          */
662         if (!got_addr) {
663             if (local_host_only)
664                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
665             else
666                 a.sin_addr.s_addr = htonl(INADDR_ANY);
667         }
668
669         a.sin_port = htons((short)port);
670         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
671     }
672
673     if (retcode >= 0) {
674         err = 0;
675     } else {
676         err = errno;
677     }
678
679     if (err) {
680         ret->error = error_string(err);
681         return (Socket) ret;
682     }
683
684
685     if (listen(s, SOMAXCONN) < 0) {
686         close(s);
687         ret->error = error_string(errno);
688         return (Socket) ret;
689     }
690
691     uxsel_tell(ret);
692     add234(sktree, ret);
693
694     return (Socket) ret;
695 }
696
697 static void sk_tcp_close(Socket sock)
698 {
699     Actual_Socket s = (Actual_Socket) sock;
700
701     uxsel_del(s->s);
702     del234(sktree, s);
703     close(s->s);
704     sfree(s);
705 }
706
707 int sk_getxdmdata(void *sock, unsigned long *ip, int *port)
708 {
709     Actual_Socket s = (Actual_Socket) sock;
710     struct sockaddr_in addr;
711     socklen_t addrlen;
712
713     /*
714      * We must check that this socket really _is_ an Actual_Socket.
715      */
716     if (s->fn != &tcp_fn_table)
717         return 0;                      /* failure */
718
719     addrlen = sizeof(addr);
720     if (getsockname(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
721         return 0;
722     switch(addr.sin_family) {
723       case AF_INET:
724         *ip = ntohl(addr.sin_addr.s_addr);
725         *port = ntohs(addr.sin_port);
726         break;
727       case AF_UNIX:
728         /*
729          * For a Unix socket, we return 0xFFFFFFFF for the IP address and
730          * our current pid for the port. Bizarre, but such is life.
731          */
732         *ip = ntohl(0xFFFFFFFF);
733         *port = getpid();
734         break;
735
736         /* XXX IPV6 */
737
738       default:
739         return 0;
740     }
741
742     return 1;
743 }
744
745 /*
746  * The function which tries to send on a socket once it's deemed
747  * writable.
748  */
749 void try_send(Actual_Socket s)
750 {
751     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
752         int nsent;
753         int err;
754         void *data;
755         int len, urgentflag;
756
757         if (s->sending_oob) {
758             urgentflag = MSG_OOB;
759             len = s->sending_oob;
760             data = &s->oobdata;
761         } else {
762             urgentflag = 0;
763             bufchain_prefix(&s->output_data, &data, &len);
764         }
765         nsent = send(s->s, data, len, urgentflag);
766         noise_ultralight(nsent);
767         if (nsent <= 0) {
768             err = (nsent < 0 ? errno : 0);
769             if (err == EWOULDBLOCK) {
770                 /*
771                  * Perfectly normal: we've sent all we can for the moment.
772                  */
773                 s->writable = FALSE;
774                 return;
775             } else if (nsent == 0 ||
776                        err == ECONNABORTED || err == ECONNRESET) {
777                 /*
778                  * If send() returns CONNABORTED or CONNRESET, we
779                  * unfortunately can't just call plug_closing(),
780                  * because it's quite likely that we're currently
781                  * _in_ a call from the code we'd be calling back
782                  * to, so we'd have to make half the SSH code
783                  * reentrant. Instead we flag a pending error on
784                  * the socket, to be dealt with (by calling
785                  * plug_closing()) at some suitable future moment.
786                  */
787                 s->pending_error = err;
788                 return;
789             } else {
790                 /* We're inside the Unix frontend here, so we know
791                  * that the frontend handle is unnecessary. */
792                 logevent(NULL, error_string(err));
793                 fatalbox("%s", error_string(err));
794             }
795         } else {
796             if (s->sending_oob) {
797                 if (nsent < len) {
798                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
799                     s->sending_oob = len - nsent;
800                 } else {
801                     s->sending_oob = 0;
802                 }
803             } else {
804                 bufchain_consume(&s->output_data, nsent);
805             }
806         }
807     }
808     uxsel_tell(s);
809 }
810
811 static int sk_tcp_write(Socket sock, const char *buf, int len)
812 {
813     Actual_Socket s = (Actual_Socket) sock;
814
815     /*
816      * Add the data to the buffer list on the socket.
817      */
818     bufchain_add(&s->output_data, buf, len);
819
820     /*
821      * Now try sending from the start of the buffer list.
822      */
823     if (s->writable)
824         try_send(s);
825
826     /*
827      * Update the select() status to correctly reflect whether or
828      * not we should be selecting for write.
829      */
830     uxsel_tell(s);
831
832     return bufchain_size(&s->output_data);
833 }
834
835 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
836 {
837     Actual_Socket s = (Actual_Socket) sock;
838
839     /*
840      * Replace the buffer list on the socket with the data.
841      */
842     bufchain_clear(&s->output_data);
843     assert(len <= sizeof(s->oobdata));
844     memcpy(s->oobdata, buf, len);
845     s->sending_oob = len;
846
847     /*
848      * Now try sending from the start of the buffer list.
849      */
850     if (s->writable)
851         try_send(s);
852
853     /*
854      * Update the select() status to correctly reflect whether or
855      * not we should be selecting for write.
856      */
857     uxsel_tell(s);
858
859     return s->sending_oob;
860 }
861
862 static int net_select_result(int fd, int event)
863 {
864     int ret;
865     int err;
866     char buf[20480];                   /* nice big buffer for plenty of speed */
867     Actual_Socket s;
868     u_long atmark;
869
870     /* Find the Socket structure */
871     s = find234(sktree, &fd, cmpforsearch);
872     if (!s)
873         return 1;                      /* boggle */
874
875     noise_ultralight(event);
876
877     switch (event) {
878       case 4:                          /* exceptional */
879         if (!s->oobinline) {
880             /*
881              * On a non-oobinline socket, this indicates that we
882              * can immediately perform an OOB read and get back OOB
883              * data, which we will send to the back end with
884              * type==2 (urgent data).
885              */
886             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
887             noise_ultralight(ret);
888             if (ret <= 0) {
889                 const char *str = (ret == 0 ? "Internal networking trouble" :
890                                    error_string(errno));
891                 /* We're inside the Unix frontend here, so we know
892                  * that the frontend handle is unnecessary. */
893                 logevent(NULL, str);
894                 fatalbox("%s", str);
895             } else {
896                 return plug_receive(s->plug, 2, buf, ret);
897             }
898             break;
899         }
900
901         /*
902          * If we reach here, this is an oobinline socket, which
903          * means we should set s->oobpending and then deal with it
904          * when we get called for the readability event (which
905          * should also occur).
906          */
907         s->oobpending = TRUE;
908         break;
909       case 1:                          /* readable; also acceptance */
910         if (s->listener) {
911             /*
912              * On a listening socket, the readability event means a
913              * connection is ready to be accepted.
914              */
915             struct sockaddr_in isa;
916             int addrlen = sizeof(struct sockaddr_in);
917             int t;  /* socket of connection */
918
919             memset(&isa, 0, sizeof(struct sockaddr_in));
920             err = 0;
921             t = accept(s->s,(struct sockaddr *)&isa,(socklen_t *) &addrlen);
922             if (t < 0) {
923                 break;
924             }
925
926             if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
927                 close(t);              /* someone let nonlocal through?! */
928             } else if (plug_accepting(s->plug, t)) {
929                 close(t);              /* denied or error */
930             }
931             break;
932         }
933
934         /*
935          * If we reach here, this is not a listening socket, so
936          * readability really means readability.
937          */
938
939         /* In the case the socket is still frozen, we don't even bother */
940         if (s->frozen) {
941             s->frozen_readable = 1;
942             break;
943         }
944
945         /*
946          * We have received data on the socket. For an oobinline
947          * socket, this might be data _before_ an urgent pointer,
948          * in which case we send it to the back end with type==1
949          * (data prior to urgent).
950          */
951         if (s->oobinline && s->oobpending) {
952             atmark = 1;
953             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
954                 s->oobpending = FALSE; /* clear this indicator */
955         } else
956             atmark = 1;
957
958         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
959         noise_ultralight(ret);
960         if (ret < 0) {
961             if (errno == EWOULDBLOCK) {
962                 break;
963             }
964         }
965         if (ret < 0) {
966             return plug_closing(s->plug, error_string(errno), errno, 0);
967         } else if (0 == ret) {
968             return plug_closing(s->plug, NULL, 0, 0);
969         } else {
970             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
971         }
972         break;
973       case 2:                          /* writable */
974         if (!s->connected) {
975             /*
976              * select() reports a socket as _writable_ when an
977              * asynchronous connection is completed.
978              */
979             s->connected = s->writable = 1;
980             uxsel_tell(s);
981             break;
982         } else {
983             int bufsize_before, bufsize_after;
984             s->writable = 1;
985             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
986             try_send(s);
987             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
988             if (bufsize_after < bufsize_before)
989                 plug_sent(s->plug, bufsize_after);
990         }
991         break;
992     }
993
994     return 1;
995 }
996
997 /*
998  * Deal with socket errors detected in try_send().
999  */
1000 void net_pending_errors(void)
1001 {
1002     int i;
1003     Actual_Socket s;
1004
1005     /*
1006      * This might be a fiddly business, because it's just possible
1007      * that handling a pending error on one socket might cause
1008      * others to be closed. (I can't think of any reason this might
1009      * happen in current SSH implementation, but to maintain
1010      * generality of this network layer I'll assume the worst.)
1011      * 
1012      * So what we'll do is search the socket list for _one_ socket
1013      * with a pending error, and then handle it, and then search
1014      * the list again _from the beginning_. Repeat until we make a
1015      * pass with no socket errors present. That way we are
1016      * protected against the socket list changing under our feet.
1017      */
1018
1019     do {
1020         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1021             if (s->pending_error) {
1022                 /*
1023                  * An error has occurred on this socket. Pass it to the
1024                  * plug.
1025                  */
1026                 plug_closing(s->plug, error_string(s->pending_error),
1027                              s->pending_error, 0);
1028                 break;
1029             }
1030         }
1031     } while (s);
1032 }
1033
1034 /*
1035  * Each socket abstraction contains a `void *' private field in
1036  * which the client can keep state.
1037  */
1038 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1039 {
1040     Actual_Socket s = (Actual_Socket) sock;
1041     s->private_ptr = ptr;
1042 }
1043
1044 static void *sk_tcp_get_private_ptr(Socket sock)
1045 {
1046     Actual_Socket s = (Actual_Socket) sock;
1047     return s->private_ptr;
1048 }
1049
1050 /*
1051  * Special error values are returned from sk_namelookup and sk_new
1052  * if there's a problem. These functions extract an error message,
1053  * or return NULL if there's no problem.
1054  */
1055 const char *sk_addr_error(SockAddr addr)
1056 {
1057     return addr->error;
1058 }
1059 static const char *sk_tcp_socket_error(Socket sock)
1060 {
1061     Actual_Socket s = (Actual_Socket) sock;
1062     return s->error;
1063 }
1064
1065 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1066 {
1067     Actual_Socket s = (Actual_Socket) sock;
1068     if (s->frozen == is_frozen)
1069         return;
1070     s->frozen = is_frozen;
1071     if (!is_frozen && s->frozen_readable) {
1072         char c;
1073         recv(s->s, &c, 1, MSG_PEEK);
1074     }
1075     s->frozen_readable = 0;
1076     uxsel_tell(s);
1077 }
1078
1079 static void uxsel_tell(Actual_Socket s)
1080 {
1081     int rwx = 0;
1082     if (!s->connected)
1083         rwx |= 2;                      /* write == connect */
1084     if (s->connected && !s->frozen)
1085         rwx |= 1 | 4;                  /* read, except */
1086     if (bufchain_size(&s->output_data))
1087         rwx |= 2;                      /* write */
1088     if (s->listener)
1089         rwx |= 1;                      /* read == accept */
1090     uxsel_set(s->s, rwx, net_select_result);
1091 }
1092
1093 int net_service_lookup(char *service)
1094 {
1095     struct servent *se;
1096     se = getservbyname(service, NULL);
1097     if (se != NULL)
1098         return ntohs(se->s_port);
1099     else
1100         return 0;
1101 }
1102
1103 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1104 {
1105     SockAddr ret = snew(struct SockAddr_tag);
1106     int n;
1107
1108     memset(ret, 0, sizeof *ret);
1109     ret->family = AF_UNIX;
1110     n = snprintf(ret->hostname, sizeof ret->hostname,
1111                  "%s%d", X11_UNIX_PATH, displaynum);
1112     if(n < 0)
1113         ret->error = "snprintf failed";
1114     else if(n >= sizeof ret->hostname)
1115         ret->error = "X11 UNIX name too long";
1116     else
1117         *canonicalname = dupstr(ret->hostname);
1118     return ret;
1119 }