]> asedeno.scripts.mit.edu Git - PuTTY.git/blob - unix/uxnet.c
sk_nonamelookup() should ensure the sockaddr it returns has `error'
[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, char *data, int len);
302 static int sk_tcp_write_oob(Socket s, 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 Socket sk_register(void *sock, Plug plug)
309 {
310     static struct socket_function_table fn_table = {
311         sk_tcp_plug,
312         sk_tcp_close,
313         sk_tcp_write,
314         sk_tcp_write_oob,
315         sk_tcp_flush,
316         sk_tcp_set_private_ptr,
317         sk_tcp_get_private_ptr,
318         sk_tcp_set_frozen,
319         sk_tcp_socket_error
320     };
321
322     Actual_Socket ret;
323
324     /*
325      * Create Socket structure.
326      */
327     ret = smalloc(sizeof(struct Socket_tag));
328     ret->fn = &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     static struct socket_function_table fn_table = {
359         sk_tcp_plug,
360         sk_tcp_close,
361         sk_tcp_write,
362         sk_tcp_write_oob,
363         sk_tcp_flush,
364         sk_tcp_set_private_ptr,
365         sk_tcp_get_private_ptr,
366         sk_tcp_set_frozen,
367         sk_tcp_socket_error
368     };
369
370     int s;
371 #ifdef IPV6
372     struct sockaddr_in6 a6;
373 #endif
374     struct sockaddr_in a;
375     int err;
376     Actual_Socket ret;
377     short localport;
378
379     /*
380      * Create Socket structure.
381      */
382     ret = smalloc(sizeof(struct Socket_tag));
383     ret->fn = &fn_table;
384     ret->error = NULL;
385     ret->plug = plug;
386     bufchain_init(&ret->output_data);
387     ret->connected = 0;                /* to start with */
388     ret->writable = 0;                 /* to start with */
389     ret->sending_oob = 0;
390     ret->frozen = 0;
391     ret->frozen_readable = 0;
392     ret->localhost_only = 0;           /* unused, but best init anyway */
393     ret->pending_error = 0;
394     ret->oobpending = FALSE;
395     ret->listener = 0;
396
397     /*
398      * Open socket.
399      */
400     assert(addr->family != AF_UNSPEC);
401     s = socket(addr->family, SOCK_STREAM, 0);
402     ret->s = s;
403
404     if (s < 0) {
405         ret->error = error_string(errno);
406         return (Socket) ret;
407     }
408
409     ret->oobinline = oobinline;
410     if (oobinline) {
411         int b = TRUE;
412         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, (void *) &b, sizeof(b));
413     }
414
415     if (nodelay) {
416         int b = TRUE;
417         setsockopt(s, IPPROTO_TCP, TCP_NODELAY, (void *) &b, sizeof(b));
418     }
419
420     /*
421      * Bind to local address.
422      */
423     if (privport)
424         localport = 1023;              /* count from 1023 downwards */
425     else
426         localport = 0;                 /* just use port 0 (ie kernel picks) */
427
428     /* Loop round trying to bind */
429     while (1) {
430         int retcode;
431
432 #ifdef IPV6
433         if (addr->family == AF_INET6) {
434             memset(&a6, 0, sizeof(a6));
435             a6.sin6_family = AF_INET6;
436 /*a6.sin6_addr      = in6addr_any; *//* == 0 */
437             a6.sin6_port = htons(localport);
438         } else
439 #endif
440         {
441             a.sin_family = AF_INET;
442             a.sin_addr.s_addr = htonl(INADDR_ANY);
443             a.sin_port = htons(localport);
444         }
445 #ifdef IPV6
446         retcode = bind(s, (addr->family == AF_INET6 ?
447                            (struct sockaddr *) &a6 :
448                            (struct sockaddr *) &a),
449                        (addr->family ==
450                         AF_INET6 ? sizeof(a6) : sizeof(a)));
451 #else
452         retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
453 #endif
454         if (retcode >= 0) {
455             err = 0;
456             break;                     /* done */
457         } else {
458             err = errno;
459             if (err != EADDRINUSE)     /* failed, for a bad reason */
460                 break;
461         }
462
463         if (localport == 0)
464             break;                     /* we're only looping once */
465         localport--;
466         if (localport == 0)
467             break;                     /* we might have got to the end */
468     }
469
470     if (err) {
471         ret->error = error_string(err);
472         return (Socket) ret;
473     }
474
475     /*
476      * Connect to remote address.
477      */
478 #ifdef IPV6
479     if (addr->family == AF_INET6) {
480         memset(&a, 0, sizeof(a));
481         a6.sin6_family = AF_INET6;
482         a6.sin6_port = htons((short) port);
483         a6.sin6_addr =
484             ((struct sockaddr_in6 *) addr->ai->ai_addr)->sin6_addr;
485     } else
486 #endif
487     {
488         a.sin_family = AF_INET;
489         a.sin_addr.s_addr = htonl(addr->address);
490         a.sin_port = htons((short) port);
491     }
492
493     if ((
494 #ifdef IPV6
495             connect(s, ((addr->family == AF_INET6) ?
496                         (struct sockaddr *) &a6 : (struct sockaddr *) &a),
497                     (addr->family == AF_INET6) ? sizeof(a6) : sizeof(a))
498 #else
499             connect(s, (struct sockaddr *) &a, sizeof(a))
500 #endif
501         ) < 0) {
502         /*
503          * FIXME: We are prepared to receive EWOULDBLOCK here,
504          * because we might want the connection to be made
505          * asynchronously; but how do we actually arrange this in
506          * Unix? I forget.
507          */
508         if ( errno != EWOULDBLOCK ) {
509             ret->error = error_string(errno);
510             return (Socket) ret;
511         }
512     } else {
513         /*
514          * If we _don't_ get EWOULDBLOCK, the connect has completed
515          * and we should set the socket as connected and writable.
516          */
517         ret->connected = 1;
518         ret->writable = 1;
519     }
520
521     add234(sktree, ret);
522
523     return (Socket) ret;
524 }
525
526 Socket sk_newlistener(char *srcaddr, int port, Plug plug, int local_host_only)
527 {
528     static struct socket_function_table fn_table = {
529         sk_tcp_plug,
530         sk_tcp_close,
531         sk_tcp_write,
532         sk_tcp_write_oob,
533         sk_tcp_flush,
534         sk_tcp_set_private_ptr,
535         sk_tcp_get_private_ptr,
536         sk_tcp_set_frozen,
537         sk_tcp_socket_error
538     };
539
540     int s;
541 #ifdef IPV6
542     struct sockaddr_in6 a6;
543 #endif
544     struct sockaddr_in a;
545     int err;
546     Actual_Socket ret;
547     int retcode;
548     int on = 1;
549
550     /*
551      * Create Socket structure.
552      */
553     ret = smalloc(sizeof(struct Socket_tag));
554     ret->fn = &fn_table;
555     ret->error = NULL;
556     ret->plug = plug;
557     bufchain_init(&ret->output_data);
558     ret->writable = 0;                 /* to start with */
559     ret->sending_oob = 0;
560     ret->frozen = 0;
561     ret->frozen_readable = 0;
562     ret->localhost_only = local_host_only;
563     ret->pending_error = 0;
564     ret->oobpending = FALSE;
565     ret->listener = 1;
566
567     /*
568      * Open socket.
569      */
570     s = socket(AF_INET, SOCK_STREAM, 0);
571     ret->s = s;
572
573     if (s < 0) {
574         ret->error = error_string(errno);
575         return (Socket) ret;
576     }
577
578     ret->oobinline = 0;
579
580     setsockopt(s, SOL_SOCKET, SO_REUSEADDR, (const char *)&on, sizeof(on));
581
582 #ifdef IPV6
583     if (addr->family == AF_INET6) {
584         memset(&a6, 0, sizeof(a6));
585         a6.sin6_family = AF_INET6;
586         /* FIXME: srcaddr is ignored for IPv6, because I (SGT) don't
587          * know how to do it. :-) */
588         if (local_host_only)
589             a6.sin6_addr = in6addr_loopback;
590         else
591             a6.sin6_addr = in6addr_any;
592         a6.sin6_port = htons(port);
593     } else
594 #endif
595     {
596         int got_addr = 0;
597         a.sin_family = AF_INET;
598
599         /*
600          * Bind to source address. First try an explicitly
601          * specified one...
602          */
603         if (srcaddr) {
604             a.sin_addr.s_addr = inet_addr(srcaddr);
605             if (a.sin_addr.s_addr != INADDR_NONE) {
606                 /* Override localhost_only with specified listen addr. */
607                 ret->localhost_only = ipv4_is_loopback(a.sin_addr);
608                 got_addr = 1;
609             }
610         }
611
612         /*
613          * ... and failing that, go with one of the standard ones.
614          */
615         if (!got_addr) {
616             if (local_host_only)
617                 a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
618             else
619                 a.sin_addr.s_addr = htonl(INADDR_ANY);
620         }
621
622         a.sin_port = htons((short)port);
623     }
624 #ifdef IPV6
625     retcode = bind(s, (addr->family == AF_INET6 ?
626                        (struct sockaddr *) &a6 :
627                        (struct sockaddr *) &a),
628                    (addr->family ==
629                     AF_INET6 ? sizeof(a6) : sizeof(a)));
630 #else
631     retcode = bind(s, (struct sockaddr *) &a, sizeof(a));
632 #endif
633     if (retcode >= 0) {
634         err = 0;
635     } else {
636         err = errno;
637     }
638
639     if (err) {
640         ret->error = error_string(err);
641         return (Socket) ret;
642     }
643
644
645     if (listen(s, SOMAXCONN) < 0) {
646         close(s);
647         ret->error = error_string(errno);
648         return (Socket) ret;
649     }
650
651     add234(sktree, ret);
652
653     return (Socket) ret;
654 }
655
656 static void sk_tcp_close(Socket sock)
657 {
658     Actual_Socket s = (Actual_Socket) sock;
659
660     del234(sktree, s);
661     close(s->s);
662     sfree(s);
663 }
664
665 /*
666  * The function which tries to send on a socket once it's deemed
667  * writable.
668  */
669 void try_send(Actual_Socket s)
670 {
671     while (s->sending_oob || bufchain_size(&s->output_data) > 0) {
672         int nsent;
673         int err;
674         void *data;
675         int len, urgentflag;
676
677         if (s->sending_oob) {
678             urgentflag = MSG_OOB;
679             len = s->sending_oob;
680             data = &s->oobdata;
681         } else {
682             urgentflag = 0;
683             bufchain_prefix(&s->output_data, &data, &len);
684         }
685         nsent = send(s->s, data, len, urgentflag);
686         noise_ultralight(nsent);
687         if (nsent <= 0) {
688             err = (nsent < 0 ? errno : 0);
689             if (err == EWOULDBLOCK) {
690                 /*
691                  * Perfectly normal: we've sent all we can for the moment.
692                  */
693                 s->writable = FALSE;
694                 return;
695             } else if (nsent == 0 ||
696                        err == ECONNABORTED || err == ECONNRESET) {
697                 /*
698                  * If send() returns CONNABORTED or CONNRESET, we
699                  * unfortunately can't just call plug_closing(),
700                  * because it's quite likely that we're currently
701                  * _in_ a call from the code we'd be calling back
702                  * to, so we'd have to make half the SSH code
703                  * reentrant. Instead we flag a pending error on
704                  * the socket, to be dealt with (by calling
705                  * plug_closing()) at some suitable future moment.
706                  */
707                 s->pending_error = err;
708                 return;
709             } else {
710                 /* We're inside the Unix frontend here, so we know
711                  * that the frontend handle is unnecessary. */
712                 logevent(NULL, error_string(err));
713                 fatalbox("%s", error_string(err));
714             }
715         } else {
716             if (s->sending_oob) {
717                 if (nsent < len) {
718                     memmove(s->oobdata, s->oobdata+nsent, len-nsent);
719                     s->sending_oob = len - nsent;
720                 } else {
721                     s->sending_oob = 0;
722                 }
723             } else {
724                 bufchain_consume(&s->output_data, nsent);
725             }
726         }
727     }
728 }
729
730 static int sk_tcp_write(Socket sock, char *buf, int len)
731 {
732     Actual_Socket s = (Actual_Socket) sock;
733
734     /*
735      * Add the data to the buffer list on the socket.
736      */
737     bufchain_add(&s->output_data, buf, len);
738
739     /*
740      * Now try sending from the start of the buffer list.
741      */
742     if (s->writable)
743         try_send(s);
744
745     return bufchain_size(&s->output_data);
746 }
747
748 static int sk_tcp_write_oob(Socket sock, char *buf, int len)
749 {
750     Actual_Socket s = (Actual_Socket) sock;
751
752     /*
753      * Replace the buffer list on the socket with the data.
754      */
755     bufchain_clear(&s->output_data);
756     assert(len <= sizeof(s->oobdata));
757     memcpy(s->oobdata, buf, len);
758     s->sending_oob = len;
759
760     /*
761      * Now try sending from the start of the buffer list.
762      */
763     if (s->writable)
764         try_send(s);
765
766     return s->sending_oob;
767 }
768
769 int select_result(int fd, int event)
770 {
771     int ret;
772     int err;
773     char buf[20480];                   /* nice big buffer for plenty of speed */
774     Actual_Socket s;
775     u_long atmark;
776
777     /* Find the Socket structure */
778     s = find234(sktree, (void *) fd, cmpforsearch);
779     if (!s)
780         return 1;                      /* boggle */
781
782     noise_ultralight(event);
783
784     switch (event) {
785 #ifdef FIXME_NONBLOCKING_CONNECTIONS
786       case FIXME:                      /* connected */
787         s->connected = s->writable = 1;
788         break;
789 #endif
790       case 4:                          /* exceptional */
791         if (!s->oobinline) {
792             /*
793              * On a non-oobinline socket, this indicates that we
794              * can immediately perform an OOB read and get back OOB
795              * data, which we will send to the back end with
796              * type==2 (urgent data).
797              */
798             ret = recv(s->s, buf, sizeof(buf), MSG_OOB);
799             noise_ultralight(ret);
800             if (ret <= 0) {
801                 char *str = (ret == 0 ? "Internal networking trouble" :
802                              error_string(errno));
803                 /* We're inside the Unix frontend here, so we know
804                  * that the frontend handle is unnecessary. */
805                 logevent(NULL, str);
806                 fatalbox("%s", str);
807             } else {
808                 return plug_receive(s->plug, 2, buf, ret);
809             }
810             break;
811         }
812
813         /*
814          * If we reach here, this is an oobinline socket, which
815          * means we should set s->oobpending and then deal with it
816          * when we get called for the readability event (which
817          * should also occur).
818          */
819         s->oobpending = TRUE;
820         break;
821       case 1:                          /* readable; also acceptance */
822         if (s->listener) {
823             /*
824              * On a listening socket, the readability event means a
825              * connection is ready to be accepted.
826              */
827             struct sockaddr_in isa;
828             int addrlen = sizeof(struct sockaddr_in);
829             int t;  /* socket of connection */
830
831             memset(&isa, 0, sizeof(struct sockaddr_in));
832             err = 0;
833             t = accept(s->s,(struct sockaddr *)&isa,&addrlen);
834             if (t < 0) {
835                 break;
836             }
837
838             if (s->localhost_only && !ipv4_is_loopback(isa.sin_addr)) {
839                 close(t);              /* someone let nonlocal through?! */
840             } else if (plug_accepting(s->plug, (void*)t)) {
841                 close(t);              /* denied or error */
842             }
843             break;
844         }
845
846         /*
847          * If we reach here, this is not a listening socket, so
848          * readability really means readability.
849          */
850
851         /* In the case the socket is still frozen, we don't even bother */
852         if (s->frozen) {
853             s->frozen_readable = 1;
854             break;
855         }
856
857         /*
858          * We have received data on the socket. For an oobinline
859          * socket, this might be data _before_ an urgent pointer,
860          * in which case we send it to the back end with type==1
861          * (data prior to urgent).
862          */
863         if (s->oobinline && s->oobpending) {
864             atmark = 1;
865             if (ioctl(s->s, SIOCATMARK, &atmark) == 0 && atmark)
866                 s->oobpending = FALSE; /* clear this indicator */
867         } else
868             atmark = 1;
869
870         ret = recv(s->s, buf, s->oobpending ? 1 : sizeof(buf), 0);
871         noise_ultralight(ret);
872         if (ret < 0) {
873             if (errno == EWOULDBLOCK) {
874                 break;
875             }
876         }
877         if (ret < 0) {
878             return plug_closing(s->plug, error_string(errno), errno, 0);
879         } else if (0 == ret) {
880             return plug_closing(s->plug, NULL, 0, 0);
881         } else {
882             return plug_receive(s->plug, atmark ? 0 : 1, buf, ret);
883         }
884         break;
885       case 2:                          /* writable */
886         {
887             int bufsize_before, bufsize_after;
888             s->writable = 1;
889             bufsize_before = s->sending_oob + bufchain_size(&s->output_data);
890             try_send(s);
891             bufsize_after = s->sending_oob + bufchain_size(&s->output_data);
892             if (bufsize_after < bufsize_before)
893                 plug_sent(s->plug, bufsize_after);
894         }
895         break;
896     }
897
898     return 1;
899 }
900
901 /*
902  * Deal with socket errors detected in try_send().
903  */
904 void net_pending_errors(void)
905 {
906     int i;
907     Actual_Socket s;
908
909     /*
910      * This might be a fiddly business, because it's just possible
911      * that handling a pending error on one socket might cause
912      * others to be closed. (I can't think of any reason this might
913      * happen in current SSH implementation, but to maintain
914      * generality of this network layer I'll assume the worst.)
915      * 
916      * So what we'll do is search the socket list for _one_ socket
917      * with a pending error, and then handle it, and then search
918      * the list again _from the beginning_. Repeat until we make a
919      * pass with no socket errors present. That way we are
920      * protected against the socket list changing under our feet.
921      */
922
923     do {
924         for (i = 0; (s = index234(sktree, i)) != NULL; i++) {
925             if (s->pending_error) {
926                 /*
927                  * An error has occurred on this socket. Pass it to the
928                  * plug.
929                  */
930                 plug_closing(s->plug, error_string(s->pending_error),
931                              s->pending_error, 0);
932                 break;
933             }
934         }
935     } while (s);
936 }
937
938 /*
939  * Each socket abstraction contains a `void *' private field in
940  * which the client can keep state.
941  */
942 static void sk_tcp_set_private_ptr(Socket sock, void *ptr)
943 {
944     Actual_Socket s = (Actual_Socket) sock;
945     s->private_ptr = ptr;
946 }
947
948 static void *sk_tcp_get_private_ptr(Socket sock)
949 {
950     Actual_Socket s = (Actual_Socket) sock;
951     return s->private_ptr;
952 }
953
954 /*
955  * Special error values are returned from sk_namelookup and sk_new
956  * if there's a problem. These functions extract an error message,
957  * or return NULL if there's no problem.
958  */
959 char *sk_addr_error(SockAddr addr)
960 {
961     return addr->error;
962 }
963 static char *sk_tcp_socket_error(Socket sock)
964 {
965     Actual_Socket s = (Actual_Socket) sock;
966     return s->error;
967 }
968
969 static void sk_tcp_set_frozen(Socket sock, int is_frozen)
970 {
971     Actual_Socket s = (Actual_Socket) sock;
972     if (s->frozen == is_frozen)
973         return;
974     s->frozen = is_frozen;
975     if (!is_frozen && s->frozen_readable) {
976         char c;
977         recv(s->s, &c, 1, MSG_PEEK);
978     }
979     s->frozen_readable = 0;
980 }
981
982 /*
983  * For Unix select()-based frontends: enumerate all sockets
984  * currently active, and state whether we currently wish to receive
985  * select events on them for reading, writing and exceptional
986  * status.
987  */
988 static void set_rwx(Actual_Socket s, int *rwx)
989 {
990     int val = 0;
991     if (s->connected && !s->frozen)
992         val |= 1 | 4;                  /* read, except */
993     if (bufchain_size(&s->output_data))
994         val |= 2;                      /* write */
995     if (s->listener)
996         val |= 1;                      /* read == accept */
997     *rwx = val;
998 }
999
1000 int first_socket(int *state, int *rwx)
1001 {
1002     Actual_Socket s;
1003     *state = 0;
1004     s = index234(sktree, (*state)++);
1005     if (s)
1006         set_rwx(s, rwx);
1007     return s ? s->s : -1;
1008 }
1009
1010 int next_socket(int *state, int *rwx)
1011 {
1012     Actual_Socket s = index234(sktree, (*state)++);
1013     if (s)
1014         set_rwx(s, rwx);
1015     return s ? s->s : -1;
1016 }
1017
1018 int net_service_lookup(char *service)
1019 {
1020     struct servent *se;
1021     se = getservbyname(service, NULL);
1022     if (se != NULL)
1023         return ntohs(se->s_port);
1024     else
1025         return 0;
1026 }