1 /* SPDX-License-Identifier: BSD-3-Clause */
2 /*
3  * Copyright (c) 1995 Danny Gasparovski.
4  */
5 
6 #include "slirp.h"
7 #include "ip_icmp.h"
8 #ifdef __sun__
9 #include <sys/filio.h>
10 #endif
11 
12 static void sofcantrcvmore(struct socket *so);
13 static void sofcantsendmore(struct socket *so);
14 
solookup(struct socket ** last,struct socket * head,struct sockaddr_storage * lhost,struct sockaddr_storage * fhost)15 struct socket *solookup(struct socket **last, struct socket *head,
16                         struct sockaddr_storage *lhost,
17                         struct sockaddr_storage *fhost)
18 {
19     struct socket *so = *last;
20 
21     /* Optimisation */
22     if (so != head && sockaddr_equal(&(so->lhost.ss), lhost) &&
23         (!fhost || sockaddr_equal(&so->fhost.ss, fhost))) {
24         return so;
25     }
26 
27     for (so = head->so_next; so != head; so = so->so_next) {
28         if (sockaddr_equal(&(so->lhost.ss), lhost) &&
29             (!fhost || sockaddr_equal(&so->fhost.ss, fhost))) {
30             *last = so;
31             return so;
32         }
33     }
34 
35     return (struct socket *)NULL;
36 }
37 
38 /*
39  * Create a new socket, initialise the fields
40  * It is the responsibility of the caller to
41  * insque() it into the correct linked-list
42  */
socreate(Slirp * slirp)43 struct socket *socreate(Slirp *slirp)
44 {
45     struct socket *so = g_new(struct socket, 1);
46 
47     memset(so, 0, sizeof(struct socket));
48     so->so_state = SS_NOFDREF;
49     so->s = -1;
50     so->slirp = slirp;
51     so->pollfds_idx = -1;
52 
53     return so;
54 }
55 
56 /*
57  * Remove references to so from the given message queue.
58  */
soqfree(struct socket * so,struct quehead * qh)59 static void soqfree(struct socket *so, struct quehead *qh)
60 {
61     struct mbuf *ifq;
62 
63     for (ifq = (struct mbuf *)qh->qh_link; (struct quehead *)ifq != qh;
64          ifq = ifq->ifq_next) {
65         if (ifq->ifq_so == so) {
66             struct mbuf *ifm;
67             ifq->ifq_so = NULL;
68             for (ifm = ifq->ifs_next; ifm != ifq; ifm = ifm->ifs_next) {
69                 ifm->ifq_so = NULL;
70             }
71         }
72     }
73 }
74 
75 /*
76  * remque and free a socket, clobber cache
77  */
sofree(struct socket * so)78 void sofree(struct socket *so)
79 {
80     Slirp *slirp = so->slirp;
81 
82     soqfree(so, &slirp->if_fastq);
83     soqfree(so, &slirp->if_batchq);
84 
85     if (so == slirp->tcp_last_so) {
86         slirp->tcp_last_so = &slirp->tcb;
87     } else if (so == slirp->udp_last_so) {
88         slirp->udp_last_so = &slirp->udb;
89     } else if (so == slirp->icmp_last_so) {
90         slirp->icmp_last_so = &slirp->icmp;
91     }
92     m_free(so->so_m);
93 
94     if (so->so_next && so->so_prev)
95         remque(so); /* crashes if so is not in a queue */
96 
97     if (so->so_tcpcb) {
98         g_free(so->so_tcpcb);
99     }
100     g_free(so);
101 }
102 
sopreprbuf(struct socket * so,struct iovec * iov,int * np)103 size_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)
104 {
105     int n, lss, total;
106     struct sbuf *sb = &so->so_snd;
107     int len = sb->sb_datalen - sb->sb_cc;
108     int mss = so->so_tcpcb->t_maxseg;
109 
110     DEBUG_CALL("sopreprbuf");
111     DEBUG_ARG("so = %p", so);
112 
113     if (len <= 0)
114         return 0;
115 
116     iov[0].iov_base = sb->sb_wptr;
117     iov[1].iov_base = NULL;
118     iov[1].iov_len = 0;
119     if (sb->sb_wptr < sb->sb_rptr) {
120         iov[0].iov_len = sb->sb_rptr - sb->sb_wptr;
121         /* Should never succeed, but... */
122         if (iov[0].iov_len > len)
123             iov[0].iov_len = len;
124         if (iov[0].iov_len > mss)
125             iov[0].iov_len -= iov[0].iov_len % mss;
126         n = 1;
127     } else {
128         iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;
129         /* Should never succeed, but... */
130         if (iov[0].iov_len > len)
131             iov[0].iov_len = len;
132         len -= iov[0].iov_len;
133         if (len) {
134             iov[1].iov_base = sb->sb_data;
135             iov[1].iov_len = sb->sb_rptr - sb->sb_data;
136             if (iov[1].iov_len > len)
137                 iov[1].iov_len = len;
138             total = iov[0].iov_len + iov[1].iov_len;
139             if (total > mss) {
140                 lss = total % mss;
141                 if (iov[1].iov_len > lss) {
142                     iov[1].iov_len -= lss;
143                     n = 2;
144                 } else {
145                     lss -= iov[1].iov_len;
146                     iov[0].iov_len -= lss;
147                     n = 1;
148                 }
149             } else
150                 n = 2;
151         } else {
152             if (iov[0].iov_len > mss)
153                 iov[0].iov_len -= iov[0].iov_len % mss;
154             n = 1;
155         }
156     }
157     if (np)
158         *np = n;
159 
160     return iov[0].iov_len + (n - 1) * iov[1].iov_len;
161 }
162 
163 /*
164  * Read from so's socket into sb_snd, updating all relevant sbuf fields
165  * NOTE: This will only be called if it is select()ed for reading, so
166  * a read() of 0 (or less) means it's disconnected
167  */
soread(struct socket * so)168 int soread(struct socket *so)
169 {
170     int n, nn;
171     size_t buf_len;
172     struct sbuf *sb = &so->so_snd;
173     struct iovec iov[2];
174 
175     DEBUG_CALL("soread");
176     DEBUG_ARG("so = %p", so);
177 
178     /*
179      * No need to check if there's enough room to read.
180      * soread wouldn't have been called if there weren't
181      */
182     buf_len = sopreprbuf(so, iov, &n);
183     assert(buf_len != 0);
184 
185     nn = recv(so->s, iov[0].iov_base, iov[0].iov_len, 0);
186     if (nn <= 0) {
187         if (nn < 0 && (errno == EINTR || errno == EAGAIN))
188             return 0;
189         else {
190             int err;
191             socklen_t elen = sizeof err;
192             struct sockaddr_storage addr;
193             struct sockaddr *paddr = (struct sockaddr *)&addr;
194             socklen_t alen = sizeof addr;
195 
196             err = errno;
197             if (nn == 0) {
198                 int shutdown_wr = so->so_state & SS_FCANTSENDMORE;
199 
200                 if (!shutdown_wr && getpeername(so->s, paddr, &alen) < 0) {
201                     err = errno;
202                 } else {
203                     getsockopt(so->s, SOL_SOCKET, SO_ERROR, &err, &elen);
204                 }
205             }
206 
207             DEBUG_MISC(" --- soread() disconnected, nn = %d, errno = %d-%s", nn,
208                        errno, strerror(errno));
209             sofcantrcvmore(so);
210 
211             if (err == ECONNRESET || err == ECONNREFUSED || err == ENOTCONN ||
212                 err == EPIPE) {
213                 tcp_drop(sototcpcb(so), err);
214             } else {
215                 tcp_sockclosed(sototcpcb(so));
216             }
217             return -1;
218         }
219     }
220 
221     /*
222      * If there was no error, try and read the second time round
223      * We read again if n = 2 (ie, there's another part of the buffer)
224      * and we read as much as we could in the first read
225      * We don't test for <= 0 this time, because there legitimately
226      * might not be any more data (since the socket is non-blocking),
227      * a close will be detected on next iteration.
228      * A return of -1 won't (shouldn't) happen, since it didn't happen above
229      */
230     if (n == 2 && nn == iov[0].iov_len) {
231         int ret;
232         ret = recv(so->s, iov[1].iov_base, iov[1].iov_len, 0);
233         if (ret > 0)
234             nn += ret;
235     }
236 
237     DEBUG_MISC(" ... read nn = %d bytes", nn);
238 
239     /* Update fields */
240     sb->sb_cc += nn;
241     sb->sb_wptr += nn;
242     if (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))
243         sb->sb_wptr -= sb->sb_datalen;
244     return nn;
245 }
246 
soreadbuf(struct socket * so,const char * buf,int size)247 int soreadbuf(struct socket *so, const char *buf, int size)
248 {
249     int n, nn, copy = size;
250     struct sbuf *sb = &so->so_snd;
251     struct iovec iov[2];
252 
253     DEBUG_CALL("soreadbuf");
254     DEBUG_ARG("so = %p", so);
255 
256     /*
257      * No need to check if there's enough room to read.
258      * soread wouldn't have been called if there weren't
259      */
260     assert(size > 0);
261     if (sopreprbuf(so, iov, &n) < size)
262         goto err;
263 
264     nn = MIN(iov[0].iov_len, copy);
265     memcpy(iov[0].iov_base, buf, nn);
266 
267     copy -= nn;
268     buf += nn;
269 
270     if (copy == 0)
271         goto done;
272 
273     memcpy(iov[1].iov_base, buf, copy);
274 
275 done:
276     /* Update fields */
277     sb->sb_cc += size;
278     sb->sb_wptr += size;
279     if (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))
280         sb->sb_wptr -= sb->sb_datalen;
281     return size;
282 err:
283 
284     sofcantrcvmore(so);
285     tcp_sockclosed(sototcpcb(so));
286     g_critical("soreadbuf buffer too small");
287     return -1;
288 }
289 
290 /*
291  * Get urgent data
292  *
293  * When the socket is created, we set it SO_OOBINLINE,
294  * so when OOB data arrives, we soread() it and everything
295  * in the send buffer is sent as urgent data
296  */
sorecvoob(struct socket * so)297 int sorecvoob(struct socket *so)
298 {
299     struct tcpcb *tp = sototcpcb(so);
300     int ret;
301 
302     DEBUG_CALL("sorecvoob");
303     DEBUG_ARG("so = %p", so);
304 
305     /*
306      * We take a guess at how much urgent data has arrived.
307      * In most situations, when urgent data arrives, the next
308      * read() should get all the urgent data.  This guess will
309      * be wrong however if more data arrives just after the
310      * urgent data, or the read() doesn't return all the
311      * urgent data.
312      */
313     ret = soread(so);
314     if (ret > 0) {
315         tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
316         tp->t_force = 1;
317         tcp_output(tp);
318         tp->t_force = 0;
319     }
320 
321     return ret;
322 }
323 
324 /*
325  * Send urgent data
326  * There's a lot duplicated code here, but...
327  */
sosendoob(struct socket * so)328 int sosendoob(struct socket *so)
329 {
330     struct sbuf *sb = &so->so_rcv;
331     char buff[2048]; /* XXX Shouldn't be sending more oob data than this */
332 
333     int n;
334 
335     DEBUG_CALL("sosendoob");
336     DEBUG_ARG("so = %p", so);
337     DEBUG_ARG("sb->sb_cc = %d", sb->sb_cc);
338 
339     if (so->so_urgc > 2048)
340         so->so_urgc = 2048; /* XXXX */
341 
342     if (sb->sb_rptr < sb->sb_wptr) {
343         /* We can send it directly */
344         n = slirp_send(so, sb->sb_rptr, so->so_urgc,
345                        (MSG_OOB)); /* |MSG_DONTWAIT)); */
346     } else {
347         /*
348          * Since there's no sendv or sendtov like writev,
349          * we must copy all data to a linear buffer then
350          * send it all
351          */
352         uint32_t urgc = so->so_urgc;
353         int len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;
354         if (len > urgc) {
355             len = urgc;
356         }
357         memcpy(buff, sb->sb_rptr, len);
358         urgc -= len;
359         if (urgc) {
360             n = sb->sb_wptr - sb->sb_data;
361             if (n > urgc) {
362                 n = urgc;
363             }
364             memcpy((buff + len), sb->sb_data, n);
365             len += n;
366         }
367         n = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */
368 #ifdef DEBUG
369         if (n != len) {
370             DEBUG_ERROR("Didn't send all data urgently XXXXX");
371         }
372 #endif
373     }
374 
375     if (n < 0) {
376         return n;
377     }
378     so->so_urgc -= n;
379     DEBUG_MISC(" ---2 sent %d bytes urgent data, %d urgent bytes left", n,
380                so->so_urgc);
381 
382     sb->sb_cc -= n;
383     sb->sb_rptr += n;
384     if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))
385         sb->sb_rptr -= sb->sb_datalen;
386 
387     return n;
388 }
389 
390 /*
391  * Write data from so_rcv to so's socket,
392  * updating all sbuf field as necessary
393  */
sowrite(struct socket * so)394 int sowrite(struct socket *so)
395 {
396     int n, nn;
397     struct sbuf *sb = &so->so_rcv;
398     int len = sb->sb_cc;
399     struct iovec iov[2];
400 
401     DEBUG_CALL("sowrite");
402     DEBUG_ARG("so = %p", so);
403 
404     if (so->so_urgc) {
405         uint32_t expected = so->so_urgc;
406         if (sosendoob(so) < expected) {
407             /* Treat a short write as a fatal error too,
408              * rather than continuing on and sending the urgent
409              * data as if it were non-urgent and leaving the
410              * so_urgc count wrong.
411              */
412             goto err_disconnected;
413         }
414         if (sb->sb_cc == 0)
415             return 0;
416     }
417 
418     /*
419      * No need to check if there's something to write,
420      * sowrite wouldn't have been called otherwise
421      */
422 
423     iov[0].iov_base = sb->sb_rptr;
424     iov[1].iov_base = NULL;
425     iov[1].iov_len = 0;
426     if (sb->sb_rptr < sb->sb_wptr) {
427         iov[0].iov_len = sb->sb_wptr - sb->sb_rptr;
428         /* Should never succeed, but... */
429         if (iov[0].iov_len > len)
430             iov[0].iov_len = len;
431         n = 1;
432     } else {
433         iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;
434         if (iov[0].iov_len > len)
435             iov[0].iov_len = len;
436         len -= iov[0].iov_len;
437         if (len) {
438             iov[1].iov_base = sb->sb_data;
439             iov[1].iov_len = sb->sb_wptr - sb->sb_data;
440             if (iov[1].iov_len > len)
441                 iov[1].iov_len = len;
442             n = 2;
443         } else
444             n = 1;
445     }
446     /* Check if there's urgent data to send, and if so, send it */
447 
448     nn = slirp_send(so, iov[0].iov_base, iov[0].iov_len, 0);
449     /* This should never happen, but people tell me it does *shrug* */
450     if (nn < 0 && (errno == EAGAIN || errno == EINTR))
451         return 0;
452 
453     if (nn <= 0) {
454         goto err_disconnected;
455     }
456 
457     if (n == 2 && nn == iov[0].iov_len) {
458         int ret;
459         ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len, 0);
460         if (ret > 0)
461             nn += ret;
462     }
463     DEBUG_MISC("  ... wrote nn = %d bytes", nn);
464 
465     /* Update sbuf */
466     sb->sb_cc -= nn;
467     sb->sb_rptr += nn;
468     if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))
469         sb->sb_rptr -= sb->sb_datalen;
470 
471     /*
472      * If in DRAIN mode, and there's no more data, set
473      * it CANTSENDMORE
474      */
475     if ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)
476         sofcantsendmore(so);
477 
478     return nn;
479 
480 err_disconnected:
481     DEBUG_MISC(" --- sowrite disconnected, so->so_state = %x, errno = %d",
482                so->so_state, errno);
483     sofcantsendmore(so);
484     tcp_sockclosed(sototcpcb(so));
485     return -1;
486 }
487 
488 /*
489  * recvfrom() a UDP socket
490  */
sorecvfrom(struct socket * so)491 void sorecvfrom(struct socket *so)
492 {
493     struct sockaddr_storage addr;
494     struct sockaddr_storage saddr, daddr;
495     socklen_t addrlen = sizeof(struct sockaddr_storage);
496 
497     DEBUG_CALL("sorecvfrom");
498     DEBUG_ARG("so = %p", so);
499 
500     if (so->so_type == IPPROTO_ICMP) { /* This is a "ping" reply */
501         char buff[256];
502         int len;
503 
504         len = recvfrom(so->s, buff, 256, 0, (struct sockaddr *)&addr, &addrlen);
505         /* XXX Check if reply is "correct"? */
506 
507         if (len == -1 || len == 0) {
508             uint8_t code = ICMP_UNREACH_PORT;
509 
510             if (errno == EHOSTUNREACH)
511                 code = ICMP_UNREACH_HOST;
512             else if (errno == ENETUNREACH)
513                 code = ICMP_UNREACH_NET;
514 
515             DEBUG_MISC(" udp icmp rx errno = %d-%s", errno, strerror(errno));
516             icmp_send_error(so->so_m, ICMP_UNREACH, code, 0, strerror(errno));
517         } else {
518             icmp_reflect(so->so_m);
519             so->so_m = NULL; /* Don't m_free() it again! */
520         }
521         /* No need for this socket anymore, udp_detach it */
522         udp_detach(so);
523     } else { /* A "normal" UDP packet */
524         struct mbuf *m;
525         int len;
526 #ifdef _WIN32
527         unsigned long n;
528 #else
529         int n;
530 #endif
531 
532         if (ioctlsocket(so->s, FIONREAD, &n) != 0) {
533             DEBUG_MISC(" ioctlsocket errno = %d-%s\n", errno, strerror(errno));
534             return;
535         }
536         if (n == 0) {
537             return;
538         }
539 
540         m = m_get(so->slirp);
541         if (!m) {
542             return;
543         }
544         switch (so->so_ffamily) {
545         case AF_INET:
546             m->m_data += IF_MAXLINKHDR + sizeof(struct udpiphdr);
547             break;
548         case AF_INET6:
549             m->m_data +=
550                 IF_MAXLINKHDR + sizeof(struct ip6) + sizeof(struct udphdr);
551             break;
552         default:
553             g_assert_not_reached();
554             break;
555         }
556 
557         /*
558          * XXX Shouldn't FIONREAD packets destined for port 53,
559          * but I don't know the max packet size for DNS lookups
560          */
561         len = M_FREEROOM(m);
562         /* if (so->so_fport != htons(53)) { */
563 
564         if (n > len) {
565             n = (m->m_data - m->m_dat) + m->m_len + n + 1;
566             m_inc(m, n);
567             len = M_FREEROOM(m);
568         }
569         /* } */
570 
571         m->m_len = recvfrom(so->s, m->m_data, len, 0, (struct sockaddr *)&addr,
572                             &addrlen);
573         DEBUG_MISC(" did recvfrom %d, errno = %d-%s", m->m_len, errno,
574                    strerror(errno));
575         if (m->m_len < 0) {
576             /* Report error as ICMP */
577             switch (so->so_lfamily) {
578                 uint8_t code;
579             case AF_INET:
580                 code = ICMP_UNREACH_PORT;
581 
582                 if (errno == EHOSTUNREACH) {
583                     code = ICMP_UNREACH_HOST;
584                 } else if (errno == ENETUNREACH) {
585                     code = ICMP_UNREACH_NET;
586                 }
587 
588                 DEBUG_MISC(" rx error, tx icmp ICMP_UNREACH:%i", code);
589                 icmp_send_error(so->so_m, ICMP_UNREACH, code, 0,
590                                 strerror(errno));
591                 break;
592             case AF_INET6:
593                 code = ICMP6_UNREACH_PORT;
594 
595                 if (errno == EHOSTUNREACH) {
596                     code = ICMP6_UNREACH_ADDRESS;
597                 } else if (errno == ENETUNREACH) {
598                     code = ICMP6_UNREACH_NO_ROUTE;
599                 }
600 
601                 DEBUG_MISC(" rx error, tx icmp6 ICMP_UNREACH:%i", code);
602                 icmp6_send_error(so->so_m, ICMP6_UNREACH, code);
603                 break;
604             default:
605                 g_assert_not_reached();
606                 break;
607             }
608             m_free(m);
609         } else {
610             /*
611              * Hack: domain name lookup will be used the most for UDP,
612              * and since they'll only be used once there's no need
613              * for the 4 minute (or whatever) timeout... So we time them
614              * out much quicker (10 seconds  for now...)
615              */
616             if (so->so_expire) {
617                 if (so->so_fport == htons(53))
618                     so->so_expire = curtime + SO_EXPIREFAST;
619                 else
620                     so->so_expire = curtime + SO_EXPIRE;
621             }
622 
623             /*
624              * If this packet was destined for CTL_ADDR,
625              * make it look like that's where it came from
626              */
627             saddr = addr;
628             sotranslate_in(so, &saddr);
629             daddr = so->lhost.ss;
630 
631             switch (so->so_ffamily) {
632             case AF_INET:
633                 udp_output(so, m, (struct sockaddr_in *)&saddr,
634                            (struct sockaddr_in *)&daddr, so->so_iptos);
635                 break;
636             case AF_INET6:
637                 udp6_output(so, m, (struct sockaddr_in6 *)&saddr,
638                             (struct sockaddr_in6 *)&daddr);
639                 break;
640             default:
641                 g_assert_not_reached();
642                 break;
643             }
644         } /* rx error */
645     } /* if ping packet */
646 }
647 
648 /*
649  * sendto() a socket
650  */
sosendto(struct socket * so,struct mbuf * m)651 int sosendto(struct socket *so, struct mbuf *m)
652 {
653     int ret;
654     struct sockaddr_storage addr;
655 
656     DEBUG_CALL("sosendto");
657     DEBUG_ARG("so = %p", so);
658     DEBUG_ARG("m = %p", m);
659 
660     addr = so->fhost.ss;
661     DEBUG_CALL(" sendto()ing)");
662     if (sotranslate_out(so, &addr) < 0) {
663         return -1;
664     }
665 
666     /* Don't care what port we get */
667     ret = sendto(so->s, m->m_data, m->m_len, 0, (struct sockaddr *)&addr,
668                  sockaddr_size(&addr));
669     if (ret < 0)
670         return -1;
671 
672     /*
673      * Kill the socket if there's no reply in 4 minutes,
674      * but only if it's an expirable socket
675      */
676     if (so->so_expire)
677         so->so_expire = curtime + SO_EXPIRE;
678     so->so_state &= SS_PERSISTENT_MASK;
679     so->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */
680     return 0;
681 }
682 
683 /*
684  * Listen for incoming TCP connections
685  */
tcp_listen(Slirp * slirp,uint32_t haddr,unsigned hport,uint32_t laddr,unsigned lport,int flags)686 struct socket *tcp_listen(Slirp *slirp, uint32_t haddr, unsigned hport,
687                           uint32_t laddr, unsigned lport, int flags)
688 {
689     /* TODO: IPv6 */
690     struct sockaddr_in addr;
691     struct socket *so;
692     int s, opt = 1;
693     socklen_t addrlen = sizeof(addr);
694     memset(&addr, 0, addrlen);
695 
696     DEBUG_CALL("tcp_listen");
697     DEBUG_ARG("haddr = %s", inet_ntoa((struct in_addr){ .s_addr = haddr }));
698     DEBUG_ARG("hport = %d", ntohs(hport));
699     DEBUG_ARG("laddr = %s", inet_ntoa((struct in_addr){ .s_addr = laddr }));
700     DEBUG_ARG("lport = %d", ntohs(lport));
701     DEBUG_ARG("flags = %x", flags);
702 
703     so = socreate(slirp);
704 
705     /* Don't tcp_attach... we don't need so_snd nor so_rcv */
706     if ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {
707         g_free(so);
708         return NULL;
709     }
710     insque(so, &slirp->tcb);
711 
712     /*
713      * SS_FACCEPTONCE sockets must time out.
714      */
715     if (flags & SS_FACCEPTONCE)
716         so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT * 2;
717 
718     so->so_state &= SS_PERSISTENT_MASK;
719     so->so_state |= (SS_FACCEPTCONN | flags);
720     so->so_lfamily = AF_INET;
721     so->so_lport = lport; /* Kept in network format */
722     so->so_laddr.s_addr = laddr; /* Ditto */
723 
724     addr.sin_family = AF_INET;
725     addr.sin_addr.s_addr = haddr;
726     addr.sin_port = hport;
727 
728     if (((s = slirp_socket(AF_INET, SOCK_STREAM, 0)) < 0) ||
729         (slirp_socket_set_fast_reuse(s) < 0) ||
730         (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) ||
731         (listen(s, 1) < 0)) {
732         int tmperrno = errno; /* Don't clobber the real reason we failed */
733 
734         if (s >= 0) {
735             closesocket(s);
736         }
737         sofree(so);
738         /* Restore the real errno */
739 #ifdef _WIN32
740         WSASetLastError(tmperrno);
741 #else
742         errno = tmperrno;
743 #endif
744         return NULL;
745     }
746     setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(int));
747     opt = 1;
748     setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(int));
749 
750     getsockname(s, (struct sockaddr *)&addr, &addrlen);
751     so->so_ffamily = AF_INET;
752     so->so_fport = addr.sin_port;
753     if (addr.sin_addr.s_addr == 0 ||
754         addr.sin_addr.s_addr == loopback_addr.s_addr)
755         so->so_faddr = slirp->vhost_addr;
756     else
757         so->so_faddr = addr.sin_addr;
758 
759     so->s = s;
760     return so;
761 }
762 
763 /*
764  * Various session state calls
765  * XXX Should be #define's
766  * The socket state stuff needs work, these often get call 2 or 3
767  * times each when only 1 was needed
768  */
soisfconnecting(struct socket * so)769 void soisfconnecting(struct socket *so)
770 {
771     so->so_state &= ~(SS_NOFDREF | SS_ISFCONNECTED | SS_FCANTRCVMORE |
772                       SS_FCANTSENDMORE | SS_FWDRAIN);
773     so->so_state |= SS_ISFCONNECTING; /* Clobber other states */
774 }
775 
soisfconnected(struct socket * so)776 void soisfconnected(struct socket *so)
777 {
778     so->so_state &= ~(SS_ISFCONNECTING | SS_FWDRAIN | SS_NOFDREF);
779     so->so_state |= SS_ISFCONNECTED; /* Clobber other states */
780 }
781 
sofcantrcvmore(struct socket * so)782 static void sofcantrcvmore(struct socket *so)
783 {
784     if ((so->so_state & SS_NOFDREF) == 0) {
785         shutdown(so->s, 0);
786     }
787     so->so_state &= ~(SS_ISFCONNECTING);
788     if (so->so_state & SS_FCANTSENDMORE) {
789         so->so_state &= SS_PERSISTENT_MASK;
790         so->so_state |= SS_NOFDREF; /* Don't select it */
791     } else {
792         so->so_state |= SS_FCANTRCVMORE;
793     }
794 }
795 
sofcantsendmore(struct socket * so)796 static void sofcantsendmore(struct socket *so)
797 {
798     if ((so->so_state & SS_NOFDREF) == 0) {
799         shutdown(so->s, 1); /* send FIN to fhost */
800     }
801     so->so_state &= ~(SS_ISFCONNECTING);
802     if (so->so_state & SS_FCANTRCVMORE) {
803         so->so_state &= SS_PERSISTENT_MASK;
804         so->so_state |= SS_NOFDREF; /* as above */
805     } else {
806         so->so_state |= SS_FCANTSENDMORE;
807     }
808 }
809 
810 /*
811  * Set write drain mode
812  * Set CANTSENDMORE once all data has been write()n
813  */
sofwdrain(struct socket * so)814 void sofwdrain(struct socket *so)
815 {
816     if (so->so_rcv.sb_cc)
817         so->so_state |= SS_FWDRAIN;
818     else
819         sofcantsendmore(so);
820 }
821 
sotranslate_out4(Slirp * s,struct socket * so,struct sockaddr_in * sin)822 static bool sotranslate_out4(Slirp *s, struct socket *so, struct sockaddr_in *sin)
823 {
824     if (so->so_faddr.s_addr == s->vnameserver_addr.s_addr) {
825         return get_dns_addr(&sin->sin_addr) >= 0;
826     }
827 
828     if (so->so_faddr.s_addr == s->vhost_addr.s_addr ||
829         so->so_faddr.s_addr == 0xffffffff) {
830         if (s->disable_host_loopback) {
831             return false;
832         }
833 
834         sin->sin_addr = loopback_addr;
835     }
836 
837     return true;
838 }
839 
sotranslate_out6(Slirp * s,struct socket * so,struct sockaddr_in6 * sin)840 static bool sotranslate_out6(Slirp *s, struct socket *so, struct sockaddr_in6 *sin)
841 {
842     if (in6_equal(&so->so_faddr6, &s->vnameserver_addr6)) {
843         uint32_t scope_id;
844         if (get_dns6_addr(&sin->sin6_addr, &scope_id) >= 0) {
845             sin->sin6_scope_id = scope_id;
846             return true;
847         }
848         return false;
849     }
850 
851     if (in6_equal_net(&so->so_faddr6, &s->vprefix_addr6, s->vprefix_len) ||
852         in6_equal(&so->so_faddr6, &(struct in6_addr)ALLNODES_MULTICAST)) {
853         if (s->disable_host_loopback) {
854             return false;
855         }
856 
857         sin->sin6_addr = in6addr_loopback;
858     }
859 
860     return true;
861 }
862 
863 
864 /*
865  * Translate addr in host addr when it is a virtual address
866  */
sotranslate_out(struct socket * so,struct sockaddr_storage * addr)867 int sotranslate_out(struct socket *so, struct sockaddr_storage *addr)
868 {
869     bool ok = true;
870 
871     switch (addr->ss_family) {
872     case AF_INET:
873         ok = sotranslate_out4(so->slirp, so, (struct sockaddr_in *)addr);
874         break;
875     case AF_INET6:
876         ok = sotranslate_out6(so->slirp, so, (struct sockaddr_in6 *)addr);
877         break;
878     }
879 
880     if (!ok) {
881         errno = EPERM;
882         return -1;
883     }
884 
885     return 0;
886 }
887 
sotranslate_in(struct socket * so,struct sockaddr_storage * addr)888 void sotranslate_in(struct socket *so, struct sockaddr_storage *addr)
889 {
890     Slirp *slirp = so->slirp;
891     struct sockaddr_in *sin = (struct sockaddr_in *)addr;
892     struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)addr;
893 
894     switch (addr->ss_family) {
895     case AF_INET:
896         if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==
897             slirp->vnetwork_addr.s_addr) {
898             uint32_t inv_mask = ~slirp->vnetwork_mask.s_addr;
899 
900             if ((so->so_faddr.s_addr & inv_mask) == inv_mask) {
901                 sin->sin_addr = slirp->vhost_addr;
902             } else if (sin->sin_addr.s_addr == loopback_addr.s_addr ||
903                        so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {
904                 sin->sin_addr = so->so_faddr;
905             }
906         }
907         break;
908 
909     case AF_INET6:
910         if (in6_equal_net(&so->so_faddr6, &slirp->vprefix_addr6,
911                           slirp->vprefix_len)) {
912             if (in6_equal(&sin6->sin6_addr, &in6addr_loopback) ||
913                 !in6_equal(&so->so_faddr6, &slirp->vhost_addr6)) {
914                 sin6->sin6_addr = so->so_faddr6;
915             }
916         }
917         break;
918 
919     default:
920         break;
921     }
922 }
923 
924 /*
925  * Translate connections from localhost to the real hostname
926  */
sotranslate_accept(struct socket * so)927 void sotranslate_accept(struct socket *so)
928 {
929     Slirp *slirp = so->slirp;
930 
931     switch (so->so_ffamily) {
932     case AF_INET:
933         if (so->so_faddr.s_addr == INADDR_ANY ||
934             (so->so_faddr.s_addr & loopback_mask) ==
935                 (loopback_addr.s_addr & loopback_mask)) {
936             so->so_faddr = slirp->vhost_addr;
937         }
938         break;
939 
940     case AF_INET6:
941         if (in6_equal(&so->so_faddr6, &in6addr_any) ||
942             in6_equal(&so->so_faddr6, &in6addr_loopback)) {
943             so->so_faddr6 = slirp->vhost_addr6;
944         }
945         break;
946 
947     default:
948         break;
949     }
950 }
951 
sodrop(struct socket * s,int num)952 void sodrop(struct socket *s, int num)
953 {
954     if (sbdrop(&s->so_snd, num)) {
955         s->slirp->cb->notify(s->slirp->opaque);
956     }
957 }
958