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