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