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