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