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