]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
Rewrite of Unix sk_newlistener() which should fix any possible
[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     struct sockaddr_in6 a6;
579 #endif
580     struct sockaddr *addr;
581     int addrlen;
582     struct sockaddr_in a;
583     Actual_Socket ret;
584     int retcode;
585     int on = 1;
586
587     /*
588      * Create Socket structure.
589      */
590     ret = snew(struct Socket_tag);
591     ret->fn = &tcp_fn_table;
592     ret->error = NULL;
593     ret->plug = plug;
594     bufchain_init(&ret->output_data);
595     ret->writable = 0;                 /* to start with */
596     ret->sending_oob = 0;
597     ret->frozen = 0;
598     ret->frozen_readable = 0;
599     ret->localhost_only = local_host_only;
600     ret->pending_error = 0;
601     ret->oobpending = FALSE;
602     ret->listener = 1;
603
604     /*
605      * Translate address_family from platform-independent constants
606      * into local reality.
607      */
608     address_family = (address_family == ADDRTYPE_IPV4 ? AF_INET :
609                       address_family == ADDRTYPE_IPV6 ? AF_INET6 : AF_UNSPEC);
610
611 #ifndef NO_IPV6
612     /* Let's default to IPv6.
613      * If the stack doesn't support IPv6, we will fall back to IPv4. */
614     if (address_family == AF_UNSPEC) address_family = AF_INET6;
615 #else
616     /* No other choice, default to IPv4 */
617     if (address_family == AF_UNSPEC)  address_family = AF_INET;
618 #endif
619
620     /*
621      * Open socket.
622      */
623     s = socket(address_family, SOCK_STREAM, 0);
624
625     /* If the host doesn't support IPv6 try fallback to IPv4. */
626     if (s < 0 && address_family == AF_INET6) {
627         address_family = AF_INET;
628         s = socket(address_family, SOCK_STREAM, 0);
629     }
630
631     if (s < 0) {
632         ret->error = error_string(errno);
633         return (Socket) ret;
634     }
635
636     ret->oobinline = 0;
637
638     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
639
640     retcode = -1;
641     addr = NULL; addrlen = -1;         /* placate optimiser */
642
643     if (srcaddr != NULL) {
644 #ifndef NO_IPV6
645         hints.ai_flags = AI_NUMERICHOST;
646         hints.ai_family = address_family;
647         hints.ai_socktype = 0;
648         hints.ai_protocol = 0;
649         hints.ai_addrlen = 0;
650         hints.ai_addr = NULL;
651         hints.ai_canonname = NULL;
652         hints.ai_next = NULL;
653         sprintf(portstr, "%d", port);
654         retcode = getaddrinfo(srcaddr, portstr, &hints, &ai);
655         addr = ai->ai_addr;
656         addrlen = ai->ai_addrlen;
657 #else
658         memset(&a,'\0',sizeof(struct sockaddr_in));
659         a.sin_family = AF_INET;
660         a.sin_port = htons(port);
661         a.sin_addr.s_addr = inet_addr(srcaddr);
662         if (a.sin_addr.s_addr != (in_addr_t)(-1)) {
663             /* Override localhost_only with specified listen addr. */
664             ret->localhost_only = ipv4_is_loopback(a.sin_addr);
665             got_addr = 1;
666         }
667         addr = (struct sockaddr *)a;
668         addrlen = sizeof(a);
669         retcode = 0;
670 #endif
671     }
672
673     if (retcode != 0) {
674 #ifndef NO_IPV6
675         if (address_family == AF_INET6) {
676             memset(&a6,'\0',sizeof(struct sockaddr_in6));
677             a6.sin6_family = AF_INET6;
678             a6.sin6_port = htons(port);
679             if (local_host_only)
680                 a6.sin6_addr = in6addr_loopback;
681             else
682                 a6.sin6_addr = in6addr_any;
683             addr = (struct sockaddr *)&a6;
684             addrlen = sizeof(a6);
685         } else
686 #endif
687         {
688             memset(&a,'\0',sizeof(struct sockaddr_in));
689             a.sin_family = AF_INET;
690             a.sin_port = htons(port);
691             if (local_host_only)
692                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
693             else
694                 a.sin_addr.s_addr = htonl(INADDR_ANY);
695             addr = (struct sockaddr *)&a;
696             addrlen = sizeof(a);
697         }
698     }
699
700     retcode = bind(s, addr, addrlen);
701     if (retcode < 0) {
702         close(s);
703         ret->error = error_string(errno);
704         return (Socket) ret;
705     }
706
707
708     if (listen(s, SOMAXCONN) < 0) {
709         close(s);
710         ret->error = error_string(errno);
711         return (Socket) ret;
712     }
713
714     ret->s = s;
715
716     uxsel_tell(ret);
717     add234(sktree, ret);
718
719     return (Socket) ret;
720 }
721
722 static void sk_tcp_close(Socket sock)
723 {
724     Actual_Socket s = (Actual_Socket) sock;
725
726     uxsel_del(s->s);
727     del234(sktree, s);
728     close(s->s);
729     sfree(s);
730 }
731
732 int sk_getxdmdata(void *sock, unsigned long *ip, int *port)
733 {
734     Actual_Socket s = (Actual_Socket) sock;
735     struct sockaddr_in addr;
736     socklen_t addrlen;
737
738     /*
739      * We must check that this socket really _is_ an Actual_Socket.
740      */
741     if (s->fn != &tcp_fn_table)
742         return 0;                      /* failure */
743
744     addrlen = sizeof(addr);
745     if (getsockname(s->s, (struct sockaddr *)&addr, &addrlen) < 0)
746         return 0;
747     switch(addr.sin_family) {
748       case AF_INET:
749         *ip = ntohl(addr.sin_addr.s_addr);
750         *port = ntohs(addr.sin_port);
751         break;
752       case AF_UNIX:
753         /*
754          * For a Unix socket, we return 0xFFFFFFFF for the IP address and
755          * our current pid for the port. Bizarre, but such is life.
756          */
757         *ip = ntohl(0xFFFFFFFF);
758         *port = getpid();
759         break;
760
761         /* XXX IPV6 */
762
763       default:
764         return 0;
765     }
766
767     return 1;
768 }
769
770 /*
771  * The function which tries to send on a socket once it's deemed
772  * writable.
773  */
774 void try_send(Actual_Socket s)
775 {
776     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
777         int nsent;
778         int err;
779         void *data;
780         int len, urgentflag;
781
782         if (s->sending_oob) {
783             urgentflag = MSG_OOB;
784             len = s->sending_oob;
785             data = &s->oobdata;
786         } else {
787             urgentflag = 0;
788             bufchain_prefix(&s->output_data, &data, &len);
789         }
790         nsent = send(s->s, data, len, urgentflag);
791         noise_ultralight(nsent);
792         if (nsent <= 0) {
793             err = (nsent < 0 ? errno : 0);
794             if (err == EWOULDBLOCK) {
795                 /*
796                  * Perfectly normal: we've sent all we can for the moment.
797                  */
798                 s->writable = FALSE;
799                 return;
800             } else if (nsent == 0 ||
801                        err == ECONNABORTED || err == ECONNRESET) {
802                 /*
803                  * If send() returns CONNABORTED or CONNRESET, we
804                  * unfortunately can't just call plug_closing(),
805                  * because it's quite likely that we're currently
806                  * _in_ a call from the code we'd be calling back
807                  * to, so we'd have to make half the SSH code
808                  * reentrant. Instead we flag a pending error on
809                  * the socket, to be dealt with (by calling
810                  * plug_closing()) at some suitable future moment.
811                  */
812                 s->pending_error = err;
813                 return;
814             } else {
815                 /* We're inside the Unix frontend here, so we know
816                  * that the frontend handle is unnecessary. */
817                 logevent(NULL, error_string(err));
818                 fatalbox("%s", error_string(err));
819             }
820         } else {
821             if (s->sending_oob) {
822                 if (nsent < len) {
823                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
824                     s->sending_oob = len - nsent;
825                 } else {
826                     s->sending_oob = 0;
827                 }
828             } else {
829                 bufchain_consume(&s->output_data, nsent);
830             }
831         }
832     }
833     uxsel_tell(s);
834 }
835
836 static int sk_tcp_write(Socket sock, const char *buf, int len)
837 {
838     Actual_Socket s = (Actual_Socket) sock;
839
840     /*
841      * Add the data to the buffer list on the socket.
842      */
843     bufchain_add(&s->output_data, buf, len);
844
845     /*
846      * Now try sending from the start of the buffer list.
847      */
848     if (s->writable)
849         try_send(s);
850
851     /*
852      * Update the select() status to correctly reflect whether or
853      * not we should be selecting for write.
854      */
855     uxsel_tell(s);
856
857     return bufchain_size(&s->output_data);
858 }
859
860 static int sk_tcp_write_oob(Socket sock, const char *buf, int len)
861 {
862     Actual_Socket s = (Actual_Socket) sock;
863
864     /*
865      * Replace the buffer list on the socket with the data.
866      */
867     bufchain_clear(&s->output_data);
868     assert(len <= sizeof(s->oobdata));
869     memcpy(s->oobdata, buf, len);
870     s->sending_oob = len;
871
872     /*
873      * Now try sending from the start of the buffer list.
874      */
875     if (s->writable)
876         try_send(s);
877
878     /*
879      * Update the select() status to correctly reflect whether or
880      * not we should be selecting for write.
881      */
882     uxsel_tell(s);
883
884     return s->sending_oob;
885 }
886
887 static int net_select_result(int fd, int event)
888 {
889     int ret;
890     int err;
891     char buf[20480];                   /* nice big buffer for plenty of speed */
892     Actual_Socket s;
893     u_long atmark;
894
895     /* Find the Socket structure */
896     s = find234(sktree, &fd, cmpforsearch);
897     if (!s)
898         return 1;                      /* boggle */
899
900     noise_ultralight(event);
901
902     switch (event) {
903       case 4:                          /* exceptional */
904         if (!s->oobinline) {
905             /*
906              * On a non-oobinline socket, this indicates that we
907              * can immediately perform an OOB read and get back OOB
908              * data, which we will send to the back end with
909              * type==2 (urgent data).
910              */
911             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
912             noise_ultralight(ret);
913             if (ret <= 0) {
914                 const char *str = (ret == 0 ? "Internal networking trouble" :
915                                    error_string(errno));
916                 /* We're inside the Unix frontend here, so we know
917                  * that the frontend handle is unnecessary. */
918                 logevent(NULL, str);
919                 fatalbox("%s", str);
920             } else {
921                 return plug_receive(s->plug, 2, buf, ret);
922             }
923             break;
924         }
925
926         /*
927          * If we reach here, this is an oobinline socket, which
928          * means we should set s->oobpending and then deal with it
929          * when we get called for the readability event (which
930          * should also occur).
931          */
932         s->oobpending = TRUE;
933         break;
934       case 1:                          /* readable; also acceptance */
935         if (s->listener) {
936             /*
937              * On a listening socket, the readability event means a
938              * connection is ready to be accepted.
939              */
940             struct sockaddr_in isa;
941             int addrlen = sizeof(struct sockaddr_in);
942             int t;  /* socket of connection */
943
944             memset(&isa, 0, sizeof(struct sockaddr_in));
945             err = 0;
946             t = accept(s->s,(struct sockaddr *)&isa,(socklen_t *) &addrlen);
947             if (t < 0) {
948                 break;
949             }
950
951             if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
952                 close(t);              /* someone let nonlocal through?! */
953             } else if (plug_accepting(s->plug, t)) {
954                 close(t);              /* denied or error */
955             }
956             break;
957         }
958
959         /*
960          * If we reach here, this is not a listening socket, so
961          * readability really means readability.
962          */
963
964         /* In the case the socket is still frozen, we don't even bother */
965         if (s->frozen) {
966             s->frozen_readable = 1;
967             break;
968         }
969
970         /*
971          * We have received data on the socket. For an oobinline
972          * socket, this might be data _before_ an urgent pointer,
973          * in which case we send it to the back end with type==1
974          * (data prior to urgent).
975          */
976         if (s->oobinline && s->oobpending) {
977             atmark = 1;
978             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
979                 s->oobpending = FALSE; /* clear this indicator */
980         } else
981             atmark = 1;
982
983         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
984         noise_ultralight(ret);
985         if (ret < 0) {
986             if (errno == EWOULDBLOCK) {
987                 break;
988             }
989         }
990         if (ret < 0) {
991             return plug_closing(s->plug, error_string(errno), errno, 0);
992         } else if (0 == ret) {
993             return plug_closing(s->plug, NULL, 0, 0);
994         } else {
995             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
996         }
997         break;
998       case 2:                          /* writable */
999         if (!s->connected) {
1000             /*
1001              * select() reports a socket as _writable_ when an
1002              * asynchronous connection is completed.
1003              */
1004             s->connected = s->writable = 1;
1005             uxsel_tell(s);
1006             break;
1007         } else {
1008             int bufsize_before, bufsize_after;
1009             s->writable = 1;
1010             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
1011             try_send(s);
1012             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
1013             if (bufsize_after < bufsize_before)
1014                 plug_sent(s->plug, bufsize_after);
1015         }
1016         break;
1017     }
1018
1019     return 1;
1020 }
1021
1022 /*
1023  * Deal with socket errors detected in try_send().
1024  */
1025 void net_pending_errors(void)
1026 {
1027     int i;
1028     Actual_Socket s;
1029
1030     /*
1031      * This might be a fiddly business, because it's just possible
1032      * that handling a pending error on one socket might cause
1033      * others to be closed. (I can't think of any reason this might
1034      * happen in current SSH implementation, but to maintain
1035      * generality of this network layer I'll assume the worst.)
1036      * 
1037      * So what we'll do is search the socket list for _one_ socket
1038      * with a pending error, and then handle it, and then search
1039      * the list again _from the beginning_. Repeat until we make a
1040      * pass with no socket errors present. That way we are
1041      * protected against the socket list changing under our feet.
1042      */
1043
1044     do {
1045         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
1046             if (s->pending_error) {
1047                 /*
1048                  * An error has occurred on this socket. Pass it to the
1049                  * plug.
1050                  */
1051                 plug_closing(s->plug, error_string(s->pending_error),
1052                              s->pending_error, 0);
1053                 break;
1054             }
1055         }
1056     } while (s);
1057 }
1058
1059 /*
1060  * Each socket abstraction contains a `void *' private field in
1061  * which the client can keep state.
1062  */
1063 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
1064 {
1065     Actual_Socket s = (Actual_Socket) sock;
1066     s->private_ptr = ptr;
1067 }
1068
1069 static void *sk_tcp_get_private_ptr(Socket sock)
1070 {
1071     Actual_Socket s = (Actual_Socket) sock;
1072     return s->private_ptr;
1073 }
1074
1075 /*
1076  * Special error values are returned from sk_namelookup and sk_new
1077  * if there's a problem. These functions extract an error message,
1078  * or return NULL if there's no problem.
1079  */
1080 const char *sk_addr_error(SockAddr addr)
1081 {
1082     return addr->error;
1083 }
1084 static const char *sk_tcp_socket_error(Socket sock)
1085 {
1086     Actual_Socket s = (Actual_Socket) sock;
1087     return s->error;
1088 }
1089
1090 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
1091 {
1092     Actual_Socket s = (Actual_Socket) sock;
1093     if (s->frozen == is_frozen)
1094         return;
1095     s->frozen = is_frozen;
1096     if (!is_frozen && s->frozen_readable) {
1097         char c;
1098         recv(s->s, &c, 1, MSG_PEEK);
1099     }
1100     s->frozen_readable = 0;
1101     uxsel_tell(s);
1102 }
1103
1104 static void uxsel_tell(Actual_Socket s)
1105 {
1106     int rwx = 0;
1107     if (!s->connected)
1108         rwx |= 2;                      /* write == connect */
1109     if (s->connected && !s->frozen)
1110         rwx |= 1 | 4;                  /* read, except */
1111     if (bufchain_size(&s->output_data))
1112         rwx |= 2;                      /* write */
1113     if (s->listener)
1114         rwx |= 1;                      /* read == accept */
1115     uxsel_set(s->s, rwx, net_select_result);
1116 }
1117
1118 int net_service_lookup(char *service)
1119 {
1120     struct servent *se;
1121     se = getservbyname(service, NULL);
1122     if (se != NULL)
1123         return ntohs(se->s_port);
1124     else
1125         return 0;
1126 }
1127
1128 SockAddr platform_get_x11_unix_address(int displaynum, char **canonicalname)
1129 {
1130     SockAddr ret = snew(struct SockAddr_tag);
1131     int n;
1132
1133     memset(ret, 0, sizeof *ret);
1134     ret->family = AF_UNIX;
1135     n = snprintf(ret->hostname, sizeof ret->hostname,
1136                  "%s%d", X11_UNIX_PATH, displaynum);
1137     if(n < 0)
1138         ret->error = "snprintf failed";
1139     else if(n >= sizeof ret->hostname)
1140         ret->error = "X11 UNIX name too long";
1141     else
1142         *canonicalname = dupstr(ret->hostname);
1143     return ret;
1144 }