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