VirtualBox

source: vbox/trunk/src/VBox/Devices/Network/slirp/slirp.c@ 1076

Last change on this file since 1076 was 1076, checked in by vboxsync, 18 years ago

Removed tons of ifdef VBOX conditionals to make slirp readable again

  • Property svn:eol-style set to native
File size: 17.5 KB
Line 
1#include "slirp.h"
2#ifdef __OS2__
3# include <paths.h>
4#endif
5
6#include <VBox/err.h>
7#include <iprt/assert.h>
8
9static const uint8_t special_ethaddr[6] = {
10 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
11};
12
13#ifdef _WIN32
14
15static int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
16{
17 FIXED_INFO *FixedInfo=NULL;
18 ULONG BufLen;
19 DWORD ret;
20 IP_ADDR_STRING *pIPAddr;
21 struct in_addr tmp_addr;
22
23 FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
24 BufLen = sizeof(FIXED_INFO);
25
26 if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {
27 if (FixedInfo) {
28 GlobalFree(FixedInfo);
29 FixedInfo = NULL;
30 }
31 FixedInfo = GlobalAlloc(GPTR, BufLen);
32 }
33
34 if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {
35 Log(("GetNetworkParams failed. ret = %08x\n", (u_int)ret ));
36 if (FixedInfo) {
37 GlobalFree(FixedInfo);
38 FixedInfo = NULL;
39 }
40 return -1;
41 }
42
43 pIPAddr = &(FixedInfo->DnsServerList);
44 inet_aton(pIPAddr->IpAddress.String, &tmp_addr);
45 *pdns_addr = tmp_addr;
46 Log(("nat: DNS Servers:\n"));
47 Log(("nat: DNS Addr:%s\n", pIPAddr->IpAddress.String));
48
49 pIPAddr = FixedInfo -> DnsServerList.Next;
50 while ( pIPAddr ) {
51 Log(("nat: DNS Addr:%s\n", pIPAddr ->IpAddress.String));
52 pIPAddr = pIPAddr ->Next;
53 }
54 if (FixedInfo) {
55 GlobalFree(FixedInfo);
56 FixedInfo = NULL;
57 }
58 return 0;
59}
60
61#else
62
63static int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
64{
65 char buff[512];
66 char buff2[256];
67 FILE *f;
68 int found = 0;
69 struct in_addr tmp_addr;
70
71#ifdef __OS2__
72 /* Try various locations. */
73 char *etc = getenv("ETC");
74 f = NULL;
75 if (etc)
76 {
77 snprintf(buff, sizeof(buff), "%s/RESOLV2", etc);
78 f = fopen(buff, "rt");
79 }
80 if (!f) {
81 snprintf(buff, sizeof(buff), "%s/RESOLV2", _PATH_ETC);
82 f = fopen(buff, "rt");
83 }
84 if (!f) {
85 snprintf(buff, sizeof(buff), "%s/resolv.conf", _PATH_ETC);
86 f = fopen(buff, "rt");
87 }
88#else
89 f = fopen("/etc/resolv.conf", "r");
90#endif
91 if (!f)
92 return -1;
93
94 Log(("nat: IP address of your DNS(s): \n"));
95 while (fgets(buff, 512, f) != NULL) {
96 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1) {
97 if (!inet_aton(buff2, &tmp_addr))
98 continue;
99 if (tmp_addr.s_addr == loopback_addr.s_addr)
100 tmp_addr = our_addr;
101 /* If it's the first one, set it to dns_addr */
102 if (!found)
103 *pdns_addr = tmp_addr;
104 if (++found > 3) {
105 Log(("nat: (more)\n"));
106 break;
107 } else
108 Log(("nat: %s\n", inet_ntoa(tmp_addr)));
109 }
110 }
111 fclose(f);
112 if (!found)
113 return -1;
114 return 0;
115}
116
117#endif
118
119int slirp_init(PNATState *ppData, const char *pszNetAddr, void *pvUser)
120{
121 PNATState pData = malloc(sizeof(NATState));
122 *ppData = pData;
123 if (!pData)
124 return VERR_NO_MEMORY;
125 memset(pData, '\0', sizeof(NATState));
126 pData->pvUser = pvUser;
127#if ARCH_BITS == 64
128 pData->cpvHashUsed = 1;
129#endif
130
131#ifdef _WIN32
132 {
133 WSADATA Data;
134 WSAStartup(MAKEWORD(2,0), &Data);
135 }
136#endif
137
138 Assert(sizeof(struct ip) == 20);
139 link_up = 1;
140
141 if_init(pData);
142 ip_init(pData);
143
144 /* Initialise mbufs *after* setting the MTU */
145 m_init(pData);
146
147 /* set default addresses */
148 inet_aton("127.0.0.1", &loopback_addr);
149
150 if (get_dns_addr(pData, &dns_addr) < 0) {
151 return VERR_NAT_DNS;
152 }
153
154 inet_aton(pszNetAddr, &special_addr);
155 alias_addr.s_addr = special_addr.s_addr | htonl(CTL_ALIAS);
156 getouraddr(pData);
157 return VINF_SUCCESS;
158}
159
160/**
161 * Marks the link as up, making it possible to establish new connections.
162 */
163void slirp_link_up(PNATState pData)
164{
165 link_up = 1;
166}
167
168/**
169 * Marks the link as down and cleans up the current connections.
170 */
171void slirp_link_down(PNATState pData)
172{
173 struct socket *so;
174
175 while ((so = tcb.so_next) != &tcb)
176 {
177 if (so->so_state & SS_NOFDREF || so->s == -1)
178 sofree(pData, so);
179 else
180 tcp_drop(pData, sototcpcb(so), 0);
181 }
182
183 while ((so = udb.so_next) != &udb)
184 udp_detach(pData, so);
185
186 link_up = 0;
187}
188
189/**
190 * Terminates the slirp component.
191 */
192void slirp_term(PNATState pData)
193{
194#if ARCH_BITS == 64
195 LogRel(("NAT: cpvHashUsed=%RU32 cpvHashCollisions=%RU32 cpvHashInserts=%RU64 cpvHashDone=%RU64\n",
196 pData->cpvHashUsed, pData->cpvHashCollisions, pData->cpvHashInserts, pData->cpvHashDone));
197#endif
198
199 slirp_link_down(pData);
200#ifdef WIN32
201 WSACleanup();
202#endif
203#ifdef LOG_ENABLED
204 Log(("\n"
205 "NAT statistics\n"
206 "--------------\n"
207 "\n"));
208 ipstats(pData);
209 tcpstats(pData);
210 udpstats(pData);
211 icmpstats(pData);
212 mbufstats(pData);
213 sockstats(pData);
214 Log(("\n"
215 "\n"
216 "\n"));
217#endif
218 free(pData);
219}
220
221
222#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
223#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
224#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)
225
226/*
227 * curtime kept to an accuracy of 1ms
228 */
229#ifdef _WIN32
230static void updtime(PNATState pData)
231{
232 struct _timeb tb;
233
234 _ftime(&tb);
235 curtime = (u_int)tb.time * (u_int)1000;
236 curtime += (u_int)tb.millitm;
237}
238#else
239static void updtime(PNATState pData)
240{
241 gettimeofday(&tt, 0);
242
243 curtime = (u_int)tt.tv_sec * (u_int)1000;
244 curtime += (u_int)tt.tv_usec / (u_int)1000;
245
246 if ((tt.tv_usec % 1000) >= 500)
247 curtime++;
248}
249#endif
250
251void slirp_select_fill(PNATState pData, int *pnfds,
252 fd_set *readfds, fd_set *writefds, fd_set *xfds)
253{
254 struct socket *so, *so_next;
255 struct timeval timeout;
256 int nfds;
257 int tmp_time;
258
259 nfds = *pnfds;
260 /*
261 * First, TCP sockets
262 */
263 do_slowtimo = 0;
264 if (link_up) {
265 /*
266 * *_slowtimo needs calling if there are IP fragments
267 * in the fragment queue, or there are TCP connections active
268 */
269 do_slowtimo = ((tcb.so_next != &tcb) ||
270 ((struct ipasfrag *)&ipq != u32_to_ptr(pData, ipq.next, struct ipasfrag *)));
271
272 for (so = tcb.so_next; so != &tcb; so = so_next) {
273 so_next = so->so_next;
274
275 /*
276 * See if we need a tcp_fasttimo
277 */
278 if (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)
279 time_fasttimo = curtime; /* Flag when we want a fasttimo */
280
281 /*
282 * NOFDREF can include still connecting to local-host,
283 * newly socreated() sockets etc. Don't want to select these.
284 */
285 if (so->so_state & SS_NOFDREF || so->s == -1)
286 continue;
287
288 /*
289 * Set for reading sockets which are accepting
290 */
291 if (so->so_state & SS_FACCEPTCONN) {
292 FD_SET(so->s, readfds);
293 UPD_NFDS(so->s);
294 continue;
295 }
296
297 /*
298 * Set for writing sockets which are connecting
299 */
300 if (so->so_state & SS_ISFCONNECTING) {
301 FD_SET(so->s, writefds);
302 UPD_NFDS(so->s);
303 continue;
304 }
305
306 /*
307 * Set for writing if we are connected, can send more, and
308 * we have something to send
309 */
310 if (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {
311 FD_SET(so->s, writefds);
312 UPD_NFDS(so->s);
313 }
314
315 /*
316 * Set for reading (and urgent data) if we are connected, can
317 * receive more, and we have room for it XXX /2 ?
318 */
319 if (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {
320 FD_SET(so->s, readfds);
321 FD_SET(so->s, xfds);
322 UPD_NFDS(so->s);
323 }
324 }
325
326 /*
327 * UDP sockets
328 */
329 for (so = udb.so_next; so != &udb; so = so_next) {
330 so_next = so->so_next;
331
332 /*
333 * See if it's timed out
334 */
335 if (so->so_expire) {
336 if (so->so_expire <= curtime) {
337 udp_detach(pData, so);
338 continue;
339 } else
340 do_slowtimo = 1; /* Let socket expire */
341 }
342
343 /*
344 * When UDP packets are received from over the
345 * link, they're sendto()'d straight away, so
346 * no need for setting for writing
347 * Limit the number of packets queued by this session
348 * to 4. Note that even though we try and limit this
349 * to 4 packets, the session could have more queued
350 * if the packets needed to be fragmented
351 * (XXX <= 4 ?)
352 */
353 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {
354 FD_SET(so->s, readfds);
355 UPD_NFDS(so->s);
356 }
357 }
358 }
359
360 /*
361 * Setup timeout to use minimum CPU usage, especially when idle
362 */
363
364 /*
365 * First, see the timeout needed by *timo
366 */
367 timeout.tv_sec = 0;
368 timeout.tv_usec = -1;
369 /*
370 * If a slowtimo is needed, set timeout to 500ms from the last
371 * slow timeout. If a fast timeout is needed, set timeout within
372 * 200ms of when it was requested.
373 */
374 if (do_slowtimo) {
375 /* XXX + 10000 because some select()'s aren't that accurate */
376 timeout.tv_usec = ((500 - (curtime - last_slowtimo)) * 1000) + 10000;
377 if (timeout.tv_usec < 0)
378 timeout.tv_usec = 0;
379 else if (timeout.tv_usec > 510000)
380 timeout.tv_usec = 510000;
381
382 /* Can only fasttimo if we also slowtimo */
383 if (time_fasttimo) {
384 tmp_time = (200 - (curtime - time_fasttimo)) * 1000;
385 if (tmp_time < 0)
386 tmp_time = 0;
387
388 /* Choose the smallest of the 2 */
389 if (tmp_time < timeout.tv_usec)
390 timeout.tv_usec = (u_int)tmp_time;
391 }
392 }
393 *pnfds = nfds;
394}
395
396void slirp_select_poll(PNATState pData, fd_set *readfds, fd_set *writefds, fd_set *xfds)
397{
398 struct socket *so, *so_next;
399 int ret;
400
401 /* Update time */
402 updtime(pData);
403
404 /*
405 * See if anything has timed out
406 */
407 if (link_up) {
408 if (time_fasttimo && ((curtime - time_fasttimo) >= 2)) {
409 tcp_fasttimo(pData);
410 time_fasttimo = 0;
411 }
412 if (do_slowtimo && ((curtime - last_slowtimo) >= 499)) {
413 ip_slowtimo(pData);
414 tcp_slowtimo(pData);
415 last_slowtimo = curtime;
416 }
417 }
418
419 /*
420 * Check sockets
421 */
422 if (link_up) {
423 /*
424 * Check TCP sockets
425 */
426 for (so = tcb.so_next; so != &tcb; so = so_next) {
427 so_next = so->so_next;
428
429 /*
430 * FD_ISSET is meaningless on these sockets
431 * (and they can crash the program)
432 */
433 if (so->so_state & SS_NOFDREF || so->s == -1)
434 continue;
435
436 /*
437 * Check for URG data
438 * This will soread as well, so no need to
439 * test for readfds below if this succeeds
440 */
441 if (FD_ISSET(so->s, xfds))
442 sorecvoob(pData, so);
443 /*
444 * Check sockets for reading
445 */
446 else if (FD_ISSET(so->s, readfds)) {
447 /*
448 * Check for incoming connections
449 */
450 if (so->so_state & SS_FACCEPTCONN) {
451 tcp_connect(pData, so);
452 continue;
453 } /* else */
454 ret = soread(pData, so);
455
456 /* Output it if we read something */
457 if (ret > 0)
458 tcp_output(pData, sototcpcb(so));
459 }
460
461 /*
462 * Check sockets for writing
463 */
464 if (FD_ISSET(so->s, writefds)) {
465 /*
466 * Check for non-blocking, still-connecting sockets
467 */
468 if (so->so_state & SS_ISFCONNECTING) {
469 /* Connected */
470 so->so_state &= ~SS_ISFCONNECTING;
471
472 ret = send(so->s, &ret, 0, 0);
473 if (ret < 0) {
474 /* XXXXX Must fix, zero bytes is a NOP */
475 if (errno == EAGAIN || errno == EWOULDBLOCK ||
476 errno == EINPROGRESS || errno == ENOTCONN)
477 continue;
478
479 /* else failed */
480 so->so_state = SS_NOFDREF;
481 }
482 /* else so->so_state &= ~SS_ISFCONNECTING; */
483
484 /*
485 * Continue tcp_input
486 */
487 tcp_input(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
488 /* continue; */
489 } else
490 ret = sowrite(pData, so);
491 /*
492 * XXXXX If we wrote something (a lot), there
493 * could be a need for a window update.
494 * In the worst case, the remote will send
495 * a window probe to get things going again
496 */
497 }
498
499 /*
500 * Probe a still-connecting, non-blocking socket
501 * to check if it's still alive
502 */
503#ifdef PROBE_CONN
504 if (so->so_state & SS_ISFCONNECTING) {
505 ret = recv(so->s, (char *)&ret, 0,0);
506
507 if (ret < 0) {
508 /* XXX */
509 if (errno == EAGAIN || errno == EWOULDBLOCK ||
510 errno == EINPROGRESS || errno == ENOTCONN)
511 continue; /* Still connecting, continue */
512
513 /* else failed */
514 so->so_state = SS_NOFDREF;
515
516 /* tcp_input will take care of it */
517 } else {
518 ret = send(so->s, &ret, 0,0);
519 if (ret < 0) {
520 /* XXX */
521 if (errno == EAGAIN || errno == EWOULDBLOCK ||
522 errno == EINPROGRESS || errno == ENOTCONN)
523 continue;
524 /* else failed */
525 so->so_state = SS_NOFDREF;
526 } else
527 so->so_state &= ~SS_ISFCONNECTING;
528
529 }
530 tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);
531 } /* SS_ISFCONNECTING */
532#endif
533 }
534
535 /*
536 * Now UDP sockets.
537 * Incoming packets are sent straight away, they're not buffered.
538 * Incoming UDP data isn't buffered either.
539 */
540 for (so = udb.so_next; so != &udb; so = so_next) {
541 so_next = so->so_next;
542
543 if (so->s != -1 && FD_ISSET(so->s, readfds)) {
544 sorecvfrom(pData, so);
545 }
546 }
547 }
548
549 /*
550 * See if we can start outputting
551 */
552 if (if_queued && link_up)
553 if_start(pData);
554}
555
556#define ETH_ALEN 6
557#define ETH_HLEN 14
558
559#define ETH_P_IP 0x0800 /* Internet Protocol packet */
560#define ETH_P_ARP 0x0806 /* Address Resolution packet */
561
562#define ARPOP_REQUEST 1 /* ARP request */
563#define ARPOP_REPLY 2 /* ARP reply */
564
565struct ethhdr
566{
567 unsigned char h_dest[ETH_ALEN]; /* destination eth addr */
568 unsigned char h_source[ETH_ALEN]; /* source ether addr */
569 unsigned short h_proto; /* packet type ID field */
570};
571
572struct arphdr
573{
574 unsigned short ar_hrd; /* format of hardware address */
575 unsigned short ar_pro; /* format of protocol address */
576 unsigned char ar_hln; /* length of hardware address */
577 unsigned char ar_pln; /* length of protocol address */
578 unsigned short ar_op; /* ARP opcode (command) */
579
580 /*
581 * Ethernet looks like this : This bit is variable sized however...
582 */
583 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
584 unsigned char ar_sip[4]; /* sender IP address */
585 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
586 unsigned char ar_tip[4]; /* target IP address */
587};
588
589static
590void arp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
591{
592 struct ethhdr *eh = (struct ethhdr *)pkt;
593 struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);
594 uint8_t arp_reply[ETH_HLEN + sizeof(struct arphdr)];
595 struct ethhdr *reh = (struct ethhdr *)arp_reply;
596 struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);
597 int ar_op;
598 struct ex_list *ex_ptr;
599
600 ar_op = ntohs(ah->ar_op);
601 switch(ar_op) {
602 case ARPOP_REQUEST:
603 if (!memcmp(ah->ar_tip, &special_addr, 3)) {
604 if (ah->ar_tip[3] == CTL_DNS || ah->ar_tip[3] == CTL_ALIAS)
605 goto arp_ok;
606 for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
607 if (ex_ptr->ex_addr == ah->ar_tip[3])
608 goto arp_ok;
609 }
610 return;
611 arp_ok:
612 /* XXX: make an ARP request to have the client address */
613 memcpy(client_ethaddr, eh->h_source, ETH_ALEN);
614
615 /* ARP request for alias/dns mac address */
616 memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);
617 memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 1);
618 reh->h_source[5] = ah->ar_tip[3];
619 reh->h_proto = htons(ETH_P_ARP);
620
621 rah->ar_hrd = htons(1);
622 rah->ar_pro = htons(ETH_P_IP);
623 rah->ar_hln = ETH_ALEN;
624 rah->ar_pln = 4;
625 rah->ar_op = htons(ARPOP_REPLY);
626 memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);
627 memcpy(rah->ar_sip, ah->ar_tip, 4);
628 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
629 memcpy(rah->ar_tip, ah->ar_sip, 4);
630 slirp_output(pData->pvUser, arp_reply, sizeof(arp_reply));
631 }
632 break;
633 default:
634 break;
635 }
636}
637
638void slirp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
639{
640 struct mbuf *m;
641 int proto;
642
643 if (pkt_len < ETH_HLEN)
644 return;
645
646 proto = ntohs(*(uint16_t *)(pkt + 12));
647 switch(proto) {
648 case ETH_P_ARP:
649 arp_input(pData, pkt, pkt_len);
650 break;
651 case ETH_P_IP:
652 m = m_get(pData);
653 if (!m)
654 return;
655 /* Note: we add to align the IP header */
656 m->m_len = pkt_len + 2;
657 memcpy(m->m_data + 2, pkt, pkt_len);
658
659 m->m_data += 2 + ETH_HLEN;
660 m->m_len -= 2 + ETH_HLEN;
661
662 ip_input(pData, m);
663 break;
664 default:
665 break;
666 }
667}
668
669/* output the IP packet to the ethernet device */
670void if_encap(PNATState pData, const uint8_t *ip_data, int ip_data_len)
671{
672 uint8_t buf[1600];
673 struct ethhdr *eh = (struct ethhdr *)buf;
674
675 if (ip_data_len + ETH_HLEN > sizeof(buf))
676 return;
677
678 memcpy(eh->h_dest, client_ethaddr, ETH_ALEN);
679 memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 1);
680 /* XXX: not correct */
681 eh->h_source[5] = CTL_ALIAS;
682 eh->h_proto = htons(ETH_P_IP);
683 memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);
684 slirp_output(pData->pvUser, buf, ip_data_len + ETH_HLEN);
685}
686
687int slirp_redir(PNATState pData, int is_udp, int host_port,
688 struct in_addr guest_addr, int guest_port)
689{
690 if (is_udp) {
691 if (!udp_listen(pData, htons(host_port), guest_addr.s_addr,
692 htons(guest_port), 0))
693 return -1;
694 } else {
695 if (!solisten(pData, htons(host_port), guest_addr.s_addr,
696 htons(guest_port), 0))
697 return -1;
698 }
699 return 0;
700}
701
702int slirp_add_exec(PNATState pData, int do_pty, const char *args, int addr_low_byte,
703 int guest_port)
704{
705 return add_exec(&exec_list, do_pty, (char *)args,
706 addr_low_byte, htons(guest_port));
707}
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette