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