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