]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
Support for doing DNS at the proxy end. I've invented a new type of
[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->family = AF_UNSPEC;
207     strncpy(ret->hostname, host, lenof(ret->hostname));
208     ret->hostname[lenof(ret->hostname)-1] = '\0';
209     return ret;
210 }
211
212 void sk_getaddr(SockAddr addr, char *buf, int buflen)
213 {
214 #ifdef IPV6
215     if (addr->family == AF_INET6) {
216         FIXME; /* I don't know how to get a text form of an IPv6 address. */
217     } else
218 #endif
219     if (addr->family == AF_INET) {
220         struct in_addr a;
221         a.s_addr = htonl(addr->address);
222         strncpy(buf, inet_ntoa(a), buflen);
223         buf[buflen-1] = '\0';
224     } else {
225         assert(addr->family == AF_UNSPEC);
226         strncpy(buf, addr->hostname, buflen);
227         buf[buflen-1] = '\0';
228     }
229 }
230
231 int sk_hostname_is_local(char *name)
232 {
233     return !strcmp(name, "localhost");
234 }
235
236 int sk_address_is_local(SockAddr addr)
237 {
238 #ifdef IPV6
239     if (addr->family == AF_INET6) {
240         FIXME;  /* someone who can compile for IPV6 had better do this bit */
241     } else
242 #endif
243     if (addr->family == AF_INET) {
244         struct in_addr a;
245         a.s_addr = htonl(addr->address);
246         return ipv4_is_loopback(a);
247     } else {
248         assert(addr->family == AF_UNSPEC);
249         return 0;                      /* we don't know; assume not */
250     }
251 }
252
253 int sk_addrtype(SockAddr addr)
254 {
255     return (addr->family == AF_INET ? ADDRTYPE_IPV4 :
256 #ifdef IPV6
257             addr->family == AF_INET6 ? ADDRTYPE_IPV6 :
258 #endif
259             ADDRTYPE_NAME);
260 }
261
262 void sk_addrcopy(SockAddr addr, char *buf)
263 {
264     assert(addr->family != AF_UNSPEC);
265 #ifdef IPV6
266     if (addr->family == AF_INET6) {
267         memcpy(buf, (char*) addr->ai, 16);
268     } else
269 #endif
270     if (addr->family == AF_INET) {
271         struct in_addr a;
272         a.s_addr = htonl(addr->address);
273         memcpy(buf, (char*) &a.s_addr, 4);
274     }
275 }
276
277 void sk_addr_free(SockAddr addr)
278 {
279     sfree(addr);
280 }
281
282 static Plug sk_tcp_plug(Socket sock, Plug p)
283 {
284     Actual_Socket s = (Actual_Socket) sock;
285     Plug ret = s->plug;
286     if (p)
287         s->plug = p;
288     return ret;
289 }
290
291 static void sk_tcp_flush(Socket s)
292 {
293     /*
294      * We send data to the socket as soon as we can anyway,
295      * so we don't need to do anything here.  :-)
296      */
297 }
298
299 static void sk_tcp_close(Socket s);
300 static int sk_tcp_write(Socket s, char *data, int len);
301 static int sk_tcp_write_oob(Socket s, char *data, int len);
302 static void sk_tcp_set_private_ptr(Socket s, void *ptr);
303 static void *sk_tcp_get_private_ptr(Socket s);
304 static void sk_tcp_set_frozen(Socket s, int is_frozen);
305 static char *sk_tcp_socket_error(Socket s);
306
307 Socket sk_register(void *sock, Plug plug)
308 {
309     static struct socket_function_table fn_table = {
310         sk_tcp_plug,
311         sk_tcp_close,
312         sk_tcp_write,
313         sk_tcp_write_oob,
314         sk_tcp_flush,
315         sk_tcp_set_private_ptr,
316         sk_tcp_get_private_ptr,
317         sk_tcp_set_frozen,
318         sk_tcp_socket_error
319     };
320
321     Actual_Socket ret;
322
323     /*
324      * Create Socket structure.
325      */
326     ret = smalloc(sizeof(struct Socket_tag));
327     ret->fn = &fn_table;
328     ret->error = NULL;
329     ret->plug = plug;
330     bufchain_init(&ret->output_data);
331     ret->writable = 1;                 /* to start with */
332     ret->sending_oob = 0;
333     ret->frozen = 1;
334     ret->frozen_readable = 0;
335     ret->localhost_only = 0;           /* unused, but best init anyway */
336     ret->pending_error = 0;
337     ret->oobpending = FALSE;
338     ret->listener = 0;
339
340     ret->s = (int)sock;
341
342     if (ret->s < 0) {
343         ret->error = error_string(errno);
344         return (Socket) ret;
345     }
346
347     ret->oobinline = 0;
348
349     add234(sktree, ret);
350
351     return (Socket) ret;
352 }
353
354 Socket sk_new(SockAddr addr, int port, int privport, int oobinline,
355               int nodelay, Plug plug)
356 {
357     static struct socket_function_table fn_table = {
358         sk_tcp_plug,
359         sk_tcp_close,
360         sk_tcp_write,
361         sk_tcp_write_oob,
362         sk_tcp_flush,
363         sk_tcp_set_private_ptr,
364         sk_tcp_get_private_ptr,
365         sk_tcp_set_frozen,
366         sk_tcp_socket_error
367     };
368
369     int s;
370 #ifdef IPV6
371     struct sockaddr_in6 a6;
372 #endif
373     struct sockaddr_in a;
374     int err;
375     Actual_Socket ret;
376     short localport;
377
378     /*
379      * Create Socket structure.
380      */
381     ret = smalloc(sizeof(struct Socket_tag));
382     ret->fn = &fn_table;
383     ret->error = NULL;
384     ret->plug = plug;
385     bufchain_init(&ret->output_data);
386     ret->connected = 0;                /* to start with */
387     ret->writable = 0;                 /* to start with */
388     ret->sending_oob = 0;
389     ret->frozen = 0;
390     ret->frozen_readable = 0;
391     ret->localhost_only = 0;           /* unused, but best init anyway */
392     ret->pending_error = 0;
393     ret->oobpending = FALSE;
394     ret->listener = 0;
395
396     /*
397      * Open socket.
398      */
399     assert(addr->family != AF_UNSPEC);
400     s = socket(addr->family, SOCK_STREAM, 0);
401     ret->s = s;
402
403     if (s < 0) {
404         ret->error = error_string(errno);
405         return (Socket) ret;
406     }
407
408     ret->oobinline = oobinline;
409     if (oobinline) {
410         int b = TRUE;
411         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
412     }
413
414     if (nodelay) {
415         int b = TRUE;
416         setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
417     }
418
419     /*
420      * Bind to local address.
421      */
422     if (privport)
423         localport = 1023;              /* count from 1023 downwards */
424     else
425         localport = 0;                 /* just use port 0 (ie kernel picks) */
426
427     /* Loop round trying to bind */
428     while (1) {
429         int retcode;
430
431 #ifdef IPV6
432         if (addr->family == AF_INET6) {
433             memset(&a6, 0, sizeof(a6));
434             a6.sin6_family = AF_INET6;
435 /*a6.sin6_addr      = in6addr_any; *//* == 0 */
436             a6.sin6_port = htons(localport);
437         } else
438 #endif
439         {
440             a.sin_family = AF_INET;
441             a.sin_addr.s_addr = htonl(INADDR_ANY);
442             a.sin_port = htons(localport);
443         }
444 #ifdef IPV6
445         retcode = bind(s, (addr->family == AF_INET6 ?
446                            (struct sockaddr *) &a6 :
447                            (struct sockaddr *) &a),
448                        (addr->family ==
449                         AF_INET6 ? sizeof(a6) : sizeof(a)));
450 #else
451         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
452 #endif
453         if (retcode >= 0) {
454             err = 0;
455             break;                     /* done */
456         } else {
457             err = errno;
458             if (err != EADDRINUSE)     /* failed, for a bad reason */
459                 break;
460         }
461
462         if (localport == 0)
463             break;                     /* we're only looping once */
464         localport--;
465         if (localport == 0)
466             break;                     /* we might have got to the end */
467     }
468
469     if (err) {
470         ret->error = error_string(err);
471         return (Socket) ret;
472     }
473
474     /*
475      * Connect to remote address.
476      */
477 #ifdef IPV6
478     if (addr->family == AF_INET6) {
479         memset(&a, 0, sizeof(a));
480         a6.sin6_family = AF_INET6;
481         a6.sin6_port = htons((short) port);
482         a6.sin6_addr =
483             ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
484     } else
485 #endif
486     {
487         a.sin_family = AF_INET;
488         a.sin_addr.s_addr = htonl(addr->address);
489         a.sin_port = htons((short) port);
490     }
491
492     if ((
493 #ifdef IPV6
494             connect(s, ((addr->family == AF_INET6) ?
495                         (struct sockaddr *) &a6 : (struct sockaddr *) &a),
496                     (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
497 #else
498             connect(s, (struct sockaddr *) &a, sizeof(a))
499 #endif
500         ) < 0) {
501         /*
502          * FIXME: We are prepared to receive EWOULDBLOCK here,
503          * because we might want the connection to be made
504          * asynchronously; but how do we actually arrange this in
505          * Unix? I forget.
506          */
507         if ( errno != EWOULDBLOCK ) {
508             ret->error = error_string(errno);
509             return (Socket) ret;
510         }
511     } else {
512         /*
513          * If we _don't_ get EWOULDBLOCK, the connect has completed
514          * and we should set the socket as connected and writable.
515          */
516         ret->connected = 1;
517         ret->writable = 1;
518     }
519
520     add234(sktree, ret);
521
522     return (Socket) ret;
523 }
524
525 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
526 {
527     static struct socket_function_table fn_table = {
528         sk_tcp_plug,
529         sk_tcp_close,
530         sk_tcp_write,
531         sk_tcp_write_oob,
532         sk_tcp_flush,
533         sk_tcp_set_private_ptr,
534         sk_tcp_get_private_ptr,
535         sk_tcp_set_frozen,
536         sk_tcp_socket_error
537     };
538
539     int s;
540 #ifdef IPV6
541     struct sockaddr_in6 a6;
542 #endif
543     struct sockaddr_in a;
544     int err;
545     Actual_Socket ret;
546     int retcode;
547     int on = 1;
548
549     /*
550      * Create Socket structure.
551      */
552     ret = smalloc(sizeof(struct Socket_tag));
553     ret->fn = &fn_table;
554     ret->error = NULL;
555     ret->plug = plug;
556     bufchain_init(&ret->output_data);
557     ret->writable = 0;                 /* to start with */
558     ret->sending_oob = 0;
559     ret->frozen = 0;
560     ret->frozen_readable = 0;
561     ret->localhost_only = local_host_only;
562     ret->pending_error = 0;
563     ret->oobpending = FALSE;
564     ret->listener = 1;
565
566     /*
567      * Open socket.
568      */
569     s = socket(AF_INET, SOCK_STREAM, 0);
570     ret->s = s;
571
572     if (s < 0) {
573         ret->error = error_string(errno);
574         return (Socket) ret;
575     }
576
577     ret->oobinline = 0;
578
579     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
580
581 #ifdef IPV6
582     if (addr->family == AF_INET6) {
583         memset(&a6, 0, sizeof(a6));
584         a6.sin6_family = AF_INET6;
585         /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
586          * know how to do it. :-) */
587         if (local_host_only)
588             a6.sin6_addr = in6addr_loopback;
589         else
590             a6.sin6_addr = in6addr_any;
591         a6.sin6_port = htons(port);
592     } else
593 #endif
594     {
595         int got_addr = 0;
596         a.sin_family = AF_INET;
597
598         /*
599          * Bind to source address. First try an explicitly
600          * specified one...
601          */
602         if (srcaddr) {
603             a.sin_addr.s_addr = inet_addr(srcaddr);
604             if (a.sin_addr.s_addr != INADDR_NONE) {
605                 /* Override localhost_only with specified listen addr. */
606                 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
607                 got_addr = 1;
608             }
609         }
610
611         /*
612          * ... and failing that, go with one of the standard ones.
613          */
614         if (!got_addr) {
615             if (local_host_only)
616                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
617             else
618                 a.sin_addr.s_addr = htonl(INADDR_ANY);
619         }
620
621         a.sin_port = htons((short)port);
622     }
623 #ifdef IPV6
624     retcode = bind(s, (addr->family == AF_INET6 ?
625                        (struct sockaddr *) &a6 :
626                        (struct sockaddr *) &a),
627                    (addr->family ==
628                     AF_INET6 ? sizeof(a6) : sizeof(a)));
629 #else
630     retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
631 #endif
632     if (retcode >= 0) {
633         err = 0;
634     } else {
635         err = errno;
636     }
637
638     if (err) {
639         ret->error = error_string(err);
640         return (Socket) ret;
641     }
642
643
644     if (listen(s, SOMAXCONN) < 0) {
645         close(s);
646         ret->error = error_string(errno);
647         return (Socket) ret;
648     }
649
650     add234(sktree, ret);
651
652     return (Socket) ret;
653 }
654
655 static void sk_tcp_close(Socket sock)
656 {
657     Actual_Socket s = (Actual_Socket) sock;
658
659     del234(sktree, s);
660     close(s->s);
661     sfree(s);
662 }
663
664 /*
665  * The function which tries to send on a socket once it's deemed
666  * writable.
667  */
668 void try_send(Actual_Socket s)
669 {
670     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
671         int nsent;
672         int err;
673         void *data;
674         int len, urgentflag;
675
676         if (s->sending_oob) {
677             urgentflag = MSG_OOB;
678             len = s->sending_oob;
679             data = &s->oobdata;
680         } else {
681             urgentflag = 0;
682             bufchain_prefix(&s->output_data, &data, &len);
683         }
684         nsent = send(s->s, data, len, urgentflag);
685         noise_ultralight(nsent);
686         if (nsent <= 0) {
687             err = (nsent < 0 ? errno : 0);
688             if (err == EWOULDBLOCK) {
689                 /*
690                  * Perfectly normal: we've sent all we can for the moment.
691                  */
692                 s->writable = FALSE;
693                 return;
694             } else if (nsent == 0 ||
695                        err == ECONNABORTED || err == ECONNRESET) {
696                 /*
697                  * If send() returns CONNABORTED or CONNRESET, we
698                  * unfortunately can't just call plug_closing(),
699                  * because it's quite likely that we're currently
700                  * _in_ a call from the code we'd be calling back
701                  * to, so we'd have to make half the SSH code
702                  * reentrant. Instead we flag a pending error on
703                  * the socket, to be dealt with (by calling
704                  * plug_closing()) at some suitable future moment.
705                  */
706                 s->pending_error = err;
707                 return;
708             } else {
709                 /* We're inside the Unix frontend here, so we know
710                  * that the frontend handle is unnecessary. */
711                 logevent(NULL, error_string(err));
712                 fatalbox("%s", error_string(err));
713             }
714         } else {
715             if (s->sending_oob) {
716                 if (nsent < len) {
717                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
718                     s->sending_oob = len - nsent;
719                 } else {
720                     s->sending_oob = 0;
721                 }
722             } else {
723                 bufchain_consume(&s->output_data, nsent);
724             }
725         }
726     }
727 }
728
729 static int sk_tcp_write(Socket sock, char *buf, int len)
730 {
731     Actual_Socket s = (Actual_Socket) sock;
732
733     /*
734      * Add the data to the buffer list on the socket.
735      */
736     bufchain_add(&s->output_data, buf, len);
737
738     /*
739      * Now try sending from the start of the buffer list.
740      */
741     if (s->writable)
742         try_send(s);
743
744     return bufchain_size(&s->output_data);
745 }
746
747 static int sk_tcp_write_oob(Socket sock, char *buf, int len)
748 {
749     Actual_Socket s = (Actual_Socket) sock;
750
751     /*
752      * Replace the buffer list on the socket with the data.
753      */
754     bufchain_clear(&s->output_data);
755     assert(len <= sizeof(s->oobdata));
756     memcpy(s->oobdata, buf, len);
757     s->sending_oob = len;
758
759     /*
760      * Now try sending from the start of the buffer list.
761      */
762     if (s->writable)
763         try_send(s);
764
765     return s->sending_oob;
766 }
767
768 int select_result(int fd, int event)
769 {
770     int ret;
771     int err;
772     char buf[20480];                   /* nice big buffer for plenty of speed */
773     Actual_Socket s;
774     u_long atmark;
775
776     /* Find the Socket structure */
777     s = find234(sktree, (void *) fd, cmpforsearch);
778     if (!s)
779         return 1;                      /* boggle */
780
781     noise_ultralight(event);
782
783     switch (event) {
784 #ifdef FIXME_NONBLOCKING_CONNECTIONS
785       case FIXME:                      /* connected */
786         s->connected = s->writable = 1;
787         break;
788 #endif
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         {
886             int bufsize_before, bufsize_after;
887             s->writable = 1;
888             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
889             try_send(s);
890             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
891             if (bufsize_after < bufsize_before)
892                 plug_sent(s->plug, bufsize_after);
893         }
894         break;
895     }
896
897     return 1;
898 }
899
900 /*
901  * Deal with socket errors detected in try_send().
902  */
903 void net_pending_errors(void)
904 {
905     int i;
906     Actual_Socket s;
907
908     /*
909      * This might be a fiddly business, because it's just possible
910      * that handling a pending error on one socket might cause
911      * others to be closed. (I can't think of any reason this might
912      * happen in current SSH implementation, but to maintain
913      * generality of this network layer I'll assume the worst.)
914      * 
915      * So what we'll do is search the socket list for _one_ socket
916      * with a pending error, and then handle it, and then search
917      * the list again _from the beginning_. Repeat until we make a
918      * pass with no socket errors present. That way we are
919      * protected against the socket list changing under our feet.
920      */
921
922     do {
923         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
924             if (s->pending_error) {
925                 /*
926                  * An error has occurred on this socket. Pass it to the
927                  * plug.
928                  */
929                 plug_closing(s->plug, error_string(s->pending_error),
930                              s->pending_error, 0);
931                 break;
932             }
933         }
934     } while (s);
935 }
936
937 /*
938  * Each socket abstraction contains a `void *' private field in
939  * which the client can keep state.
940  */
941 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
942 {
943     Actual_Socket s = (Actual_Socket) sock;
944     s->private_ptr = ptr;
945 }
946
947 static void *sk_tcp_get_private_ptr(Socket sock)
948 {
949     Actual_Socket s = (Actual_Socket) sock;
950     return s->private_ptr;
951 }
952
953 /*
954  * Special error values are returned from sk_namelookup and sk_new
955  * if there's a problem. These functions extract an error message,
956  * or return NULL if there's no problem.
957  */
958 char *sk_addr_error(SockAddr addr)
959 {
960     return addr->error;
961 }
962 static char *sk_tcp_socket_error(Socket sock)
963 {
964     Actual_Socket s = (Actual_Socket) sock;
965     return s->error;
966 }
967
968 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
969 {
970     Actual_Socket s = (Actual_Socket) sock;
971     if (s->frozen == is_frozen)
972         return;
973     s->frozen = is_frozen;
974     if (!is_frozen && s->frozen_readable) {
975         char c;
976         recv(s->s, &c, 1, MSG_PEEK);
977     }
978     s->frozen_readable = 0;
979 }
980
981 /*
982  * For Unix select()-based frontends: enumerate all sockets
983  * currently active, and state whether we currently wish to receive
984  * select events on them for reading, writing and exceptional
985  * status.
986  */
987 static void set_rwx(Actual_Socket s, int *rwx)
988 {
989     int val = 0;
990     if (s->connected && !s->frozen)
991         val |= 1 | 4;                  /* read, except */
992     if (bufchain_size(&s->output_data))
993         val |= 2;                      /* write */
994     if (s->listener)
995         val |= 1;                      /* read == accept */
996     *rwx = val;
997 }
998
999 int first_socket(int *state, int *rwx)
1000 {
1001     Actual_Socket s;
1002     *state = 0;
1003     s = index234(sktree, (*state)++);
1004     if (s)
1005         set_rwx(s, rwx);
1006     return s ? s->s : -1;
1007 }
1008
1009 int next_socket(int *state, int *rwx)
1010 {
1011     Actual_Socket s = index234(sktree, (*state)++);
1012     if (s)
1013         set_rwx(s, rwx);
1014     return s ? s->s : -1;
1015 }
1016
1017 int net_service_lookup(char *service)
1018 {
1019     struct servent *se;
1020     se = getservbyname(service, NULL);
1021     if (se != NULL)
1022         return ntohs(se->s_port);
1023     else
1024         return 0;
1025 }