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