2 * Unix networking abstraction.
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>
20 #define DEFINE_PLUG_METHOD_MACROS
25 /* Solaris needs <sys/sockio.h> for SIOCATMARK. */
27 #include <sys/sockio.h>
31 # define X11_UNIX_PATH "/tmp/.X11-unix/X"
35 * We used to typedef struct Socket_tag *Socket.
37 * Since we have made the networking abstraction slightly more
38 * abstract, Socket no longer means a tcp socket (it could mean
39 * an ssl socket). So now we must use Actual_Socket when we know
40 * we are talking about a tcp socket.
42 typedef struct Socket_tag *Actual_Socket;
45 * Mutable state that goes with a SockAddr: stores information
46 * about where in the list of candidate IP(v*) addresses we've
49 typedef struct SockAddrStep_tag SockAddrStep;
50 struct SockAddrStep_tag {
52 struct addrinfo *ai; /* steps along addr->ais */
58 struct socket_function_table *fn;
59 /* the above variable absolutely *must* be the first in this structure */
65 int connected; /* irrelevant for listening sockets */
67 int frozen; /* this causes readability notifications to be ignored */
68 int frozen_readable; /* this means we missed at least one readability
69 * notification while we were frozen */
70 int localhost_only; /* for listening sockets */
73 int oobpending; /* is there OOB data available to read? */
75 int pending_error; /* in case send() returns error */
77 int nodelay, keepalive; /* for connect()-type sockets */
78 int privport, port; /* and again */
82 * We sometimes need pairs of Socket structures to be linked:
83 * if we are listening on the same IPv6 and v4 port, for
84 * example. So here we define `parent' and `child' pointers to
87 Actual_Socket parent, child;
92 enum { UNRESOLVED, UNIX, IP } superfamily;
94 struct addrinfo *ais; /* Addresses IPv6 style. */
96 unsigned long *addresses; /* Addresses IPv4 style. */
99 char hostname[512]; /* Store an unresolved host name. */
103 * Which address family this address belongs to. AF_INET for IPv4;
104 * AF_INET6 for IPv6; AF_UNSPEC indicates that name resolution has
105 * not been done and a simple host name is held in this SockAddr
109 #define SOCKADDR_FAMILY(addr, step) \
110 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
111 (addr)->superfamily == UNIX ? AF_UNIX : \
112 (step).ai ? (step).ai->ai_family : AF_INET)
114 #define SOCKADDR_FAMILY(addr, step) \
115 ((addr)->superfamily == UNRESOLVED ? AF_UNSPEC : \
116 (addr)->superfamily == UNIX ? AF_UNIX : AF_INET)
120 * Start a SockAddrStep structure to step through multiple
124 #define START_STEP(addr, step) \
125 ((step).ai = (addr)->ais, (step).curraddr = 0)
127 #define START_STEP(addr, step) \
128 ((step).curraddr = 0)
131 static tree234 *sktree;
133 static void uxsel_tell(Actual_Socket s);
135 static int cmpfortree(void *av, void *bv)
137 Actual_Socket a = (Actual_Socket) av, b = (Actual_Socket) bv;
138 int as = a->s, bs = b->s;
150 static int cmpforsearch(void *av, void *bv)
152 Actual_Socket b = (Actual_Socket) bv;
153 int as = *(int *)av, bs = b->s;
163 sktree = newtree234(cmpfortree);
166 void sk_cleanup(void)
172 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
178 SockAddr sk_namelookup(const char *host, char **canonicalname, int address_family)
180 SockAddr ret = snew(struct SockAddr_tag);
182 struct addrinfo hints;
186 struct hostent *h = NULL;
191 /* Clear the structure and default to IPv4. */
192 memset(ret, 0, sizeof(struct SockAddr_tag));
193 ret->superfamily = UNRESOLVED;
198 hints.ai_flags = AI_CANONNAME;
199 hints.ai_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
200 address_family == ADDRTYPE_IPV6 ? AF_INET6 :
202 hints.ai_socktype = SOCK_STREAM;
203 hints.ai_protocol = 0;
204 hints.ai_addrlen = 0;
205 hints.ai_addr = NULL;
206 hints.ai_canonname = NULL;
207 hints.ai_next = NULL;
208 err = getaddrinfo(host, NULL, &hints, &ret->ais);
210 ret->error = gai_strerror(err);
213 ret->superfamily = IP;
215 if (ret->ais->ai_canonname != NULL)
216 strncat(realhost, ret->ais->ai_canonname, sizeof(realhost) - 1);
218 strncat(realhost, host, sizeof(realhost) - 1);
220 if ((a = inet_addr(host)) == (unsigned long)(in_addr_t)(-1)) {
222 * Otherwise use the IPv4-only gethostbyname... (NOTE:
223 * we don't use gethostbyname as a fallback!)
225 if (ret->superfamily == UNRESOLVED) {
226 /*debug(("Resolving \"%s\" with gethostbyname() (IPv4 only)...\n", host)); */
227 if ( (h = gethostbyname(host)) )
228 ret->superfamily = IP;
230 if (ret->superfamily == UNRESOLVED) {
231 ret->error = (h_errno == HOST_NOT_FOUND ||
232 h_errno == NO_DATA ||
233 h_errno == NO_ADDRESS ? "Host does not exist" :
234 h_errno == TRY_AGAIN ?
235 "Temporary name service failure" :
236 "gethostbyname: unknown error");
239 /* This way we are always sure the h->h_name is valid :) */
240 strncpy(realhost, h->h_name, sizeof(realhost));
241 for (n = 0; h->h_addr_list[n]; n++);
242 ret->addresses = snewn(n, unsigned long);
244 for (n = 0; n < ret->naddresses; n++) {
245 memcpy(&a, h->h_addr_list[n], sizeof(a));
246 ret->addresses[n] = ntohl(a);
250 * This must be a numeric IPv4 address because it caused a
251 * success return from inet_addr.
253 ret->superfamily = IP;
254 strncpy(realhost, host, sizeof(realhost));
255 ret->addresses = snew(unsigned long);
257 ret->addresses[0] = ntohl(a);
260 realhost[lenof(realhost)-1] = '\0';
261 *canonicalname = snewn(1+strlen(realhost), char);
262 strcpy(*canonicalname, realhost);
266 SockAddr sk_nonamelookup(const char *host)
268 SockAddr ret = snew(struct SockAddr_tag);
270 ret->superfamily = UNRESOLVED;
271 strncpy(ret->hostname, host, lenof(ret->hostname));
272 ret->hostname[lenof(ret->hostname)-1] = '\0';
276 ret->addresses = NULL;
281 static int sk_nextaddr(SockAddr addr, SockAddrStep *step)
284 if (step->ai && step->ai->ai_next) {
285 step->ai = step->ai->ai_next;
290 if (step->curraddr+1 < addr->naddresses) {
299 void sk_getaddr(SockAddr addr, char *buf, int buflen)
302 if (addr->superfamily == UNRESOLVED) {
303 strncpy(buf, addr->hostname, buflen);
304 buf[buflen-1] = '\0';
307 if (getnameinfo(addr->ais->ai_addr, addr->ais->ai_addrlen, buf, buflen,
308 NULL, 0, NI_NUMERICHOST) != 0) {
310 strncat(buf, "<unknown>", buflen - 1);
315 START_STEP(addr, step);
316 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
317 a.s_addr = htonl(addr->addresses[0]);
318 strncpy(buf, inet_ntoa(a), buflen);
319 buf[buflen-1] = '\0';
324 int sk_hostname_is_local(char *name)
326 return !strcmp(name, "localhost");
329 #define ipv4_is_loopback(addr) \
330 (((addr).s_addr & htonl(0xff000000)) == htonl(0x7f000000))
332 static int sockaddr_is_loopback(struct sockaddr *sa)
334 struct sockaddr_in *sin;
336 struct sockaddr_in6 *sin6;
339 switch (sa->sa_family) {
341 sin = (struct sockaddr_in *)sa;
342 return ipv4_is_loopback(sin->sin_addr);
345 sin6 = (struct sockaddr_in6 *)sa;
346 return IN6_IS_ADDR_LOOPBACK(&sin6->sin6_addr);
355 int sk_address_is_local(SockAddr addr)
358 if (addr->superfamily == UNRESOLVED)
359 return 0; /* we don't know; assume not */
362 return sockaddr_is_loopback(addr->ais->ai_addr);
366 START_STEP(addr, step);
367 assert(SOCKADDR_FAMILY(addr, step) == AF_INET);
368 a.s_addr = htonl(addr->addresses[0]);
369 return ipv4_is_loopback(a);
374 int sk_addrtype(SockAddr addr)
378 START_STEP(addr, step);
379 family = SOCKADDR_FAMILY(addr, step);
381 return (family == AF_INET ? ADDRTYPE_IPV4 :
383 family == AF_INET6 ? ADDRTYPE_IPV6 :
388 void sk_addrcopy(SockAddr addr, char *buf)
392 START_STEP(addr, step);
393 family = SOCKADDR_FAMILY(addr, step);
396 if (family == AF_INET)
397 memcpy(buf, &((struct sockaddr_in *)step.ai->ai_addr)->sin_addr,
398 sizeof(struct in_addr));
399 else if (family == AF_INET6)
400 memcpy(buf, &((struct sockaddr_in6 *)step.ai->ai_addr)->sin6_addr,
401 sizeof(struct in6_addr));
407 assert(family == AF_INET);
408 a.s_addr = htonl(addr->addresses[step.curraddr]);
409 memcpy(buf, (char*) &a.s_addr, 4);
413 void sk_addr_free(SockAddr addr)
417 if (addr->ais != NULL)
418 freeaddrinfo(addr->ais);
420 sfree(addr->addresses);
425 static Plug sk_tcp_plug(Socket sock, Plug p)
427 Actual_Socket s = (Actual_Socket) sock;
434 static void sk_tcp_flush(Socket s)
437 * We send data to the socket as soon as we can anyway,
438 * so we don't need to do anything here. :-)
442 static void sk_tcp_close(Socket s);
443 static int sk_tcp_write(Socket s, const char *data, int len);
444 static int sk_tcp_write_oob(Socket s, const char *data, int len);
445 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
446 static void *sk_tcp_get_private_ptr(Socket s);
447 static void sk_tcp_set_frozen(Socket s, int is_frozen);
448 static const char *sk_tcp_socket_error(Socket s);
450 static struct socket_function_table tcp_fn_table = {
456 sk_tcp_set_private_ptr,
457 sk_tcp_get_private_ptr,
462 Socket sk_register(OSSocket sockfd, Plug plug)
467 * Create Socket structure.
469 ret = snew(struct Socket_tag);
470 ret->fn = &tcp_fn_table;
473 bufchain_init(&ret->output_data);
474 ret->writable = 1; /* to start with */
475 ret->sending_oob = 0;
477 ret->frozen_readable = 0;
478 ret->localhost_only = 0; /* unused, but best init anyway */
479 ret->pending_error = 0;
480 ret->oobpending = FALSE;
482 ret->parent = ret->child = NULL;
489 ret->error = strerror(errno);
501 static int try_connect(Actual_Socket sock)
505 struct sockaddr_in6 a6;
507 struct sockaddr_in a;
508 struct sockaddr_un au;
509 const struct sockaddr *sa;
512 int fl, salen, family;
515 * Remove the socket from the tree before we overwrite its
516 * internal socket id, because that forms part of the tree's
517 * sorting criterion. We'll add it back before exiting this
518 * function, whether we changed anything or not.
520 del234(sktree, sock);
525 plug_log(sock->plug, 0, sock->addr, sock->port, NULL, 0);
530 family = SOCKADDR_FAMILY(sock->addr, sock->step);
531 assert(family != AF_UNSPEC);
532 s = socket(family, SOCK_STREAM, 0);
542 if (sock->oobinline) {
544 setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
549 setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
552 if (sock->keepalive) {
554 setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, (void *) &b, sizeof(b));
558 * Bind to local address.
561 localport = 1023; /* count from 1023 downwards */
563 localport = 0; /* just use port 0 (ie kernel picks) */
565 /* BSD IP stacks need sockaddr_in zeroed before filling in */
566 memset(&a,'\0',sizeof(struct sockaddr_in));
568 memset(&a6,'\0',sizeof(struct sockaddr_in6));
571 /* We don't try to bind to a local address for UNIX domain sockets. (Why
572 * do we bother doing the bind when localport == 0 anyway?) */
573 if (family != AF_UNIX) {
574 /* Loop round trying to bind */
579 if (family == AF_INET6) {
580 /* XXX use getaddrinfo to get a local address? */
581 a6.sin6_family = AF_INET6;
582 a6.sin6_addr = in6addr_any;
583 a6.sin6_port = htons(localport);
584 retcode = bind(s, (struct sockaddr *) &a6, sizeof(a6));
588 assert(family == AF_INET);
589 a.sin_family = AF_INET;
590 a.sin_addr.s_addr = htonl(INADDR_ANY);
591 a.sin_port = htons(localport);
592 retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
599 if (err != EADDRINUSE) /* failed, for a bad reason */
604 break; /* we're only looping once */
607 break; /* we might have got to the end */
615 * Connect to remote address.
620 /* XXX would be better to have got getaddrinfo() to fill in the port. */
621 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
623 sa = (const struct sockaddr *)sock->step.ai->ai_addr;
624 salen = sock->step.ai->ai_addrlen;
627 ((struct sockaddr_in *)sock->step.ai->ai_addr)->sin_port =
629 sa = (const struct sockaddr *)sock->step.ai->ai_addr;
630 salen = sock->step.ai->ai_addrlen;
634 a.sin_family = AF_INET;
635 a.sin_addr.s_addr = htonl(sock->addr->addresses[sock->step.curraddr]);
636 a.sin_port = htons((short) sock->port);
637 sa = (const struct sockaddr *)&a;
642 assert(sock->port == 0); /* to catch confused people */
643 assert(strlen(sock->addr->hostname) < sizeof au.sun_path);
644 memset(&au, 0, sizeof au);
645 au.sun_family = AF_UNIX;
646 strcpy(au.sun_path, sock->addr->hostname);
647 sa = (const struct sockaddr *)&au;
652 assert(0 && "unknown address family");
653 exit(1); /* XXX: GCC doesn't understand assert() on some systems. */
656 fl = fcntl(s, F_GETFL);
658 fcntl(s, F_SETFL, fl | O_NONBLOCK);
660 if ((connect(s, sa, salen)) < 0) {
661 if ( errno != EINPROGRESS ) {
667 * If we _don't_ get EWOULDBLOCK, the connect has completed
668 * and we should set the socket as connected and writable.
679 * No matter what happened, put the socket back in the tree.
681 add234(sktree, sock);
684 plug_log(sock->plug, 1, sock->addr, sock->port, strerror(err), err);
688 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
689 int nodelay, int keepalive, Plug plug)
695 * Create Socket structure.
697 ret = snew(struct Socket_tag);
698 ret->fn = &tcp_fn_table;
701 bufchain_init(&ret->output_data);
702 ret->connected = 0; /* to start with */
703 ret->writable = 0; /* to start with */
704 ret->sending_oob = 0;
706 ret->frozen_readable = 0;
707 ret->localhost_only = 0; /* unused, but best init anyway */
708 ret->pending_error = 0;
709 ret->parent = ret->child = NULL;
710 ret->oobpending = FALSE;
713 START_STEP(ret->addr, ret->step);
715 ret->oobinline = oobinline;
716 ret->nodelay = nodelay;
717 ret->keepalive = keepalive;
718 ret->privport = privport;
723 err = try_connect(ret);
724 } while (err && sk_nextaddr(ret->addr, &ret->step));
727 ret->error = strerror(err);
732 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only, int orig_address_family)
736 struct addrinfo hints, *ai;
738 struct sockaddr_in6 a6;
740 struct sockaddr *addr;
742 struct sockaddr_in a;
749 * Create Socket structure.
751 ret = snew(struct Socket_tag);
752 ret->fn = &tcp_fn_table;
755 bufchain_init(&ret->output_data);
756 ret->writable = 0; /* to start with */
757 ret->sending_oob = 0;
759 ret->frozen_readable = 0;
760 ret->localhost_only = local_host_only;
761 ret->pending_error = 0;
762 ret->parent = ret->child = NULL;
763 ret->oobpending = FALSE;
768 * Translate address_family from platform-independent constants
769 * into local reality.
771 address_family = (orig_address_family == ADDRTYPE_IPV4 ? AF_INET :
773 orig_address_family == ADDRTYPE_IPV6 ? AF_INET6 :
778 /* Let's default to IPv6.
779 * If the stack doesn't support IPv6, we will fall back to IPv4. */
780 if (address_family == AF_UNSPEC) address_family = AF_INET6;
782 /* No other choice, default to IPv4 */
783 if (address_family == AF_UNSPEC) address_family = AF_INET;
789 s = socket(address_family, SOCK_STREAM, 0);
792 /* If the host doesn't support IPv6 try fallback to IPv4. */
793 if (s < 0 && address_family == AF_INET6) {
794 address_family = AF_INET;
795 s = socket(address_family, SOCK_STREAM, 0);
800 ret->error = strerror(errno);
808 setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
811 addr = NULL; addrlen = -1; /* placate optimiser */
813 if (srcaddr != NULL) {
815 hints.ai_flags = AI_NUMERICHOST;
816 hints.ai_family = address_family;
817 hints.ai_socktype = SOCK_STREAM;
818 hints.ai_protocol = 0;
819 hints.ai_addrlen = 0;
820 hints.ai_addr = NULL;
821 hints.ai_canonname = NULL;
822 hints.ai_next = NULL;
823 assert(port >= 0 && port <= 99999);
824 sprintf(portstr, "%d", port);
825 retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
828 addrlen = ai->ai_addrlen;
831 memset(&a,'\0',sizeof(struct sockaddr_in));
832 a.sin_family = AF_INET;
833 a.sin_port = htons(port);
834 a.sin_addr.s_addr = inet_addr(srcaddr);
835 if (a.sin_addr.s_addr != (in_addr_t)(-1)) {
836 /* Override localhost_only with specified listen addr. */
837 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
839 addr = (struct sockaddr *)&a;
847 if (address_family == AF_INET6) {
848 memset(&a6,'\0',sizeof(struct sockaddr_in6));
849 a6.sin6_family = AF_INET6;
850 a6.sin6_port = htons(port);
852 a6.sin6_addr = in6addr_loopback;
854 a6.sin6_addr = in6addr_any;
855 addr = (struct sockaddr *)&a6;
856 addrlen = sizeof(a6);
860 memset(&a,'\0',sizeof(struct sockaddr_in));
861 a.sin_family = AF_INET;
862 a.sin_port = htons(port);
864 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
866 a.sin_addr.s_addr = htonl(INADDR_ANY);
867 addr = (struct sockaddr *)&a;
872 retcode = bind(s, addr, addrlen);
875 ret->error = strerror(errno);
879 if (listen(s, SOMAXCONN) < 0) {
881 ret->error = strerror(errno);
887 * If we were given ADDRTYPE_UNSPEC, we must also create an
888 * IPv4 listening socket and link it to this one.
890 if (address_family == AF_INET6 && orig_address_family == ADDRTYPE_UNSPEC) {
893 other = (Actual_Socket) sk_newlistener(srcaddr, port, plug,
894 local_host_only, ADDRTYPE_IPV4);
901 /* If we couldn't create a listening socket on IPv4 as well
902 * as IPv6, we must return an error overall. */
905 return (Socket) other;
919 static void sk_tcp_close(Socket sock)
921 Actual_Socket s = (Actual_Socket) sock;
924 sk_tcp_close((Socket)s->child);
930 sk_addr_free(s->addr);
934 void *sk_getxdmdata(void *sock, int *lenp)
936 Actual_Socket s = (Actual_Socket) sock;
938 struct sockaddr_in addr;
940 struct sockaddr_storage addr;
941 struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)&addr;
943 struct sockaddr *sa = (struct sockaddr *)&addr;
944 struct sockaddr_in *sin = (struct sockaddr_in *)&addr;
947 static unsigned int unix_addr = 0xFFFFFFFF;
950 * We must check that this socket really _is_ an Actual_Socket.
952 if (s->fn != &tcp_fn_table)
953 return NULL; /* failure */
955 addrlen = sizeof(addr);
956 if (getsockname(s->s, sa, &addrlen) < 0)
958 switch(sa->sa_family) {
961 buf = snewn(*lenp, char);
962 PUT_32BIT_MSB_FIRST(buf, ntohl(sin->sin_addr.s_addr));
963 PUT_16BIT_MSB_FIRST(buf+4, ntohs(sin->sin_port));
968 buf = snewn(*lenp, char);
969 if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
970 memcpy(buf, sin6->sin6_addr.s6_addr + 12, 4);
971 PUT_16BIT_MSB_FIRST(buf+4, ntohs(sin6->sin6_port));
973 /* This is stupid, but it's what XLib does. */
979 buf = snewn(*lenp, char);
980 PUT_32BIT_MSB_FIRST(buf, unix_addr--);
981 PUT_16BIT_MSB_FIRST(buf+4, getpid());
994 * The function which tries to send on a socket once it's deemed
997 void try_send(Actual_Socket s)
999 while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
1003 int len, urgentflag;
1005 if (s->sending_oob) {
1006 urgentflag = MSG_OOB;
1007 len = s->sending_oob;
1011 bufchain_prefix(&s->output_data, &data, &len);
1013 nsent = send(s->s, data, len, urgentflag);
1014 noise_ultralight(nsent);
1016 err = (nsent < 0 ? errno : 0);
1017 if (err == EWOULDBLOCK) {
1019 * Perfectly normal: we've sent all we can for the moment.
1021 s->writable = FALSE;
1025 * We unfortunately can't just call plug_closing(),
1026 * because it's quite likely that we're currently
1027 * _in_ a call from the code we'd be calling back
1028 * to, so we'd have to make half the SSH code
1029 * reentrant. Instead we flag a pending error on
1030 * the socket, to be dealt with (by calling
1031 * plug_closing()) at some suitable future moment.
1033 s->pending_error = err;
1037 if (s->sending_oob) {
1039 memmove(s->oobdata, s->oobdata+nsent, len-nsent);
1040 s->sending_oob = len - nsent;
1045 bufchain_consume(&s->output_data, nsent);
1052 static int sk_tcp_write(Socket sock, const char *buf, int len)
1054 Actual_Socket s = (Actual_Socket) sock;
1057 * Add the data to the buffer list on the socket.
1059 bufchain_add(&s->output_data, buf, len);
1062 * Now try sending from the start of the buffer list.
1068 * Update the select() status to correctly reflect whether or
1069 * not we should be selecting for write.
1073 return bufchain_size(&s->output_data);
1076 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
1078 Actual_Socket s = (Actual_Socket) sock;
1081 * Replace the buffer list on the socket with the data.
1083 bufchain_clear(&s->output_data);
1084 assert(len <= sizeof(s->oobdata));
1085 memcpy(s->oobdata, buf, len);
1086 s->sending_oob = len;
1089 * Now try sending from the start of the buffer list.
1095 * Update the select() status to correctly reflect whether or
1096 * not we should be selecting for write.
1100 return s->sending_oob;
1103 static int net_select_result(int fd, int event)
1106 char buf[20480]; /* nice big buffer for plenty of speed */
1110 /* Find the Socket structure */
1111 s = find234(sktree, &fd, cmpforsearch);
1113 return 1; /* boggle */
1115 noise_ultralight(event);
1118 case 4: /* exceptional */
1119 if (!s->oobinline) {
1121 * On a non-oobinline socket, this indicates that we
1122 * can immediately perform an OOB read and get back OOB
1123 * data, which we will send to the back end with
1124 * type==2 (urgent data).
1126 ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
1127 noise_ultralight(ret);
1129 return plug_closing(s->plug,
1130 ret == 0 ? "Internal networking trouble" :
1131 strerror(errno), errno, 0);
1134 * Receiving actual data on a socket means we can
1135 * stop falling back through the candidate
1136 * addresses to connect to.
1139 sk_addr_free(s->addr);
1142 return plug_receive(s->plug, 2, buf, ret);
1148 * If we reach here, this is an oobinline socket, which
1149 * means we should set s->oobpending and then deal with it
1150 * when we get called for the readability event (which
1151 * should also occur).
1153 s->oobpending = TRUE;
1155 case 1: /* readable; also acceptance */
1158 * On a listening socket, the readability event means a
1159 * connection is ready to be accepted.
1162 struct sockaddr_in ss;
1164 struct sockaddr_storage ss;
1166 socklen_t addrlen = sizeof(ss);
1167 int t; /* socket of connection */
1170 memset(&ss, 0, addrlen);
1171 t = accept(s->s, (struct sockaddr *)&ss, &addrlen);
1176 fl = fcntl(t, F_GETFL);
1178 fcntl(t, F_SETFL, fl | O_NONBLOCK);
1180 if (s->localhost_only &&
1181 !sockaddr_is_loopback((struct sockaddr *)&ss)) {
1182 close(t); /* someone let nonlocal through?! */
1183 } else if (plug_accepting(s->plug, t)) {
1184 close(t); /* denied or error */
1190 * If we reach here, this is not a listening socket, so
1191 * readability really means readability.
1194 /* In the case the socket is still frozen, we don't even bother */
1196 s->frozen_readable = 1;
1201 * We have received data on the socket. For an oobinline
1202 * socket, this might be data _before_ an urgent pointer,
1203 * in which case we send it to the back end with type==1
1204 * (data prior to urgent).
1206 if (s->oobinline && s->oobpending) {
1208 if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
1209 s->oobpending = FALSE; /* clear this indicator */
1213 ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
1214 noise_ultralight(ret);
1216 if (errno == EWOULDBLOCK) {
1222 * An error at this point _might_ be an error reported
1223 * by a non-blocking connect(). So before we return a
1224 * panic status to the user, let's just see whether
1229 plug_log(s->plug, 1, s->addr, s->port, strerror(err), err);
1230 while (s->addr && sk_nextaddr(s->addr, &s->step)) {
1231 err = try_connect(s);
1235 return plug_closing(s->plug, strerror(err), err, 0);
1236 } else if (0 == ret) {
1237 return plug_closing(s->plug, NULL, 0, 0);
1240 * Receiving actual data on a socket means we can
1241 * stop falling back through the candidate
1242 * addresses to connect to.
1245 sk_addr_free(s->addr);
1248 return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
1251 case 2: /* writable */
1252 if (!s->connected) {
1254 * select() reports a socket as _writable_ when an
1255 * asynchronous connection is completed.
1257 s->connected = s->writable = 1;
1261 int bufsize_before, bufsize_after;
1263 bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1265 bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1266 if (bufsize_after < bufsize_before)
1267 plug_sent(s->plug, bufsize_after);
1276 * Deal with socket errors detected in try_send().
1278 void net_pending_errors(void)
1284 * This might be a fiddly business, because it's just possible
1285 * that handling a pending error on one socket might cause
1286 * others to be closed. (I can't think of any reason this might
1287 * happen in current SSH implementation, but to maintain
1288 * generality of this network layer I'll assume the worst.)
1290 * So what we'll do is search the socket list for _one_ socket
1291 * with a pending error, and then handle it, and then search
1292 * the list again _from the beginning_. Repeat until we make a
1293 * pass with no socket errors present. That way we are
1294 * protected against the socket list changing under our feet.
1298 for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1299 if (s->pending_error) {
1301 * An error has occurred on this socket. Pass it to the
1304 plug_closing(s->plug, strerror(s->pending_error),
1305 s->pending_error, 0);
1313 * Each socket abstraction contains a `void *' private field in
1314 * which the client can keep state.
1316 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1318 Actual_Socket s = (Actual_Socket) sock;
1319 s->private_ptr = ptr;
1322 static void *sk_tcp_get_private_ptr(Socket sock)
1324 Actual_Socket s = (Actual_Socket) sock;
1325 return s->private_ptr;
1329 * Special error values are returned from sk_namelookup and sk_new
1330 * if there's a problem. These functions extract an error message,
1331 * or return NULL if there's no problem.
1333 const char *sk_addr_error(SockAddr addr)
1337 static const char *sk_tcp_socket_error(Socket sock)
1339 Actual_Socket s = (Actual_Socket) sock;
1343 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1345 Actual_Socket s = (Actual_Socket) sock;
1346 if (s->frozen == is_frozen)
1348 s->frozen = is_frozen;
1349 if (!is_frozen && s->frozen_readable) {
1351 recv(s->s, &c, 1, MSG_PEEK);
1353 s->frozen_readable = 0;
1357 static void uxsel_tell(Actual_Socket s)
1361 rwx |= 1; /* read == accept */
1364 rwx |= 2; /* write == connect */
1365 if (s->connected && !s->frozen)
1366 rwx |= 1 | 4; /* read, except */
1367 if (bufchain_size(&s->output_data))
1368 rwx |= 2; /* write */
1370 uxsel_set(s->s, rwx, net_select_result);
1373 int net_service_lookup(char *service)
1376 se = getservbyname(service, NULL);
1378 return ntohs(se->s_port);
1383 SockAddr platform_get_x11_unix_address(const char *display, int displaynum,
1384 char **canonicalname)
1386 SockAddr ret = snew(struct SockAddr_tag);
1389 memset(ret, 0, sizeof *ret);
1390 ret->superfamily = UNIX;
1392 * Mac OS X Leopard uses an innovative X display naming
1393 * convention in which the entire display name is the path to
1394 * the Unix socket, including the trailing :0 which only
1395 * _looks_ like a display number. Heuristically, I think
1396 * detecting this by means of a leading slash ought to be
1399 if (display[0] == '/') {
1400 n = snprintf(ret->hostname, sizeof ret->hostname,
1403 n = snprintf(ret->hostname, sizeof ret->hostname,
1404 "%s%d", X11_UNIX_PATH, displaynum);
1407 ret->error = "snprintf failed";
1408 else if(n >= sizeof ret->hostname)
1409 ret->error = "X11 UNIX name too long";
1411 *canonicalname = dupstr(ret->hostname);
1415 ret->addresses = NULL;
1416 ret->naddresses = 0;