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