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