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