]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
Move out of the SockAddr structure the mutable fields "ai" and
[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 /* Solaris needs <sys/sockio.h> for SIOCATMARK. */
26 #ifndef SIOCATMARK
27 #include <sys/sockio.h>
28 #endif
29
30 #ifndef X11_UNIX_PATH
31 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
32 #endif
33
34 /*
35  * We used to typedef struct Socket_tag *Socket.
36  *
37  * Since we have made the networking abstraction slightly more
38  * abstract, Socket no longer means a tcp socket (it could mean
39  * an ssl socket).  So now we must use Actual_Socket when we know
40  * we are talking about a tcp socket.
41  */
42 typedef struct Socket_tag *Actual_Socket;
43
44 /*
45  * Mutable state that goes with a SockAddr: stores information
46  * about where in the list of candidate IP(v*) addresses we've
47  * currently got to.
48  */
49 typedef struct SockAddrStep_tag SockAddrStep;
50 struct SockAddrStep_tag {
51 #ifndef NO_IPV6
52     struct addrinfo *ai;               /* steps along addr->ais */
53 #endif
54     int curraddr;
55 };
56
57 struct Socket_tag {
58     struct socket_function_table *fn;
59     /* the above variable absolutely *must* be the first in this structure */
60     const char *error;
61     int s;
62     Plug plug;
63     void *private_ptr;
64     bufchain output_data;
65     int connected;                     /* irrelevant for listening sockets */
66     int writable;
67     int frozen; /* this causes readability notifications to be ignored */
68     int frozen_readable; /* this means we missed at least one readability
69                           * notification while we were frozen */
70     int localhost_only;                /* for listening sockets */
71     char oobdata[1];
72     int sending_oob;
73     int oobpending;                    /* is there OOB data available to read? */
74     int oobinline;
75     int pending_error;                 /* in case send() returns error */
76     int listener;
77     int nodelay, keepalive;            /* for connect()-type sockets */
78     int privport, port;                /* and again */
79     SockAddr addr;
80     SockAddrStep step;
81     /*
82      * We sometimes need pairs of Socket structures to be linked:
83      * if we are listening on the same IPv6 and v4 port, for
84      * example. So here we define `parent' and `child' pointers to
85      * track this link.
86      */
87     Actual_Socket parent, child;
88 };
89
90 struct SockAddr_tag {
91     const char *error;
92     enum { UNRESOLVED, UNIX, IP } superfamily;
93 #ifndef NO_IPV6
94     struct addrinfo *ais;              /* Addresses IPv6 style. */
95 #else
96     unsigned long *addresses;          /* Addresses IPv4 style. */
97     int naddresses;
98 #endif
99     char hostname[512];                /* Store an unresolved host name. */
100 };
101
102 /*
103  * Which address family this address belongs to. AF_INET for IPv4;
104  * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
105  * not been done and a simple host name is held in this SockAddr
106  * structure.
107  */
108 #ifndef NO_IPV6
109 #define SOCKADDR_FAMILY(addr, step) \
110     ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
111      (addr)->superfamily == UNIX ? AF_UNIX : \
112      (step).ai ? (step).ai->ai_family : AF_INET)
113 #else
114 #define SOCKADDR_FAMILY(addr, step) \
115     ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
116      (addr)->superfamily == UNIX ? AF_UNIX : AF_INET)
117 #endif
118
119 /*
120  * Start a SockAddrStep structure to step through multiple
121  * addresses.
122  */
123 #ifndef NO_IPV6
124 #define START_STEP(addr, step) \
125     ((step).ai = (addr)->ais, (step).curraddr = 0)
126 #else
127 #define START_STEP(addr, step) \
128     ((step).curraddr = 0)
129 #endif
130
131 static tree234 *sktree;
132
133 static void uxsel_tell(Actual_Socket s);
134
135 static int cmpfortree(void *av, void *bv)
136 {
137     Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
138     int as = a->s, bs = b->s;
139     if (as < bs)
140         return -1;
141     if (as > bs)
142         return +1;
143     if (a < b)
144        return -1;
145     if (a > b)
146        return +1;
147     return 0;
148 }
149
150 static int cmpforsearch(void *av, void *bv)
151 {
152     Actual_Socket b = (Actual_Socket) bv;
153     int as = *(int *)av, bs = b->s;
154     if (as < bs)
155         return -1;
156     if (as > bs)
157         return +1;
158     return 0;
159 }
160
161 void sk_init(void)
162 {
163     sktree = newtree234(cmpfortree);
164 }
165
166 void sk_cleanup(void)
167 {
168     Actual_Socket s;
169     int i;
170
171     if (sktree) {
172         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
173             close(s->s);
174         }
175     }
176 }
177
178 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
179 {
180     SockAddr ret = snew(struct SockAddr_tag);
181 #ifndef NO_IPV6
182     struct addrinfo hints;
183     int err;
184 #else
185     unsigned long a;
186     struct hostent *h = NULL;
187     int n;
188 #endif
189     char realhost[8192];
190
191     /* Clear the structure and default to IPv4. */
192     memset(ret, 0, sizeof(struct SockAddr_tag));
193     ret->superfamily = UNRESOLVED;
194     *realhost = '\0';
195     ret->error = NULL;
196
197 #ifndef NO_IPV6
198     hints.ai_flags = AI_CANONNAME;
199     hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
200                        address_family == ADDRTYPE_IPV6 ? AF_INET6 :
201                        AF_UNSPEC);
202     hints.ai_socktype = SOCK_STREAM;
203     hints.ai_protocol = 0;
204     hints.ai_addrlen = 0;
205     hints.ai_addr = NULL;
206     hints.ai_canonname = NULL;
207     hints.ai_next = NULL;
208     err = getaddrinfo(host, NULL, &hints, &ret->ais);
209     if (err != 0) {
210         ret->error = gai_strerror(err);
211         return ret;
212     }
213     ret->superfamily = IP;
214     *realhost = '\0';
215     if (ret->ais->ai_canonname != NULL)
216         strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
217     else
218         strncat(realhost, host, sizeof(realhost) - 1);
219 #else
220     if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
221         /*
222          * Otherwise use the IPv4-only gethostbyname... (NOTE:
223          * we don't use gethostbyname as a fallback!)
224          */
225         if (ret->superfamily == UNRESOLVED) {
226             /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
227             if ( (h = gethostbyname(host)) )
228                 ret->superfamily = IP;
229         }
230         if (ret->superfamily == UNRESOLVED) {
231             ret->error = (h_errno == HOST_NOT_FOUND ||
232                           h_errno == NO_DATA ||
233                           h_errno == NO_ADDRESS ? "Host does not exist" :
234                           h_errno == TRY_AGAIN ?
235                           "Temporary name service failure" :
236                           "gethostbyname: unknown error");
237             return ret;
238         }
239         /* This way we are always sure the h->h_name is valid :) */
240         strncpy(realhost, h->h_name, sizeof(realhost));
241         for (n = 0; h->h_addr_list[n]; n++);
242         ret->addresses = snewn(n, unsigned long);
243         ret->naddresses = n;
244         for (n = 0; n < ret->naddresses; n++) {
245             memcpy(&a, h->h_addr_list[n], sizeof(a));
246             ret->addresses[n] = ntohl(a);
247         }
248     } else {
249         /*
250          * This must be a numeric IPv4 address because it caused a
251          * success return from inet_addr.
252          */
253         ret->superfamily = IP;
254         strncpy(realhost, host, sizeof(realhost));
255         ret->addresses = snew(unsigned long);
256         ret->naddresses = 1;
257         ret->addresses[0] = ntohl(a);
258     }
259 #endif
260     realhost[lenof(realhost)-1] = '\0';
261     *canonicalname = snewn(1+strlen(realhost), char);
262     strcpy(*canonicalname, realhost);
263     return ret;
264 }
265
266 SockAddr sk_nonamelookup(const char *host)
267 {
268     SockAddr ret = snew(struct SockAddr_tag);
269     ret->error = NULL;
270     ret->superfamily = UNRESOLVED;
271     strncpy(ret->hostname, host, lenof(ret->hostname));
272     ret->hostname[lenof(ret->hostname)-1] = '\0';
273 #ifndef NO_IPV6
274     ret->ais = NULL;
275 #else
276     ret->addresses = NULL;
277 #endif
278     return ret;
279 }
280
281 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
282 {
283 #ifndef NO_IPV6
284     if (step->ai && step->ai->ai_next) {
285         step->ai = step->ai->ai_next;
286         return TRUE;
287     } else
288         return FALSE;
289 #else
290     if (step->curraddr+1 < addr->naddresses) {
291         step->curraddr++;
292         return TRUE;
293     } else {
294         return FALSE;
295     }
296 #endif    
297 }
298
299 void sk_getaddr(SockAddr addr, char *buf, int buflen)
300 {
301
302     if (addr->superfamily == UNRESOLVED) {
303         strncpy(buf, addr->hostname, buflen);
304         buf[buflen-1] = '\0';
305     } else {
306 #ifndef NO_IPV6
307         if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
308                         NULL, 0, NI_NUMERICHOST) != 0) {
309             buf[0] = '\0';
310             strncat(buf, "<unknown>", buflen - 1);
311         }
312 #else
313         struct in_addr a;
314         SockAddrStep step;
315         START_STEP(addr, step);
316         assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
317         a.s_addr = htonl(addr->addresses[0]);
318         strncpy(buf, inet_ntoa(a), buflen);
319         buf[buflen-1] = '\0';
320 #endif
321     }
322 }
323
324 int sk_hostname_is_local(char *name)
325 {
326     return !strcmp(name, "localhost");
327 }
328
329 #define ipv4_is_loopback(addr) \
330     (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
331
332 static int sockaddr_is_loopback(struct sockaddr *sa)
333 {
334     struct sockaddr_in *sin;
335 #ifndef NO_IPV6
336     struct sockaddr_in6 *sin6;
337 #endif
338
339     switch (sa->sa_family) {
340       case AF_INET:
341         sin = (struct sockaddr_in *)sa;
342         return ipv4_is_loopback(sin->sin_addr);
343 #ifndef NO_IPV6
344       case AF_INET6:
345         sin6 = (struct sockaddr_in6 *)sa;
346         return IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr);
347 #endif
348       case AF_UNIX:
349         return TRUE;
350       default:
351         return FALSE;
352     }
353 }
354
355 int sk_address_is_local(SockAddr addr)
356 {
357
358     if (addr->superfamily == UNRESOLVED)
359         return 0;                      /* we don't know; assume not */
360     else {
361 #ifndef NO_IPV6
362         return sockaddr_is_loopback(addr->ais->ai_addr);
363 #else
364         struct in_addr a;
365         SockAddrStep step;
366         START_STEP(addr, step);
367         assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
368         a.s_addr = htonl(addr->addresses[0]);
369         return ipv4_is_loopback(a);
370 #endif
371     }
372 }
373
374 int sk_addrtype(SockAddr addr)
375 {
376     SockAddrStep step;
377     int family;
378     START_STEP(addr, step);
379     family = SOCKADDR_FAMILY(addr, step);
380
381     return (family == AF_INET ? ADDRTYPE_IPV4 :
382 #ifndef NO_IPV6
383             family == AF_INET6 ? ADDRTYPE_IPV6 :
384 #endif
385             ADDRTYPE_NAME);
386 }
387
388 void sk_addrcopy(SockAddr addr, char *buf)
389 {
390     SockAddrStep step;
391     int family;
392     START_STEP(addr, step);
393     family = SOCKADDR_FAMILY(addr, step);
394
395 #ifndef NO_IPV6
396     if (family == AF_INET)
397         memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
398                sizeof(struct in_addr));
399     else if (family == AF_INET6)
400         memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
401                sizeof(struct in6_addr));
402     else
403         assert(FALSE);
404 #else
405     struct in_addr a;
406
407     assert(family == AF_INET);
408     a.s_addr = htonl(addr->addresses[step.curraddr]);
409     memcpy(buf, (char*) &a.s_addr, 4);
410 #endif
411 }
412
413 void sk_addr_free(SockAddr addr)
414 {
415
416 #ifndef NO_IPV6
417     if (addr->ais != NULL)
418         freeaddrinfo(addr->ais);
419 #else
420     sfree(addr->addresses);
421 #endif
422     sfree(addr);
423 }
424
425 static Plug sk_tcp_plug(Socket sock, Plug p)
426 {
427     Actual_Socket s = (Actual_Socket) sock;
428     Plug ret = s->plug;
429     if (p)
430         s->plug = p;
431     return ret;
432 }
433
434 static void sk_tcp_flush(Socket s)
435 {
436     /*
437      * We send data to the socket as soon as we can anyway,
438      * so we don't need to do anything here.  :-)
439      */
440 }
441
442 static void sk_tcp_close(Socket s);
443 static int sk_tcp_write(Socket s, const char *data, int len);
444 static int sk_tcp_write_oob(Socket s, const char *data, int len);
445 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
446 static void *sk_tcp_get_private_ptr(Socket s);
447 static void sk_tcp_set_frozen(Socket s, int is_frozen);
448 static const char *sk_tcp_socket_error(Socket s);
449
450 static struct socket_function_table tcp_fn_table = {
451     sk_tcp_plug,
452     sk_tcp_close,
453     sk_tcp_write,
454     sk_tcp_write_oob,
455     sk_tcp_flush,
456     sk_tcp_set_private_ptr,
457     sk_tcp_get_private_ptr,
458     sk_tcp_set_frozen,
459     sk_tcp_socket_error
460 };
461
462 Socket sk_register(OSSocket sockfd, Plug plug)
463 {
464     Actual_Socket ret;
465
466     /*
467      * Create Socket structure.
468      */
469     ret = snew(struct Socket_tag);
470     ret->fn = &tcp_fn_table;
471     ret->error = NULL;
472     ret->plug = plug;
473     bufchain_init(&ret->output_data);
474     ret->writable = 1;                 /* to start with */
475     ret->sending_oob = 0;
476     ret->frozen = 1;
477     ret->frozen_readable = 0;
478     ret->localhost_only = 0;           /* unused, but best init anyway */
479     ret->pending_error = 0;
480     ret->oobpending = FALSE;
481     ret->listener = 0;
482     ret->parent = ret->child = NULL;
483     ret->addr = NULL;
484     ret->connected = 1;
485
486     ret->s = sockfd;
487
488     if (ret->s < 0) {
489         ret->error = strerror(errno);
490         return (Socket) ret;
491     }
492
493     ret->oobinline = 0;
494
495     uxsel_tell(ret);
496     add234(sktree, ret);
497
498     return (Socket) ret;
499 }
500
501 static int try_connect(Actual_Socket sock)
502 {
503     int s;
504 #ifndef NO_IPV6
505     struct sockaddr_in6 a6;
506 #endif
507     struct sockaddr_in a;
508     struct sockaddr_un au;
509     const struct sockaddr *sa;
510     int err = 0;
511     short localport;
512     int fl, salen, family;
513
514     /*
515      * Remove the socket from the tree before we overwrite its
516      * internal socket id, because that forms part of the tree's
517      * sorting criterion. We'll add it back before exiting this
518      * function, whether we changed anything or not.
519      */
520     del234(sktree, sock);
521
522     if (sock->s >= 0)
523         close(sock->s);
524
525     plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
526
527     /*
528      * Open socket.
529      */
530     family = SOCKADDR_FAMILY(sock->addr, sock->step);
531     assert(family != AF_UNSPEC);
532     s = socket(family, SOCK_STREAM, 0);
533     sock->s = s;
534
535     if (s < 0) {
536         err = errno;
537         goto ret;
538     }
539
540     cloexec(s);
541
542     if (sock->oobinline) {
543         int b = TRUE;
544         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
545     }
546
547     if (sock->nodelay) {
548         int b = TRUE;
549         setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
550     }
551
552     if (sock->keepalive) {
553         int b = TRUE;
554         setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
555     }
556
557     /*
558      * Bind to local address.
559      */
560     if (sock->privport)
561         localport = 1023;              /* count from 1023 downwards */
562     else
563         localport = 0;                 /* just use port 0 (ie kernel picks) */
564
565     /* BSD IP stacks need sockaddr_in zeroed before filling in */
566     memset(&a,'\0',sizeof(struct sockaddr_in));
567 #ifndef NO_IPV6
568     memset(&a6,'\0',sizeof(struct sockaddr_in6));
569 #endif
570
571     /* We don't try to bind to a local address for UNIX domain sockets.  (Why
572      * do we bother doing the bind when localport == 0 anyway?) */
573     if (family != AF_UNIX) {
574         /* Loop round trying to bind */
575         while (1) {
576             int retcode;
577
578 #ifndef NO_IPV6
579             if (family == AF_INET6) {
580                 /* XXX use getaddrinfo to get a local address? */
581                 a6.sin6_family = AF_INET6;
582                 a6.sin6_addr = in6addr_any;
583                 a6.sin6_port = htons(localport);
584                 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
585             } else
586 #endif
587             {
588                 assert(family == AF_INET);
589                 a.sin_family = AF_INET;
590                 a.sin_addr.s_addr = htonl(INADDR_ANY);
591                 a.sin_port = htons(localport);
592                 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
593             }
594             if (retcode >= 0) {
595                 err = 0;
596                 break;                 /* done */
597             } else {
598                 err = errno;
599                 if (err != EADDRINUSE) /* failed, for a bad reason */
600                   break;
601             }
602             
603             if (localport == 0)
604               break;                   /* we're only looping once */
605             localport--;
606             if (localport == 0)
607               break;                   /* we might have got to the end */
608         }
609         
610         if (err)
611             goto ret;
612     }
613
614     /*
615      * Connect to remote address.
616      */
617     switch(family) {
618 #ifndef NO_IPV6
619       case AF_INET:
620         /* XXX would be better to have got getaddrinfo() to fill in the port. */
621         ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
622             htons(sock->port);
623         sa = (const struct sockaddr *)sock->step.ai->ai_addr;
624         salen = sock->step.ai->ai_addrlen;
625         break;
626       case AF_INET6:
627         ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
628             htons(sock->port);
629         sa = (const struct sockaddr *)sock->step.ai->ai_addr;
630         salen = sock->step.ai->ai_addrlen;
631         break;
632 #else
633       case AF_INET:
634         a.sin_family = AF_INET;
635         a.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
636         a.sin_port = htons((short) sock->port);
637         sa = (const struct sockaddr *)&a;
638         salen = sizeof a;
639         break;
640 #endif
641       case AF_UNIX:
642         assert(sock->port == 0);       /* to catch confused people */
643         assert(strlen(sock->addr->hostname) < sizeof au.sun_path);
644         memset(&au, 0, sizeof au);
645         au.sun_family = AF_UNIX;
646         strcpy(au.sun_path, sock->addr->hostname);
647         sa = (const struct sockaddr *)&au;
648         salen = sizeof au;
649         break;
650
651       default:
652         assert(0 && "unknown address family");
653         exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
654     }
655
656     fl = fcntl(s, F_GETFL);
657     if (fl != -1)
658         fcntl(s, F_SETFL, fl | O_NONBLOCK);
659
660     if ((connect(s, sa, salen)) < 0) {
661         if ( errno != EINPROGRESS ) {
662             err = errno;
663             goto ret;
664         }
665     } else {
666         /*
667          * If we _don't_ get EWOULDBLOCK, the connect has completed
668          * and we should set the socket as connected and writable.
669          */
670         sock->connected = 1;
671         sock->writable = 1;
672     }
673
674     uxsel_tell(sock);
675
676     ret:
677
678     /*
679      * No matter what happened, put the socket back in the tree.
680      */
681     add234(sktree, sock);
682
683     if (err)
684         plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
685     return err;
686 }
687
688 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
689               int nodelay, int keepalive, Plug plug)
690 {
691     Actual_Socket ret;
692     int err;
693
694     /*
695      * Create Socket structure.
696      */
697     ret = snew(struct Socket_tag);
698     ret->fn = &tcp_fn_table;
699     ret->error = NULL;
700     ret->plug = plug;
701     bufchain_init(&ret->output_data);
702     ret->connected = 0;                /* to start with */
703     ret->writable = 0;                 /* to start with */
704     ret->sending_oob = 0;
705     ret->frozen = 0;
706     ret->frozen_readable = 0;
707     ret->localhost_only = 0;           /* unused, but best init anyway */
708     ret->pending_error = 0;
709     ret->parent = ret->child = NULL;
710     ret->oobpending = FALSE;
711     ret->listener = 0;
712     ret->addr = addr;
713     START_STEP(ret->addr, ret->step);
714     ret->s = -1;
715     ret->oobinline = oobinline;
716     ret->nodelay = nodelay;
717     ret->keepalive = keepalive;
718     ret->privport = privport;
719     ret->port = port;
720
721     err = 0;
722     do {
723         err = try_connect(ret);
724     } while (err && sk_nextaddr(ret->addr, &ret->step));
725
726     if (err)
727         ret->error = strerror(err);
728
729     return (Socket) ret;
730 }
731
732 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int orig_address_family)
733 {
734     int s;
735 #ifndef NO_IPV6
736     struct addrinfo hints, *ai;
737     char portstr[6];
738     struct sockaddr_in6 a6;
739 #endif
740     struct sockaddr *addr;
741     int addrlen;
742     struct sockaddr_in a;
743     Actual_Socket ret;
744     int retcode;
745     int address_family;
746     int on = 1;
747
748     /*
749      * Create Socket structure.
750      */
751     ret = snew(struct Socket_tag);
752     ret->fn = &tcp_fn_table;
753     ret->error = NULL;
754     ret->plug = plug;
755     bufchain_init(&ret->output_data);
756     ret->writable = 0;                 /* to start with */
757     ret->sending_oob = 0;
758     ret->frozen = 0;
759     ret->frozen_readable = 0;
760     ret->localhost_only = local_host_only;
761     ret->pending_error = 0;
762     ret->parent = ret->child = NULL;
763     ret->oobpending = FALSE;
764     ret->listener = 1;
765     ret->addr = NULL;
766
767     /*
768      * Translate address_family from platform-independent constants
769      * into local reality.
770      */
771     address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
772 #ifndef NO_IPV6
773                       orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
774 #endif
775                       AF_UNSPEC);
776
777 #ifndef NO_IPV6
778     /* Let's default to IPv6.
779      * If the stack doesn't support IPv6, we will fall back to IPv4. */
780     if (address_family == AF_UNSPEC) address_family = AF_INET6;
781 #else
782     /* No other choice, default to IPv4 */
783     if (address_family == AF_UNSPEC)  address_family = AF_INET;
784 #endif
785
786     /*
787      * Open socket.
788      */
789     s = socket(address_family, SOCK_STREAM, 0);
790
791 #ifndef NO_IPV6
792     /* If the host doesn't support IPv6 try fallback to IPv4. */
793     if (s < 0 && address_family == AF_INET6) {
794         address_family = AF_INET;
795         s = socket(address_family, SOCK_STREAM, 0);
796     }
797 #endif
798
799     if (s < 0) {
800         ret->error = strerror(errno);
801         return (Socket) ret;
802     }
803
804     cloexec(s);
805
806     ret->oobinline = 0;
807
808     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
809
810     retcode = -1;
811     addr = NULL; addrlen = -1;         /* placate optimiser */
812
813     if (srcaddr != NULL) {
814 #ifndef NO_IPV6
815         hints.ai_flags = AI_NUMERICHOST;
816         hints.ai_family = address_family;
817         hints.ai_socktype = SOCK_STREAM;
818         hints.ai_protocol = 0;
819         hints.ai_addrlen = 0;
820         hints.ai_addr = NULL;
821         hints.ai_canonname = NULL;
822         hints.ai_next = NULL;
823         assert(port >= 0 && port <= 99999);
824         sprintf(portstr, "%d", port);
825         retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
826         if (retcode == 0) {
827             addr = ai->ai_addr;
828             addrlen = ai->ai_addrlen;
829         }
830 #else
831         memset(&a,'\0',sizeof(struct sockaddr_in));
832         a.sin_family = AF_INET;
833         a.sin_port = htons(port);
834         a.sin_addr.s_addr = inet_addr(srcaddr);
835         if (a.sin_addr.s_addr != (in_addr_t)(-1)) {
836             /* Override localhost_only with specified listen addr. */
837             ret->localhost_only = ipv4_is_loopback(a.sin_addr);
838         }
839         addr = (struct sockaddr *)&a;
840         addrlen = sizeof(a);
841         retcode = 0;
842 #endif
843     }
844
845     if (retcode != 0) {
846 #ifndef NO_IPV6
847         if (address_family == AF_INET6) {
848             memset(&a6,'\0',sizeof(struct sockaddr_in6));
849             a6.sin6_family = AF_INET6;
850             a6.sin6_port = htons(port);
851             if (local_host_only)
852                 a6.sin6_addr = in6addr_loopback;
853             else
854                 a6.sin6_addr = in6addr_any;
855             addr = (struct sockaddr *)&a6;
856             addrlen = sizeof(a6);
857         } else
858 #endif
859         {
860             memset(&a,'\0',sizeof(struct sockaddr_in));
861             a.sin_family = AF_INET;
862             a.sin_port = htons(port);
863             if (local_host_only)
864                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
865             else
866                 a.sin_addr.s_addr = htonl(INADDR_ANY);
867             addr = (struct sockaddr *)&a;
868             addrlen = sizeof(a);
869         }
870     }
871
872     retcode = bind(s, addr, addrlen);
873     if (retcode < 0) {
874         close(s);
875         ret->error = strerror(errno);
876         return (Socket) ret;
877     }
878
879     if (listen(s, SOMAXCONN) < 0) {
880         close(s);
881         ret->error = strerror(errno);
882         return (Socket) ret;
883     }
884
885 #ifndef NO_IPV6
886     /*
887      * If we were given ADDRTYPE_UNSPEC, we must also create an
888      * IPv4 listening socket and link it to this one.
889      */
890     if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
891         Actual_Socket other;
892
893         other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
894                                                local_host_only, ADDRTYPE_IPV4);
895
896         if (other) {
897             if (!other->error) {
898                 other->parent = ret;
899                 ret->child = other;
900             } else {
901                 /* If we couldn't create a listening socket on IPv4 as well
902                  * as IPv6, we must return an error overall. */
903                 close(s);
904                 sfree(ret);
905                 return (Socket) other;
906             }
907         }
908     }
909 #endif
910
911     ret->s = s;
912
913     uxsel_tell(ret);
914     add234(sktree, ret);
915
916     return (Socket) ret;
917 }
918
919 static void sk_tcp_close(Socket sock)
920 {
921     Actual_Socket s = (Actual_Socket) sock;
922
923     if (s->child)
924         sk_tcp_close((Socket)s->child);
925
926     uxsel_del(s->s);
927     del234(sktree, s);
928     close(s->s);
929     if (s->addr)
930         sk_addr_free(s->addr);
931     sfree(s);
932 }
933
934 void *sk_getxdmdata(void *sock, int *lenp)
935 {
936     Actual_Socket s = (Actual_Socket) sock;
937 #ifdef NO_IPV6
938     struct sockaddr_in addr;
939 #else
940     struct sockaddr_storage addr;
941     struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&addr;
942 #endif
943     struct sockaddr *sa = (struct sockaddr *)&addr;
944     struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
945     socklen_t addrlen;
946     char *buf;
947     static unsigned int unix_addr = 0xFFFFFFFF;
948
949     /*
950      * We must check that this socket really _is_ an Actual_Socket.
951      */
952     if (s->fn != &tcp_fn_table)
953         return NULL;                   /* failure */
954
955     addrlen = sizeof(addr);
956     if (getsockname(s->s, sa, &addrlen) < 0)
957         return NULL;
958     switch(sa->sa_family) {
959       case AF_INET:
960         *lenp = 6;
961         buf = snewn(*lenp, char);
962         PUT_32BIT_MSB_FIRST(buf, ntohl(sin->sin_addr.s_addr));
963         PUT_16BIT_MSB_FIRST(buf+4, ntohs(sin->sin_port));
964         break;
965 #ifndef NO_IPV6
966     case AF_INET6:
967         *lenp = 6;
968         buf = snewn(*lenp, char);
969         if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
970             memcpy(buf, sin6->sin6_addr.s6_addr + 12, 4);
971             PUT_16BIT_MSB_FIRST(buf+4, ntohs(sin6->sin6_port));
972         } else
973             /* This is stupid, but it's what XLib does. */
974             memset(buf, 0, 6);
975         break;
976 #endif
977       case AF_UNIX:
978         *lenp = 6;
979         buf = snewn(*lenp, char);
980         PUT_32BIT_MSB_FIRST(buf, unix_addr--);
981         PUT_16BIT_MSB_FIRST(buf+4, getpid());
982         break;
983
984         /* XXX IPV6 */
985
986       default:
987         return NULL;
988     }
989
990     return buf;
991 }
992
993 /*
994  * The function which tries to send on a socket once it's deemed
995  * writable.
996  */
997 void try_send(Actual_Socket s)
998 {
999     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1000         int nsent;
1001         int err;
1002         void *data;
1003         int len, urgentflag;
1004
1005         if (s->sending_oob) {
1006             urgentflag = MSG_OOB;
1007             len = s->sending_oob;
1008             data = &s->oobdata;
1009         } else {
1010             urgentflag = 0;
1011             bufchain_prefix(&s->output_data, &data, &len);
1012         }
1013         nsent = send(s->s, data, len, urgentflag);
1014         noise_ultralight(nsent);
1015         if (nsent <= 0) {
1016             err = (nsent < 0 ? errno : 0);
1017             if (err == EWOULDBLOCK) {
1018                 /*
1019                  * Perfectly normal: we've sent all we can for the moment.
1020                  */
1021                 s->writable = FALSE;
1022                 return;
1023             } else {
1024                 /*
1025                  * We unfortunately can't just call plug_closing(),
1026                  * because it's quite likely that we're currently
1027                  * _in_ a call from the code we'd be calling back
1028                  * to, so we'd have to make half the SSH code
1029                  * reentrant. Instead we flag a pending error on
1030                  * the socket, to be dealt with (by calling
1031                  * plug_closing()) at some suitable future moment.
1032                  */
1033                 s->pending_error = err;
1034                 return;
1035             }
1036         } else {
1037             if (s->sending_oob) {
1038                 if (nsent < len) {
1039                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1040                     s->sending_oob = len - nsent;
1041                 } else {
1042                     s->sending_oob = 0;
1043                 }
1044             } else {
1045                 bufchain_consume(&s->output_data, nsent);
1046             }
1047         }
1048     }
1049     uxsel_tell(s);
1050 }
1051
1052 static int sk_tcp_write(Socket sock, const char *buf, int len)
1053 {
1054     Actual_Socket s = (Actual_Socket) sock;
1055
1056     /*
1057      * Add the data to the buffer list on the socket.
1058      */
1059     bufchain_add(&s->output_data, buf, len);
1060
1061     /*
1062      * Now try sending from the start of the buffer list.
1063      */
1064     if (s->writable)
1065         try_send(s);
1066
1067     /*
1068      * Update the select() status to correctly reflect whether or
1069      * not we should be selecting for write.
1070      */
1071     uxsel_tell(s);
1072
1073     return bufchain_size(&s->output_data);
1074 }
1075
1076 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1077 {
1078     Actual_Socket s = (Actual_Socket) sock;
1079
1080     /*
1081      * Replace the buffer list on the socket with the data.
1082      */
1083     bufchain_clear(&s->output_data);
1084     assert(len <= sizeof(s->oobdata));
1085     memcpy(s->oobdata, buf, len);
1086     s->sending_oob = len;
1087
1088     /*
1089      * Now try sending from the start of the buffer list.
1090      */
1091     if (s->writable)
1092         try_send(s);
1093
1094     /*
1095      * Update the select() status to correctly reflect whether or
1096      * not we should be selecting for write.
1097      */
1098     uxsel_tell(s);
1099
1100     return s->sending_oob;
1101 }
1102
1103 static int net_select_result(int fd, int event)
1104 {
1105     int ret;
1106     char buf[20480];                   /* nice big buffer for plenty of speed */
1107     Actual_Socket s;
1108     u_long atmark;
1109
1110     /* Find the Socket structure */
1111     s = find234(sktree, &fd, cmpforsearch);
1112     if (!s)
1113         return 1;                      /* boggle */
1114
1115     noise_ultralight(event);
1116
1117     switch (event) {
1118       case 4:                          /* exceptional */
1119         if (!s->oobinline) {
1120             /*
1121              * On a non-oobinline socket, this indicates that we
1122              * can immediately perform an OOB read and get back OOB
1123              * data, which we will send to the back end with
1124              * type==2 (urgent data).
1125              */
1126             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1127             noise_ultralight(ret);
1128             if (ret <= 0) {
1129                 return plug_closing(s->plug,
1130                                     ret == 0 ? "Internal networking trouble" :
1131                                     strerror(errno), errno, 0);
1132             } else {
1133                 /*
1134                  * Receiving actual data on a socket means we can
1135                  * stop falling back through the candidate
1136                  * addresses to connect to.
1137                  */
1138                 if (s->addr) {
1139                     sk_addr_free(s->addr);
1140                     s->addr = NULL;
1141                 }
1142                 return plug_receive(s->plug, 2, buf, ret);
1143             }
1144             break;
1145         }
1146
1147         /*
1148          * If we reach here, this is an oobinline socket, which
1149          * means we should set s->oobpending and then deal with it
1150          * when we get called for the readability event (which
1151          * should also occur).
1152          */
1153         s->oobpending = TRUE;
1154         break;
1155       case 1:                          /* readable; also acceptance */
1156         if (s->listener) {
1157             /*
1158              * On a listening socket, the readability event means a
1159              * connection is ready to be accepted.
1160              */
1161 #ifdef NO_IPV6
1162             struct sockaddr_in ss;
1163 #else
1164             struct sockaddr_storage ss;
1165 #endif
1166             socklen_t addrlen = sizeof(ss);
1167             int t;  /* socket of connection */
1168             int fl;
1169
1170             memset(&ss, 0, addrlen);
1171             t = accept(s->s, (struct sockaddr *)&ss, &addrlen);
1172             if (t < 0) {
1173                 break;
1174             }
1175
1176             fl = fcntl(t, F_GETFL);
1177             if (fl != -1)
1178                 fcntl(t, F_SETFL, fl | O_NONBLOCK);
1179
1180             if (s->localhost_only &&
1181                 !sockaddr_is_loopback((struct sockaddr *)&ss)) {
1182                 close(t);              /* someone let nonlocal through?! */
1183             } else if (plug_accepting(s->plug, t)) {
1184                 close(t);              /* denied or error */
1185             }
1186             break;
1187         }
1188
1189         /*
1190          * If we reach here, this is not a listening socket, so
1191          * readability really means readability.
1192          */
1193
1194         /* In the case the socket is still frozen, we don't even bother */
1195         if (s->frozen) {
1196             s->frozen_readable = 1;
1197             break;
1198         }
1199
1200         /*
1201          * We have received data on the socket. For an oobinline
1202          * socket, this might be data _before_ an urgent pointer,
1203          * in which case we send it to the back end with type==1
1204          * (data prior to urgent).
1205          */
1206         if (s->oobinline && s->oobpending) {
1207             atmark = 1;
1208             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1209                 s->oobpending = FALSE; /* clear this indicator */
1210         } else
1211             atmark = 1;
1212
1213         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1214         noise_ultralight(ret);
1215         if (ret < 0) {
1216             if (errno == EWOULDBLOCK) {
1217                 break;
1218             }
1219         }
1220         if (ret < 0) {
1221             /*
1222              * An error at this point _might_ be an error reported
1223              * by a non-blocking connect(). So before we return a
1224              * panic status to the user, let's just see whether
1225              * that's the case.
1226              */
1227             int err = errno;
1228             if (s->addr) {
1229                 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1230                 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1231                     err = try_connect(s);
1232                 }
1233             }
1234             if (err != 0)
1235                 return plug_closing(s->plug, strerror(err), err, 0);
1236         } else if (0 == ret) {
1237             return plug_closing(s->plug, NULL, 0, 0);
1238         } else {
1239             /*
1240              * Receiving actual data on a socket means we can
1241              * stop falling back through the candidate
1242              * addresses to connect to.
1243              */
1244             if (s->addr) {
1245                 sk_addr_free(s->addr);
1246                 s->addr = NULL;
1247             }
1248             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1249         }
1250         break;
1251       case 2:                          /* writable */
1252         if (!s->connected) {
1253             /*
1254              * select() reports a socket as _writable_ when an
1255              * asynchronous connection is completed.
1256              */
1257             s->connected = s->writable = 1;
1258             uxsel_tell(s);
1259             break;
1260         } else {
1261             int bufsize_before, bufsize_after;
1262             s->writable = 1;
1263             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1264             try_send(s);
1265             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1266             if (bufsize_after < bufsize_before)
1267                 plug_sent(s->plug, bufsize_after);
1268         }
1269         break;
1270     }
1271
1272     return 1;
1273 }
1274
1275 /*
1276  * Deal with socket errors detected in try_send().
1277  */
1278 void net_pending_errors(void)
1279 {
1280     int i;
1281     Actual_Socket s;
1282
1283     /*
1284      * This might be a fiddly business, because it's just possible
1285      * that handling a pending error on one socket might cause
1286      * others to be closed. (I can't think of any reason this might
1287      * happen in current SSH implementation, but to maintain
1288      * generality of this network layer I'll assume the worst.)
1289      * 
1290      * So what we'll do is search the socket list for _one_ socket
1291      * with a pending error, and then handle it, and then search
1292      * the list again _from the beginning_. Repeat until we make a
1293      * pass with no socket errors present. That way we are
1294      * protected against the socket list changing under our feet.
1295      */
1296
1297     do {
1298         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1299             if (s->pending_error) {
1300                 /*
1301                  * An error has occurred on this socket. Pass it to the
1302                  * plug.
1303                  */
1304                 plug_closing(s->plug, strerror(s->pending_error),
1305                              s->pending_error, 0);
1306                 break;
1307             }
1308         }
1309     } while (s);
1310 }
1311
1312 /*
1313  * Each socket abstraction contains a `void *' private field in
1314  * which the client can keep state.
1315  */
1316 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1317 {
1318     Actual_Socket s = (Actual_Socket) sock;
1319     s->private_ptr = ptr;
1320 }
1321
1322 static void *sk_tcp_get_private_ptr(Socket sock)
1323 {
1324     Actual_Socket s = (Actual_Socket) sock;
1325     return s->private_ptr;
1326 }
1327
1328 /*
1329  * Special error values are returned from sk_namelookup and sk_new
1330  * if there's a problem. These functions extract an error message,
1331  * or return NULL if there's no problem.
1332  */
1333 const char *sk_addr_error(SockAddr addr)
1334 {
1335     return addr->error;
1336 }
1337 static const char *sk_tcp_socket_error(Socket sock)
1338 {
1339     Actual_Socket s = (Actual_Socket) sock;
1340     return s->error;
1341 }
1342
1343 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1344 {
1345     Actual_Socket s = (Actual_Socket) sock;
1346     if (s->frozen == is_frozen)
1347         return;
1348     s->frozen = is_frozen;
1349     if (!is_frozen && s->frozen_readable) {
1350         char c;
1351         recv(s->s, &c, 1, MSG_PEEK);
1352     }
1353     s->frozen_readable = 0;
1354     uxsel_tell(s);
1355 }
1356
1357 static void uxsel_tell(Actual_Socket s)
1358 {
1359     int rwx = 0;
1360     if (s->listener) {
1361         rwx |= 1;                       /* read == accept */
1362     } else {
1363         if (!s->connected)
1364             rwx |= 2;                   /* write == connect */
1365         if (s->connected && !s->frozen)
1366             rwx |= 1 | 4;               /* read, except */
1367         if (bufchain_size(&s->output_data))
1368             rwx |= 2;                   /* write */
1369     }
1370     uxsel_set(s->s, rwx, net_select_result);
1371 }
1372
1373 int net_service_lookup(char *service)
1374 {
1375     struct servent *se;
1376     se = getservbyname(service, NULL);
1377     if (se != NULL)
1378         return ntohs(se->s_port);
1379     else
1380         return 0;
1381 }
1382
1383 SockAddr platform_get_x11_unix_address(const char *display, int displaynum,
1384                                        char **canonicalname)
1385 {
1386     SockAddr ret = snew(struct SockAddr_tag);
1387     int n;
1388
1389     memset(ret, 0, sizeof *ret);
1390     ret->superfamily = UNIX;
1391     /*
1392      * Mac OS X Leopard uses an innovative X display naming
1393      * convention in which the entire display name is the path to
1394      * the Unix socket, including the trailing :0 which only
1395      * _looks_ like a display number. Heuristically, I think
1396      * detecting this by means of a leading slash ought to be
1397      * adequate.
1398      */
1399     if (display[0] == '/') {
1400         n = snprintf(ret->hostname, sizeof ret->hostname,
1401                      "%s", display);
1402     } else {
1403         n = snprintf(ret->hostname, sizeof ret->hostname,
1404                      "%s%d", X11_UNIX_PATH, displaynum);
1405     }
1406     if(n < 0)
1407         ret->error = "snprintf failed";
1408     else if(n >= sizeof ret->hostname)
1409         ret->error = "X11 UNIX name too long";
1410     else
1411         *canonicalname = dupstr(ret->hostname);
1412 #ifndef NO_IPV6
1413     ret->ais = NULL;
1414 #else
1415     ret->addresses = NULL;
1416     ret->naddresses = 0;
1417 #endif
1418     return ret;
1419 }