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