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