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