f7b212fba8aad0963e369491dd7a1b3386037ea7
[qemu.git] / slirp / socket.c
blobf7b212fba8aad0963e369491dd7a1b3386037ea7
1 /*
2 * Copyright (c) 1995 Danny Gasparovski.
4 * Please read the file COPYRIGHT for the
5 * terms and conditions of the copyright.
6 */
8 #include "qemu-common.h"
9 #include <slirp.h>
10 #include "ip_icmp.h"
11 #ifdef __sun__
12 #include <sys/filio.h>
13 #endif
15 static void sofcantrcvmore(struct socket *so);
16 static void sofcantsendmore(struct socket *so);
18 struct socket *
19 solookup(struct socket *head, struct in_addr laddr, u_int lport,
20 struct in_addr faddr, u_int fport)
22 struct socket *so;
24 for (so = head->so_next; so != head; so = so->so_next) {
25 if (so->so_lport == lport &&
26 so->so_laddr.s_addr == laddr.s_addr &&
27 so->so_faddr.s_addr == faddr.s_addr &&
28 so->so_fport == fport)
29 break;
32 if (so == head)
33 return (struct socket *)NULL;
34 return so;
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
43 struct socket *
44 socreate(void)
46 struct socket *so;
48 so = (struct socket *)malloc(sizeof(struct socket));
49 if(so) {
50 memset(so, 0, sizeof(struct socket));
51 so->so_state = SS_NOFDREF;
52 so->s = -1;
54 return(so);
58 * remque and free a socket, clobber cache
60 void
61 sofree(struct socket *so)
63 if (so->so_emu==EMU_RSH && so->extra) {
64 sofree(so->extra);
65 so->extra=NULL;
67 if (so == tcp_last_so)
68 tcp_last_so = &tcb;
69 else if (so == udp_last_so)
70 udp_last_so = &udb;
72 m_free(so->so_m);
74 if(so->so_next && so->so_prev)
75 remque(so); /* crashes if so is not in a queue */
77 free(so);
80 size_t sopreprbuf(struct socket *so, struct iovec *iov, int *np)
82 int n, lss, total;
83 struct sbuf *sb = &so->so_snd;
84 int len = sb->sb_datalen - sb->sb_cc;
85 int mss = so->so_tcpcb->t_maxseg;
87 DEBUG_CALL("sopreprbuf");
88 DEBUG_ARG("so = %lx", (long )so);
90 len = sb->sb_datalen - sb->sb_cc;
92 if (len <= 0)
93 return 0;
95 iov[0].iov_base = sb->sb_wptr;
96 iov[1].iov_base = NULL;
97 iov[1].iov_len = 0;
98 if (sb->sb_wptr < sb->sb_rptr) {
99 iov[0].iov_len = sb->sb_rptr - sb->sb_wptr;
100 /* Should never succeed, but... */
101 if (iov[0].iov_len > len)
102 iov[0].iov_len = len;
103 if (iov[0].iov_len > mss)
104 iov[0].iov_len -= iov[0].iov_len%mss;
105 n = 1;
106 } else {
107 iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_wptr;
108 /* Should never succeed, but... */
109 if (iov[0].iov_len > len) iov[0].iov_len = len;
110 len -= iov[0].iov_len;
111 if (len) {
112 iov[1].iov_base = sb->sb_data;
113 iov[1].iov_len = sb->sb_rptr - sb->sb_data;
114 if(iov[1].iov_len > len)
115 iov[1].iov_len = len;
116 total = iov[0].iov_len + iov[1].iov_len;
117 if (total > mss) {
118 lss = total%mss;
119 if (iov[1].iov_len > lss) {
120 iov[1].iov_len -= lss;
121 n = 2;
122 } else {
123 lss -= iov[1].iov_len;
124 iov[0].iov_len -= lss;
125 n = 1;
127 } else
128 n = 2;
129 } else {
130 if (iov[0].iov_len > mss)
131 iov[0].iov_len -= iov[0].iov_len%mss;
132 n = 1;
135 if (np)
136 *np = n;
138 return iov[0].iov_len + (n - 1) * iov[1].iov_len;
142 * Read from so's socket into sb_snd, updating all relevant sbuf fields
143 * NOTE: This will only be called if it is select()ed for reading, so
144 * a read() of 0 (or less) means it's disconnected
147 soread(struct socket *so)
149 int n, nn;
150 struct sbuf *sb = &so->so_snd;
151 struct iovec iov[2];
153 DEBUG_CALL("soread");
154 DEBUG_ARG("so = %lx", (long )so);
157 * No need to check if there's enough room to read.
158 * soread wouldn't have been called if there weren't
160 sopreprbuf(so, iov, &n);
162 #ifdef HAVE_READV
163 nn = readv(so->s, (struct iovec *)iov, n);
164 DEBUG_MISC((dfd, " ... read nn = %d bytes\n", nn));
165 #else
166 nn = recv(so->s, iov[0].iov_base, iov[0].iov_len,0);
167 #endif
168 if (nn <= 0) {
169 if (nn < 0 && (errno == EINTR || errno == EAGAIN))
170 return 0;
171 else {
172 DEBUG_MISC((dfd, " --- soread() disconnected, nn = %d, errno = %d-%s\n", nn, errno,strerror(errno)));
173 sofcantrcvmore(so);
174 tcp_sockclosed(sototcpcb(so));
175 return -1;
179 #ifndef HAVE_READV
181 * If there was no error, try and read the second time round
182 * We read again if n = 2 (ie, there's another part of the buffer)
183 * and we read as much as we could in the first read
184 * We don't test for <= 0 this time, because there legitimately
185 * might not be any more data (since the socket is non-blocking),
186 * a close will be detected on next iteration.
187 * A return of -1 wont (shouldn't) happen, since it didn't happen above
189 if (n == 2 && nn == iov[0].iov_len) {
190 int ret;
191 ret = recv(so->s, iov[1].iov_base, iov[1].iov_len,0);
192 if (ret > 0)
193 nn += ret;
196 DEBUG_MISC((dfd, " ... read nn = %d bytes\n", nn));
197 #endif
199 /* Update fields */
200 sb->sb_cc += nn;
201 sb->sb_wptr += nn;
202 if (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))
203 sb->sb_wptr -= sb->sb_datalen;
204 return nn;
207 int soreadbuf(struct socket *so, const char *buf, int size)
209 int n, nn, copy = size;
210 struct sbuf *sb = &so->so_snd;
211 struct iovec iov[2];
213 DEBUG_CALL("soreadbuf");
214 DEBUG_ARG("so = %lx", (long )so);
217 * No need to check if there's enough room to read.
218 * soread wouldn't have been called if there weren't
220 if (sopreprbuf(so, iov, &n) < size)
221 goto err;
223 nn = MIN(iov[0].iov_len, copy);
224 memcpy(iov[0].iov_base, buf, nn);
226 copy -= nn;
227 buf += nn;
229 if (copy == 0)
230 goto done;
232 memcpy(iov[1].iov_base, buf, copy);
234 done:
235 /* Update fields */
236 sb->sb_cc += size;
237 sb->sb_wptr += size;
238 if (sb->sb_wptr >= (sb->sb_data + sb->sb_datalen))
239 sb->sb_wptr -= sb->sb_datalen;
240 return size;
241 err:
243 sofcantrcvmore(so);
244 tcp_sockclosed(sototcpcb(so));
245 fprintf(stderr, "soreadbuf buffer to small");
246 return -1;
250 * Get urgent data
252 * When the socket is created, we set it SO_OOBINLINE,
253 * so when OOB data arrives, we soread() it and everything
254 * in the send buffer is sent as urgent data
256 void
257 sorecvoob(struct socket *so)
259 struct tcpcb *tp = sototcpcb(so);
261 DEBUG_CALL("sorecvoob");
262 DEBUG_ARG("so = %lx", (long)so);
265 * We take a guess at how much urgent data has arrived.
266 * In most situations, when urgent data arrives, the next
267 * read() should get all the urgent data. This guess will
268 * be wrong however if more data arrives just after the
269 * urgent data, or the read() doesn't return all the
270 * urgent data.
272 soread(so);
273 tp->snd_up = tp->snd_una + so->so_snd.sb_cc;
274 tp->t_force = 1;
275 tcp_output(tp);
276 tp->t_force = 0;
280 * Send urgent data
281 * There's a lot duplicated code here, but...
284 sosendoob(struct socket *so)
286 struct sbuf *sb = &so->so_rcv;
287 char buff[2048]; /* XXX Shouldn't be sending more oob data than this */
289 int n, len;
291 DEBUG_CALL("sosendoob");
292 DEBUG_ARG("so = %lx", (long)so);
293 DEBUG_ARG("sb->sb_cc = %d", sb->sb_cc);
295 if (so->so_urgc > 2048)
296 so->so_urgc = 2048; /* XXXX */
298 if (sb->sb_rptr < sb->sb_wptr) {
299 /* We can send it directly */
300 n = slirp_send(so, sb->sb_rptr, so->so_urgc, (MSG_OOB)); /* |MSG_DONTWAIT)); */
301 so->so_urgc -= n;
303 DEBUG_MISC((dfd, " --- sent %d bytes urgent data, %d urgent bytes left\n", n, so->so_urgc));
304 } else {
306 * Since there's no sendv or sendtov like writev,
307 * we must copy all data to a linear buffer then
308 * send it all
310 len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;
311 if (len > so->so_urgc) len = so->so_urgc;
312 memcpy(buff, sb->sb_rptr, len);
313 so->so_urgc -= len;
314 if (so->so_urgc) {
315 n = sb->sb_wptr - sb->sb_data;
316 if (n > so->so_urgc) n = so->so_urgc;
317 memcpy((buff + len), sb->sb_data, n);
318 so->so_urgc -= n;
319 len += n;
321 n = slirp_send(so, buff, len, (MSG_OOB)); /* |MSG_DONTWAIT)); */
322 #ifdef DEBUG
323 if (n != len)
324 DEBUG_ERROR((dfd, "Didn't send all data urgently XXXXX\n"));
325 #endif
326 DEBUG_MISC((dfd, " ---2 sent %d bytes urgent data, %d urgent bytes left\n", n, so->so_urgc));
329 sb->sb_cc -= n;
330 sb->sb_rptr += n;
331 if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))
332 sb->sb_rptr -= sb->sb_datalen;
334 return n;
338 * Write data from so_rcv to so's socket,
339 * updating all sbuf field as necessary
342 sowrite(struct socket *so)
344 int n,nn;
345 struct sbuf *sb = &so->so_rcv;
346 int len = sb->sb_cc;
347 struct iovec iov[2];
349 DEBUG_CALL("sowrite");
350 DEBUG_ARG("so = %lx", (long)so);
352 if (so->so_urgc) {
353 sosendoob(so);
354 if (sb->sb_cc == 0)
355 return 0;
359 * No need to check if there's something to write,
360 * sowrite wouldn't have been called otherwise
363 len = sb->sb_cc;
365 iov[0].iov_base = sb->sb_rptr;
366 iov[1].iov_base = NULL;
367 iov[1].iov_len = 0;
368 if (sb->sb_rptr < sb->sb_wptr) {
369 iov[0].iov_len = sb->sb_wptr - sb->sb_rptr;
370 /* Should never succeed, but... */
371 if (iov[0].iov_len > len) iov[0].iov_len = len;
372 n = 1;
373 } else {
374 iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;
375 if (iov[0].iov_len > len) iov[0].iov_len = len;
376 len -= iov[0].iov_len;
377 if (len) {
378 iov[1].iov_base = sb->sb_data;
379 iov[1].iov_len = sb->sb_wptr - sb->sb_data;
380 if (iov[1].iov_len > len) iov[1].iov_len = len;
381 n = 2;
382 } else
383 n = 1;
385 /* Check if there's urgent data to send, and if so, send it */
387 #ifdef HAVE_READV
388 nn = writev(so->s, (const struct iovec *)iov, n);
390 DEBUG_MISC((dfd, " ... wrote nn = %d bytes\n", nn));
391 #else
392 nn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);
393 #endif
394 /* This should never happen, but people tell me it does *shrug* */
395 if (nn < 0 && (errno == EAGAIN || errno == EINTR))
396 return 0;
398 if (nn <= 0) {
399 DEBUG_MISC((dfd, " --- sowrite disconnected, so->so_state = %x, errno = %d\n",
400 so->so_state, errno));
401 sofcantsendmore(so);
402 tcp_sockclosed(sototcpcb(so));
403 return -1;
406 #ifndef HAVE_READV
407 if (n == 2 && nn == iov[0].iov_len) {
408 int ret;
409 ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);
410 if (ret > 0)
411 nn += ret;
413 DEBUG_MISC((dfd, " ... wrote nn = %d bytes\n", nn));
414 #endif
416 /* Update sbuf */
417 sb->sb_cc -= nn;
418 sb->sb_rptr += nn;
419 if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))
420 sb->sb_rptr -= sb->sb_datalen;
423 * If in DRAIN mode, and there's no more data, set
424 * it CANTSENDMORE
426 if ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)
427 sofcantsendmore(so);
429 return nn;
433 * recvfrom() a UDP socket
435 void
436 sorecvfrom(struct socket *so)
438 struct sockaddr_in addr;
439 socklen_t addrlen = sizeof(struct sockaddr_in);
441 DEBUG_CALL("sorecvfrom");
442 DEBUG_ARG("so = %lx", (long)so);
444 if (so->so_type == IPPROTO_ICMP) { /* This is a "ping" reply */
445 char buff[256];
446 int len;
448 len = recvfrom(so->s, buff, 256, 0,
449 (struct sockaddr *)&addr, &addrlen);
450 /* XXX Check if reply is "correct"? */
452 if(len == -1 || len == 0) {
453 u_char code=ICMP_UNREACH_PORT;
455 if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
456 else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;
458 DEBUG_MISC((dfd," udp icmp rx errno = %d-%s\n",
459 errno,strerror(errno)));
460 icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));
461 } else {
462 icmp_reflect(so->so_m);
463 so->so_m = NULL; /* Don't m_free() it again! */
465 /* No need for this socket anymore, udp_detach it */
466 udp_detach(so);
467 } else { /* A "normal" UDP packet */
468 struct mbuf *m;
469 int len;
470 #ifdef _WIN32
471 unsigned long n;
472 #else
473 int n;
474 #endif
476 if (!(m = m_get())) return;
477 m->m_data += IF_MAXLINKHDR;
480 * XXX Shouldn't FIONREAD packets destined for port 53,
481 * but I don't know the max packet size for DNS lookups
483 len = M_FREEROOM(m);
484 /* if (so->so_fport != htons(53)) { */
485 ioctlsocket(so->s, FIONREAD, &n);
487 if (n > len) {
488 n = (m->m_data - m->m_dat) + m->m_len + n + 1;
489 m_inc(m, n);
490 len = M_FREEROOM(m);
492 /* } */
494 m->m_len = recvfrom(so->s, m->m_data, len, 0,
495 (struct sockaddr *)&addr, &addrlen);
496 DEBUG_MISC((dfd, " did recvfrom %d, errno = %d-%s\n",
497 m->m_len, errno,strerror(errno)));
498 if(m->m_len<0) {
499 u_char code=ICMP_UNREACH_PORT;
501 if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
502 else if(errno == ENETUNREACH) code=ICMP_UNREACH_NET;
504 DEBUG_MISC((dfd," rx error, tx icmp ICMP_UNREACH:%i\n", code));
505 icmp_error(so->so_m, ICMP_UNREACH,code, 0,strerror(errno));
506 m_free(m);
507 } else {
509 * Hack: domain name lookup will be used the most for UDP,
510 * and since they'll only be used once there's no need
511 * for the 4 minute (or whatever) timeout... So we time them
512 * out much quicker (10 seconds for now...)
514 if (so->so_expire) {
515 if (so->so_fport == htons(53))
516 so->so_expire = curtime + SO_EXPIREFAST;
517 else
518 so->so_expire = curtime + SO_EXPIRE;
522 * If this packet was destined for CTL_ADDR,
523 * make it look like that's where it came from, done by udp_output
525 udp_output(so, m, &addr);
526 } /* rx error */
527 } /* if ping packet */
531 * sendto() a socket
534 sosendto(struct socket *so, struct mbuf *m)
536 int ret;
537 struct sockaddr_in addr;
539 DEBUG_CALL("sosendto");
540 DEBUG_ARG("so = %lx", (long)so);
541 DEBUG_ARG("m = %lx", (long)m);
543 addr.sin_family = AF_INET;
544 if ((so->so_faddr.s_addr & vnetwork_mask.s_addr) ==
545 vnetwork_addr.s_addr) {
546 /* It's an alias */
547 if (so->so_faddr.s_addr == vnameserver_addr.s_addr) {
548 addr.sin_addr = dns_addr;
549 } else {
550 addr.sin_addr = loopback_addr;
552 } else
553 addr.sin_addr = so->so_faddr;
554 addr.sin_port = so->so_fport;
556 DEBUG_MISC((dfd, " sendto()ing, addr.sin_port=%d, addr.sin_addr.s_addr=%.16s\n", ntohs(addr.sin_port), inet_ntoa(addr.sin_addr)));
558 /* Don't care what port we get */
559 ret = sendto(so->s, m->m_data, m->m_len, 0,
560 (struct sockaddr *)&addr, sizeof (struct sockaddr));
561 if (ret < 0)
562 return -1;
565 * Kill the socket if there's no reply in 4 minutes,
566 * but only if it's an expirable socket
568 if (so->so_expire)
569 so->so_expire = curtime + SO_EXPIRE;
570 so->so_state &= SS_PERSISTENT_MASK;
571 so->so_state |= SS_ISFCONNECTED; /* So that it gets select()ed */
572 return 0;
576 * Listen for incoming TCP connections
578 struct socket *
579 tcp_listen(u_int32_t haddr, u_int hport, u_int32_t laddr, u_int lport, int flags)
581 struct sockaddr_in addr;
582 struct socket *so;
583 int s, opt = 1;
584 socklen_t addrlen = sizeof(addr);
586 DEBUG_CALL("tcp_listen");
587 DEBUG_ARG("haddr = %x", haddr);
588 DEBUG_ARG("hport = %d", hport);
589 DEBUG_ARG("laddr = %x", laddr);
590 DEBUG_ARG("lport = %d", lport);
591 DEBUG_ARG("flags = %x", flags);
593 if ((so = socreate()) == NULL) {
594 return NULL;
597 /* Don't tcp_attach... we don't need so_snd nor so_rcv */
598 if ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL) {
599 free(so);
600 return NULL;
602 insque(so,&tcb);
605 * SS_FACCEPTONCE sockets must time out.
607 if (flags & SS_FACCEPTONCE)
608 so->so_tcpcb->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT*2;
610 so->so_state &= SS_PERSISTENT_MASK;
611 so->so_state |= (SS_FACCEPTCONN | flags);
612 so->so_lport = lport; /* Kept in network format */
613 so->so_laddr.s_addr = laddr; /* Ditto */
615 addr.sin_family = AF_INET;
616 addr.sin_addr.s_addr = haddr;
617 addr.sin_port = hport;
619 if (((s = socket(AF_INET,SOCK_STREAM,0)) < 0) ||
620 (setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&opt,sizeof(int)) < 0) ||
621 (bind(s,(struct sockaddr *)&addr, sizeof(addr)) < 0) ||
622 (listen(s,1) < 0)) {
623 int tmperrno = errno; /* Don't clobber the real reason we failed */
625 close(s);
626 sofree(so);
627 /* Restore the real errno */
628 #ifdef _WIN32
629 WSASetLastError(tmperrno);
630 #else
631 errno = tmperrno;
632 #endif
633 return NULL;
635 setsockopt(s,SOL_SOCKET,SO_OOBINLINE,(char *)&opt,sizeof(int));
637 getsockname(s,(struct sockaddr *)&addr,&addrlen);
638 so->so_fport = addr.sin_port;
639 if (addr.sin_addr.s_addr == 0 || addr.sin_addr.s_addr == loopback_addr.s_addr)
640 so->so_faddr = vhost_addr;
641 else
642 so->so_faddr = addr.sin_addr;
644 so->s = s;
645 return so;
649 * Various session state calls
650 * XXX Should be #define's
651 * The socket state stuff needs work, these often get call 2 or 3
652 * times each when only 1 was needed
654 void
655 soisfconnecting(struct socket *so)
657 so->so_state &= ~(SS_NOFDREF|SS_ISFCONNECTED|SS_FCANTRCVMORE|
658 SS_FCANTSENDMORE|SS_FWDRAIN);
659 so->so_state |= SS_ISFCONNECTING; /* Clobber other states */
662 void
663 soisfconnected(struct socket *so)
665 so->so_state &= ~(SS_ISFCONNECTING|SS_FWDRAIN|SS_NOFDREF);
666 so->so_state |= SS_ISFCONNECTED; /* Clobber other states */
669 static void
670 sofcantrcvmore(struct socket *so)
672 if ((so->so_state & SS_NOFDREF) == 0) {
673 shutdown(so->s,0);
674 if(global_writefds) {
675 FD_CLR(so->s,global_writefds);
678 so->so_state &= ~(SS_ISFCONNECTING);
679 if (so->so_state & SS_FCANTSENDMORE) {
680 so->so_state &= SS_PERSISTENT_MASK;
681 so->so_state |= SS_NOFDREF; /* Don't select it */
682 } else {
683 so->so_state |= SS_FCANTRCVMORE;
687 static void
688 sofcantsendmore(struct socket *so)
690 if ((so->so_state & SS_NOFDREF) == 0) {
691 shutdown(so->s,1); /* send FIN to fhost */
692 if (global_readfds) {
693 FD_CLR(so->s,global_readfds);
695 if (global_xfds) {
696 FD_CLR(so->s,global_xfds);
699 so->so_state &= ~(SS_ISFCONNECTING);
700 if (so->so_state & SS_FCANTRCVMORE) {
701 so->so_state &= SS_PERSISTENT_MASK;
702 so->so_state |= SS_NOFDREF; /* as above */
703 } else {
704 so->so_state |= SS_FCANTSENDMORE;
709 * Set write drain mode
710 * Set CANTSENDMORE once all data has been write()n
712 void
713 sofwdrain(struct socket *so)
715 if (so->so_rcv.sb_cc)
716 so->so_state |= SS_FWDRAIN;
717 else
718 sofcantsendmore(so);