VirtualBox

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

Last change on this file since 15194 was 15194, checked in by vboxsync, 16 years ago

Slirp:ICMP: Proper shutdowning of ICMP raw socket on Unix and ICMP file handle on Windows

  • Property svn:eol-style set to native
File size: 33.4 KB
Line 
1#include "slirp.h"
2#ifdef RT_OS_OS2
3# include <paths.h>
4#endif
5
6/* disable these counters for the final release */
7/* #define VBOX_WITHOUT_RELEASE_STATISTICS */
8
9#include <VBox/err.h>
10#include <VBox/pdmdrv.h>
11#include <iprt/assert.h>
12
13#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
14# define DO_ENGAGE_EVENT1(so, fdset, label) \
15 do { \
16 FD_SET((so)->s, (fdset)); \
17 UPD_NFDS((so)->s); \
18 } while(0)
19
20
21# define DO_ENGAGE_EVENT2(so, fdset0, fdset1, label) \
22 do { \
23 FD_SET((so)->s, (fdset0)); \
24 FD_SET((so)->s, (fdset1)); \
25 UPD_NFDS((so)->s); \
26 } while(0)
27#else /* defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS) */
28# define DO_ENGAGE_EVENT1(so, fdset0, label) \
29 do { \
30 rc = WSAEventSelect((so)->s, VBOX_SOCKET_EVENT, FD_ALL_EVENTS); \
31 if (rc == SOCKET_ERROR) \
32 { \
33 /* This should not happen */ \
34 error = WSAGetLastError(); \
35 LogRel(("WSAEventSelector (" #label ") error %d (so=%x, socket=%s, event=%x)\n", \
36 error, (so), (so)->s, VBOX_SOCKET_EVENT)); \
37 } \
38 } while(0)
39
40# define DO_ENGAGE_EVENT2(so, fdset0, fdset1, label) DO_ENGAGE_EVENT1((so), (fdset0), label)
41#endif /* defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS) */
42
43# define TCP_ENGAGE_EVENT1(so, fdset0) \
44 DO_ENGAGE_EVENT1((so), (fdset0), TCP)
45
46# define TCP_ENGAGE_EVENT2(so, fdset0, fdset1) \
47 DO_ENGAGE_EVENT2((so), (fdset0), (fdset1), TCP)
48
49#define UDP_ENGAGE_EVENT(so, fdset) \
50 DO_ENGAGE_EVENT1((so), (fdset), UDP)
51
52static const uint8_t special_ethaddr[6] = {
53 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
54};
55
56#ifdef RT_OS_WINDOWS
57
58static int get_dns_addr_domain(PNATState pData, bool fVerbose,
59 struct in_addr *pdns_addr,
60 const char **ppszDomain)
61{
62 int rc = 0;
63 FIXED_INFO *FixedInfo = NULL;
64 ULONG BufLen;
65 DWORD ret;
66 IP_ADDR_STRING *pIPAddr;
67 struct in_addr tmp_addr;
68
69 FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
70 BufLen = sizeof(FIXED_INFO);
71
72 /** @todo: this API returns all DNS servers, no matter whether the
73 * corresponding network adapter is disabled or not. Maybe replace
74 * this by GetAdapterAddresses(), which is XP/Vista only though. */
75 if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen))
76 {
77 if (FixedInfo)
78 {
79 GlobalFree(FixedInfo);
80 FixedInfo = NULL;
81 }
82 FixedInfo = GlobalAlloc(GPTR, BufLen);
83 }
84
85 if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS)
86 {
87 Log(("GetNetworkParams failed. ret = %08x\n", (u_int)ret ));
88 if (FixedInfo)
89 {
90 GlobalFree(FixedInfo);
91 FixedInfo = NULL;
92 }
93 rc = -1;
94 goto get_dns_prefix;
95 }
96
97 pIPAddr = &(FixedInfo->DnsServerList);
98 inet_aton(pIPAddr->IpAddress.String, &tmp_addr);
99 Log(("nat: DNS Servers:\n"));
100 if (fVerbose || pdns_addr->s_addr != tmp_addr.s_addr)
101 LogRel(("NAT: DNS address: %s\n", pIPAddr->IpAddress.String));
102 *pdns_addr = tmp_addr;
103
104 pIPAddr = FixedInfo -> DnsServerList.Next;
105 while (pIPAddr)
106 {
107 if (fVerbose)
108 LogRel(("NAT: ignored DNS address: %s\n", pIPAddr ->IpAddress.String));
109 pIPAddr = pIPAddr ->Next;
110 }
111 if (FixedInfo)
112 {
113 GlobalFree(FixedInfo);
114 FixedInfo = NULL;
115 }
116
117get_dns_prefix:
118 if (ppszDomain)
119 {
120 OSVERSIONINFO ver;
121 char szDnsDomain[256];
122 DWORD dwSize = sizeof(szDnsDomain);
123
124 *ppszDomain = NULL;
125 GetVersionEx(&ver);
126 if (ver.dwMajorVersion >= 5)
127 {
128 /* GetComputerNameEx exists in Windows versions starting with 2000. */
129 if (GetComputerNameEx(ComputerNameDnsDomain, szDnsDomain, &dwSize))
130 {
131 if (szDnsDomain[0])
132 {
133 /* Just non-empty strings are valid. */
134 *ppszDomain = RTStrDup(szDnsDomain);
135 if (pData->fPassDomain)
136 {
137 if (fVerbose)
138 LogRel(("NAT: passing domain name %s\n", szDnsDomain));
139 }
140 else
141 Log(("nat: ignoring domain %s\n", szDnsDomain));
142 }
143 }
144 else
145 Log(("nat: GetComputerNameEx failed (%d)\n", GetLastError()));
146 }
147 }
148 return rc;
149}
150
151#else
152
153static int get_dns_addr_domain(PNATState pData, bool fVerbose,
154 struct in_addr *pdns_addr,
155 const char **ppszDomain)
156{
157 char buff[512];
158 char buff2[256];
159 FILE *f;
160 int found = 0;
161 struct in_addr tmp_addr;
162
163#ifdef RT_OS_OS2
164 /* Try various locations. */
165 char *etc = getenv("ETC");
166 f = NULL;
167 if (etc)
168 {
169 snprintf(buff, sizeof(buff), "%s/RESOLV2", etc);
170 f = fopen(buff, "rt");
171 }
172 if (!f)
173 {
174 snprintf(buff, sizeof(buff), "%s/RESOLV2", _PATH_ETC);
175 f = fopen(buff, "rt");
176 }
177 if (!f)
178 {
179 snprintf(buff, sizeof(buff), "%s/resolv.conf", _PATH_ETC);
180 f = fopen(buff, "rt");
181 }
182#else
183 f = fopen("/etc/resolv.conf", "r");
184#endif
185 if (!f)
186 return -1;
187
188 if (ppszDomain)
189 *ppszDomain = NULL;
190 Log(("nat: DNS Servers:\n"));
191 while (fgets(buff, 512, f) != NULL)
192 {
193 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1)
194 {
195 if (!inet_aton(buff2, &tmp_addr))
196 continue;
197 if (tmp_addr.s_addr == loopback_addr.s_addr)
198 tmp_addr = our_addr;
199 /* If it's the first one, set it to dns_addr */
200 if (!found)
201 {
202 if (fVerbose || pdns_addr->s_addr != tmp_addr.s_addr)
203 LogRel(("NAT: DNS address: %s\n", buff2));
204 *pdns_addr = tmp_addr;
205 }
206 else
207 {
208 if (fVerbose)
209 LogRel(("NAT: ignored DNS address: %s\n", buff2));
210 }
211 found++;
212 }
213 if ( ppszDomain
214 && (!strncmp(buff, "domain", 6) || !strncmp(buff, "search", 6)))
215 {
216 /* Domain name/search list present. Pick first entry */
217 if (*ppszDomain == NULL)
218 {
219 char *tok;
220 char *saveptr;
221 tok = strtok_r(&buff[6], " \t\n", &saveptr);
222 if (tok)
223 {
224 *ppszDomain = RTStrDup(tok);
225 if (pData->fPassDomain)
226 {
227 if (fVerbose)
228 LogRel(("NAT: passing domain name %s\n", tok));
229 }
230 else
231 Log(("nat: ignoring domain %s\n", tok));
232 }
233 }
234 }
235 }
236 fclose(f);
237 if (!found)
238 return -1;
239 return 0;
240}
241
242#endif
243
244int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
245{
246 return get_dns_addr_domain(pData, false, pdns_addr, NULL);
247}
248
249int slirp_init(PNATState *ppData, const char *pszNetAddr, uint32_t u32Netmask,
250 bool fPassDomain, const char *pszTFTPPrefix,
251 const char *pszBootFile, void *pvUser)
252{
253 int fNATfailed = 0;
254 PNATState pData = malloc(sizeof(NATState));
255 *ppData = pData;
256 if (!pData)
257 return VERR_NO_MEMORY;
258 if (u32Netmask & 0x1f)
259 /* CTL is x.x.x.15, bootp passes up to 16 IPs (15..31) */
260 return VERR_INVALID_PARAMETER;
261 memset(pData, '\0', sizeof(NATState));
262 pData->fPassDomain = fPassDomain;
263 pData->pvUser = pvUser;
264#if ARCH_BITS == 64 && !defined(VBOX_WITH_BSD_REASS)
265 pData->cpvHashUsed = 1;
266#endif
267 tftp_prefix = pszTFTPPrefix;
268 bootp_filename = pszBootFile;
269 pData->netmask = u32Netmask;
270
271#ifdef RT_OS_WINDOWS
272 {
273 WSADATA Data;
274 WSAStartup(MAKEWORD(2,0), &Data);
275 }
276# if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC)
277 pData->phEvents[VBOX_SOCKET_EVENT_INDEX] = CreateEvent(NULL, FALSE, FALSE, NULL);
278# endif
279#endif
280
281 link_up = 1;
282
283 debug_init();
284 if_init(pData);
285 ip_init(pData);
286#ifdef VBOX_WITH_SLIRP_ICMP
287 icmp_init(pData);
288#endif /* VBOX_WITH_SLIRP_ICMP */
289
290 /* Initialise mbufs *after* setting the MTU */
291 m_init(pData);
292
293 /* set default addresses */
294 inet_aton("127.0.0.1", &loopback_addr);
295 inet_aton("127.0.0.1", &dns_addr);
296
297 if (get_dns_addr_domain(pData, true, &dns_addr, &pData->pszDomain) < 0)
298 fNATfailed = 1;
299
300 inet_aton(pszNetAddr, &special_addr);
301 alias_addr.s_addr = special_addr.s_addr | htonl(CTL_ALIAS);
302 getouraddr(pData);
303 return fNATfailed ? VINF_NAT_DNS : VINF_SUCCESS;
304}
305
306/**
307 * Statistics counters.
308 */
309void slirp_register_timers(PNATState pData, PPDMDRVINS pDrvIns)
310{
311#ifndef VBOX_WITHOUT_RELEASE_STATISTICS
312 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatFill, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
313 STAMUNIT_TICKS_PER_CALL, "Profiling slirp fills", "/Drivers/NAT%d/Fill", pDrvIns->iInstance);
314 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatPoll, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
315 STAMUNIT_TICKS_PER_CALL, "Profiling slirp polls", "/Drivers/NAT%d/Poll", pDrvIns->iInstance);
316 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatFastTimer, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
317 STAMUNIT_TICKS_PER_CALL, "Profiling slirp fast timer", "/Drivers/NAT%d/TimerFast", pDrvIns->iInstance);
318 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatSlowTimer, STAMTYPE_PROFILE, STAMVISIBILITY_ALWAYS,
319 STAMUNIT_TICKS_PER_CALL, "Profiling slirp slow timer", "/Drivers/NAT%d/TimerSlow", pDrvIns->iInstance);
320 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatTCP, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
321 STAMUNIT_COUNT, "TCP sockets", "/Drivers/NAT%d/SockTCP", pDrvIns->iInstance);
322 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatTCPHot, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
323 STAMUNIT_COUNT, "TCP sockets active", "/Drivers/NAT%d/SockTCPHot", pDrvIns->iInstance);
324 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatUDP, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
325 STAMUNIT_COUNT, "UDP sockets", "/Drivers/NAT%d/SockUDP", pDrvIns->iInstance);
326 PDMDrvHlpSTAMRegisterF(pDrvIns, &pData->StatUDPHot, STAMTYPE_COUNTER, STAMVISIBILITY_ALWAYS,
327 STAMUNIT_COUNT, "UDP sockets active", "/Drivers/NAT%d/SockUDPHot", pDrvIns->iInstance);
328#endif /* VBOX_WITHOUT_RELEASE_STATISTICS */
329}
330
331/**
332 * Marks the link as up, making it possible to establish new connections.
333 */
334void slirp_link_up(PNATState pData)
335{
336 link_up = 1;
337}
338
339/**
340 * Marks the link as down and cleans up the current connections.
341 */
342void slirp_link_down(PNATState pData)
343{
344 struct socket *so;
345
346 while ((so = tcb.so_next) != &tcb)
347 {
348 if (so->so_state & SS_NOFDREF || so->s == -1)
349 sofree(pData, so);
350 else
351 tcp_drop(pData, sototcpcb(so), 0);
352 }
353
354 while ((so = udb.so_next) != &udb)
355 udp_detach(pData, so);
356
357 link_up = 0;
358}
359
360/**
361 * Terminates the slirp component.
362 */
363void slirp_term(PNATState pData)
364{
365 if (pData->pszDomain)
366 RTStrFree((char *)(void *)pData->pszDomain);
367
368#if ARCH_BITS == 64 && !defined(VBOX_WITH_BSD_REASS)
369 LogRel(("NAT: cpvHashUsed=%RU32 cpvHashCollisions=%RU32 cpvHashInserts=%RU64 cpvHashDone=%RU64\n",
370 pData->cpvHashUsed, pData->cpvHashCollisions, pData->cpvHashInserts, pData->cpvHashDone));
371#endif
372
373#ifdef VBOX_WITH_SLIRP_ICMP
374# ifdef RT_OS_WINDOWS
375 pData->pfIcmpCloseHandle(pData->icmp_socket.sh);
376# else
377 closesocket(pData->icmp_socket.s);
378# endif
379#endif
380
381 slirp_link_down(pData);
382#ifdef RT_OS_WINDOWS
383 WSACleanup();
384#endif
385#ifdef LOG_ENABLED
386 Log(("\n"
387 "NAT statistics\n"
388 "--------------\n"
389 "\n"));
390 ipstats(pData);
391 tcpstats(pData);
392 udpstats(pData);
393 icmpstats(pData);
394 mbufstats(pData);
395 sockstats(pData);
396 Log(("\n"
397 "\n"
398 "\n"));
399#endif
400 free(pData);
401}
402
403
404#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
405#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
406#define UPD_NFDS(x) if (nfds < (x)) nfds = (x)
407
408/*
409 * curtime kept to an accuracy of 1ms
410 */
411#ifdef RT_OS_WINDOWS
412static void updtime(PNATState pData)
413{
414 struct _timeb tb;
415
416 _ftime(&tb);
417 curtime = (u_int)tb.time * (u_int)1000;
418 curtime += (u_int)tb.millitm;
419}
420#else
421static void updtime(PNATState pData)
422{
423 gettimeofday(&tt, 0);
424
425 curtime = (u_int)tt.tv_sec * (u_int)1000;
426 curtime += (u_int)tt.tv_usec / (u_int)1000;
427
428 if ((tt.tv_usec % 1000) >= 500)
429 curtime++;
430}
431#endif
432
433void slirp_select_fill(PNATState pData, int *pnfds,
434 fd_set *readfds, fd_set *writefds, fd_set *xfds)
435{
436 struct socket *so, *so_next;
437 int nfds;
438#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
439 int rc;
440 int error;
441#endif
442#ifdef VBOX_WITH_BSD_REASS
443 int i;
444#endif /* VBOX_WITH_BSD_REASS */
445
446 STAM_REL_PROFILE_START(&pData->StatFill, a);
447
448 nfds = *pnfds;
449
450 /*
451 * First, TCP sockets
452 */
453 do_slowtimo = 0;
454 if (link_up)
455 {
456 /*
457 * *_slowtimo needs calling if there are IP fragments
458 * in the fragment queue, or there are TCP connections active
459 */
460#ifndef VBOX_WITH_BSD_REASS
461 do_slowtimo = ((tcb.so_next != &tcb)
462 || ((struct ipasfrag *)&ipq != u32_to_ptr(pData, ipq.next, struct ipasfrag *)));
463#else /* !VBOX_WITH_BSD_REASS */
464 /* XXX:
465 * triggering of fragment expiration should be the same but use new macroses
466 */
467 do_slowtimo = (tcb.so_next != &tcb);
468 if (!do_slowtimo)
469 {
470 for (i = 0; i < IPREASS_NHASH; i++)
471 {
472 if (!TAILQ_EMPTY(&ipq[i]))
473 {
474 do_slowtimo = 1;
475 break;
476 }
477 }
478 }
479#endif /* VBOX_WITH_BSD_REASS */
480
481 STAM_REL_COUNTER_RESET(&pData->StatTCP);
482 STAM_REL_COUNTER_RESET(&pData->StatTCPHot);
483
484 for (so = tcb.so_next; so != &tcb; so = so_next)
485 {
486 so_next = so->so_next;
487
488 STAM_REL_COUNTER_INC(&pData->StatTCP);
489
490 /*
491 * See if we need a tcp_fasttimo
492 */
493 if (time_fasttimo == 0 && so->so_tcpcb->t_flags & TF_DELACK)
494 time_fasttimo = curtime; /* Flag when we want a fasttimo */
495
496 /*
497 * NOFDREF can include still connecting to local-host,
498 * newly socreated() sockets etc. Don't want to select these.
499 */
500 if (so->so_state & SS_NOFDREF || so->s == -1)
501 continue;
502
503 /*
504 * Set for reading sockets which are accepting
505 */
506 if (so->so_state & SS_FACCEPTCONN)
507 {
508 STAM_REL_COUNTER_INC(&pData->StatTCPHot);
509 TCP_ENGAGE_EVENT1(so, readfds);
510 continue;
511 }
512
513 /*
514 * Set for writing sockets which are connecting
515 */
516 if (so->so_state & SS_ISFCONNECTING)
517 {
518 STAM_REL_COUNTER_INC(&pData->StatTCPHot);
519 TCP_ENGAGE_EVENT1(so, writefds);
520 }
521
522 /*
523 * Set for writing if we are connected, can send more, and
524 * we have something to send
525 */
526 if (CONN_CANFSEND(so) && so->so_rcv.sb_cc)
527 {
528 STAM_REL_COUNTER_INC(&pData->StatTCPHot);
529 TCP_ENGAGE_EVENT1(so, writefds);
530 }
531
532 /*
533 * Set for reading (and urgent data) if we are connected, can
534 * receive more, and we have room for it XXX /2 ?
535 */
536 if (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2)))
537 {
538 STAM_REL_COUNTER_INC(&pData->StatTCPHot);
539 TCP_ENGAGE_EVENT2(so, readfds, xfds);
540 }
541 }
542
543 /*
544 * UDP sockets
545 */
546 STAM_REL_COUNTER_RESET(&pData->StatUDP);
547 STAM_REL_COUNTER_RESET(&pData->StatUDPHot);
548
549 for (so = udb.so_next; so != &udb; so = so_next)
550 {
551 so_next = so->so_next;
552
553 STAM_REL_COUNTER_INC(&pData->StatUDP);
554
555 /*
556 * See if it's timed out
557 */
558 if (so->so_expire)
559 {
560 if (so->so_expire <= curtime)
561 {
562 udp_detach(pData, so);
563 continue;
564 }
565 else
566 do_slowtimo = 1; /* Let socket expire */
567 }
568
569 /*
570 * When UDP packets are received from over the link, they're
571 * sendto()'d straight away, so no need for setting for writing
572 * Limit the number of packets queued by this session to 4.
573 * Note that even though we try and limit this to 4 packets,
574 * the session could have more queued if the packets needed
575 * to be fragmented.
576 *
577 * (XXX <= 4 ?)
578 */
579 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4)
580 {
581 STAM_REL_COUNTER_INC(&pData->StatUDPHot);
582 UDP_ENGAGE_EVENT(so, readfds);
583 }
584 }
585 }
586
587#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
588 *pnfds = nfds;
589#else
590 *pnfds = VBOX_EVENT_COUNT;
591#endif
592
593 STAM_REL_PROFILE_STOP(&pData->StatFill, a);
594}
595
596void slirp_select_poll(PNATState pData, fd_set *readfds, fd_set *writefds, fd_set *xfds)
597{
598 struct socket *so, *so_next;
599 int ret;
600#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
601 WSANETWORKEVENTS NetworkEvents;
602 int rc;
603 int error;
604#endif
605 static uint32_t stat_time;
606
607 STAM_REL_PROFILE_START(&pData->StatPoll, a);
608
609 /* Update time */
610 updtime(pData);
611
612#ifdef LOG_ENABLED
613 if (curtime - stat_time > 10000)
614 {
615 stat_time = curtime;
616 sockstats(pData);
617 }
618#endif
619
620 /*
621 * See if anything has timed out
622 */
623 if (link_up)
624 {
625 if (time_fasttimo && ((curtime - time_fasttimo) >= 2))
626 {
627 STAM_REL_PROFILE_START(&pData->StatFastTimer, a);
628 tcp_fasttimo(pData);
629 time_fasttimo = 0;
630 STAM_REL_PROFILE_STOP(&pData->StatFastTimer, a);
631 }
632 if (do_slowtimo && ((curtime - last_slowtimo) >= 499))
633 {
634 STAM_REL_PROFILE_START(&pData->StatSlowTimer, a);
635 ip_slowtimo(pData);
636 tcp_slowtimo(pData);
637 last_slowtimo = curtime;
638 STAM_REL_PROFILE_STOP(&pData->StatSlowTimer, a);
639 }
640 }
641#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
642 if (!readfds && !writefds && !xfds)
643 return; /* only timer update */
644#endif
645
646 /*
647 * Check sockets
648 */
649 if (link_up)
650 {
651 /*
652 * Check TCP sockets
653 */
654 for (so = tcb.so_next; so != &tcb; so = so_next)
655 {
656 so_next = so->so_next;
657
658 /*
659 * FD_ISSET is meaningless on these sockets
660 * (and they can crash the program)
661 */
662 if (so->so_state & SS_NOFDREF || so->s == -1)
663 continue;
664
665#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
666 rc = WSAEnumNetworkEvents(so->s, VBOX_SOCKET_EVENT, &NetworkEvents);
667 if (rc == SOCKET_ERROR)
668 {
669 error = WSAGetLastError();
670 LogRel(("WSAEnumNetworkEvents TCP error %d\n", error));
671 continue;
672 }
673#endif
674
675 /*
676 * Check for URG data
677 * This will soread as well, so no need to
678 * test for readfds below if this succeeds
679 */
680#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
681 if (FD_ISSET(so->s, xfds))
682#else
683 /* out-of-band data */
684 if ((NetworkEvents.lNetworkEvents & FD_OOB) && NetworkEvents.iErrorCode[FD_OOB_BIT] == 0)
685#endif
686 {
687 sorecvoob(pData, so);
688 }
689
690 /*
691 * Check sockets for reading
692 */
693#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
694 else if (FD_ISSET(so->s, readfds))
695#else
696 else if ((NetworkEvents.lNetworkEvents & FD_READ) && (NetworkEvents.iErrorCode[FD_READ_BIT] == 0))
697#endif
698 {
699 /*
700 * Check for incoming connections
701 */
702 if (so->so_state & SS_FACCEPTCONN)
703 {
704 tcp_connect(pData, so);
705#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
706 if (!NetworkEvents.lNetworkEvents & FD_CLOSE)
707#endif
708 continue;
709 }
710
711 ret = soread(pData, so);
712 /* Output it if we read something */
713 if (ret > 0)
714 tcp_output(pData, sototcpcb(so));
715 }
716
717#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
718 /*
719 * Check for FD_CLOSE events.
720 */
721 if (NetworkEvents.lNetworkEvents & FD_CLOSE)
722 {
723 /*
724 * drain the socket
725 */
726 for (;;)
727 {
728 ret = soread(pData, so);
729 if (ret > 0)
730 tcp_output(pData, sototcpcb(so));
731 else
732 break;
733 }
734 }
735#endif
736
737 /*
738 * Check sockets for writing
739 */
740#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
741 if (FD_ISSET(so->s, writefds))
742#else
743 if ((NetworkEvents.lNetworkEvents & FD_WRITE) && (NetworkEvents.iErrorCode[FD_WRITE_BIT] == 0))
744#endif
745 {
746 /*
747 * Check for non-blocking, still-connecting sockets
748 */
749 if (so->so_state & SS_ISFCONNECTING)
750 {
751 /* Connected */
752 so->so_state &= ~SS_ISFCONNECTING;
753
754 /*
755 * This should be probably guarded by PROBE_CONN too. Anyway,
756 * we disable it on OS/2 because the below send call returns
757 * EFAULT which causes the opened TCP socket to close right
758 * after it has been opened and connected.
759 */
760#ifndef RT_OS_OS2
761 ret = send(so->s, (const char *)&ret, 0, 0);
762 if (ret < 0)
763 {
764 /* XXXXX Must fix, zero bytes is a NOP */
765 if ( errno == EAGAIN
766 || errno == EWOULDBLOCK
767 || errno == EINPROGRESS
768 || errno == ENOTCONN)
769 continue;
770
771 /* else failed */
772 so->so_state = SS_NOFDREF;
773 }
774 /* else so->so_state &= ~SS_ISFCONNECTING; */
775#endif
776
777 /*
778 * Continue tcp_input
779 */
780 tcp_input(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
781 /* continue; */
782 }
783 else
784 ret = sowrite(pData, so);
785 /*
786 * XXX If we wrote something (a lot), there could be the need
787 * for a window update. In the worst case, the remote will send
788 * a window probe to get things going again.
789 */
790 }
791
792 /*
793 * Probe a still-connecting, non-blocking socket
794 * to check if it's still alive
795 */
796#ifdef PROBE_CONN
797 if (so->so_state & SS_ISFCONNECTING)
798 {
799 ret = recv(so->s, (char *)&ret, 0, 0);
800
801 if (ret < 0)
802 {
803 /* XXX */
804 if ( errno == EAGAIN
805 || errno == EWOULDBLOCK
806 || errno == EINPROGRESS
807 || errno == ENOTCONN)
808 {
809 continue; /* Still connecting, continue */
810 }
811
812 /* else failed */
813 so->so_state = SS_NOFDREF;
814
815 /* tcp_input will take care of it */
816 }
817 else
818 {
819 ret = send(so->s, &ret, 0, 0);
820 if (ret < 0)
821 {
822 /* XXX */
823 if ( errno == EAGAIN
824 || errno == EWOULDBLOCK
825 || errno == EINPROGRESS
826 || errno == ENOTCONN)
827 {
828 continue;
829 }
830 /* else failed */
831 so->so_state = SS_NOFDREF;
832 }
833 else
834 so->so_state &= ~SS_ISFCONNECTING;
835
836 }
837 tcp_input((struct mbuf *)NULL, sizeof(struct ip),so);
838 } /* SS_ISFCONNECTING */
839#endif
840 }
841
842 /*
843 * Now UDP sockets.
844 * Incoming packets are sent straight away, they're not buffered.
845 * Incoming UDP data isn't buffered either.
846 */
847 for (so = udb.so_next; so != &udb; so = so_next)
848 {
849 so_next = so->so_next;
850
851#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
852 rc = WSAEnumNetworkEvents(so->s, VBOX_SOCKET_EVENT, &NetworkEvents);
853 if (rc == SOCKET_ERROR)
854 {
855 error = WSAGetLastError();
856 LogRel(("WSAEnumNetworkEvents TCP error %d\n", error));
857 continue;
858 }
859#endif
860#if !defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) || !defined(RT_OS_WINDOWS)
861 if (so->s != -1 && FD_ISSET(so->s, readfds))
862#else
863 if (((NetworkEvents.lNetworkEvents & FD_READ) && (NetworkEvents.iErrorCode[FD_READ_BIT] == 0)))
864#endif
865 {
866 sorecvfrom(pData, so);
867 }
868 }
869#if defined(VBOX_WITH_SLIRP_ICMP) && defined(RT_OS_WINDOWS)
870 sorecvfrom(pData, &pData->icmp_socket);
871#endif
872 }
873
874 /*
875 * See if we can start outputting
876 */
877 if (if_queued && link_up)
878 if_start(pData);
879
880 STAM_REL_PROFILE_STOP(&pData->StatPoll, a);
881}
882
883#define ETH_ALEN 6
884#define ETH_HLEN 14
885
886#define ETH_P_IP 0x0800 /* Internet Protocol packet */
887#define ETH_P_ARP 0x0806 /* Address Resolution packet */
888
889#define ARPOP_REQUEST 1 /* ARP request */
890#define ARPOP_REPLY 2 /* ARP reply */
891
892struct ethhdr
893{
894 unsigned char h_dest[ETH_ALEN]; /* destination eth addr */
895 unsigned char h_source[ETH_ALEN]; /* source ether addr */
896 unsigned short h_proto; /* packet type ID field */
897};
898
899struct arphdr
900{
901 unsigned short ar_hrd; /* format of hardware address */
902 unsigned short ar_pro; /* format of protocol address */
903 unsigned char ar_hln; /* length of hardware address */
904 unsigned char ar_pln; /* length of protocol address */
905 unsigned short ar_op; /* ARP opcode (command) */
906
907 /*
908 * Ethernet looks like this : This bit is variable sized however...
909 */
910 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
911 unsigned char ar_sip[4]; /* sender IP address */
912 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
913 unsigned char ar_tip[4]; /* target IP address */
914};
915
916static
917void arp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
918{
919 struct ethhdr *eh = (struct ethhdr *)pkt;
920 struct arphdr *ah = (struct arphdr *)(pkt + ETH_HLEN);
921 uint8_t arp_reply[ETH_HLEN + sizeof(struct arphdr)];
922 struct ethhdr *reh = (struct ethhdr *)arp_reply;
923 struct arphdr *rah = (struct arphdr *)(arp_reply + ETH_HLEN);
924 int ar_op;
925 struct ex_list *ex_ptr;
926 uint32_t htip = ntohl(*(uint32_t*)ah->ar_tip);
927
928 ar_op = ntohs(ah->ar_op);
929 switch(ar_op)
930 {
931 case ARPOP_REQUEST:
932 if ((htip & pData->netmask) == ntohl(special_addr.s_addr))
933 {
934 if ( (htip & ~pData->netmask) == CTL_DNS
935 || (htip & ~pData->netmask) == CTL_ALIAS)
936 goto arp_ok;
937 for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)
938 {
939 if ((htip & ~pData->netmask) == ex_ptr->ex_addr)
940 goto arp_ok;
941 }
942 return;
943 arp_ok:
944 /* XXX: make an ARP request to have the client address */
945 memcpy(client_ethaddr, eh->h_source, ETH_ALEN);
946
947 /* ARP request for alias/dns mac address */
948 memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);
949 memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 1);
950 reh->h_source[5] = ah->ar_tip[3];
951 reh->h_proto = htons(ETH_P_ARP);
952
953 rah->ar_hrd = htons(1);
954 rah->ar_pro = htons(ETH_P_IP);
955 rah->ar_hln = ETH_ALEN;
956 rah->ar_pln = 4;
957 rah->ar_op = htons(ARPOP_REPLY);
958 memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);
959 memcpy(rah->ar_sip, ah->ar_tip, 4);
960 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
961 memcpy(rah->ar_tip, ah->ar_sip, 4);
962 slirp_output(pData->pvUser, arp_reply, sizeof(arp_reply));
963 }
964 break;
965 default:
966 break;
967 }
968}
969
970void slirp_input(PNATState pData, const uint8_t *pkt, int pkt_len)
971{
972 struct mbuf *m;
973 int proto;
974
975 if (pkt_len < ETH_HLEN)
976 return;
977
978 proto = ntohs(*(uint16_t *)(pkt + 12));
979 switch(proto)
980 {
981 case ETH_P_ARP:
982 arp_input(pData, pkt, pkt_len);
983 break;
984 case ETH_P_IP:
985 /* Update time. Important if the network is very quiet, as otherwise
986 * the first outgoing connection gets an incorrect timestamp. */
987 updtime(pData);
988
989 m = m_get(pData);
990 if (!m)
991 return;
992 /* Note: we add to align the IP header */
993 if (M_FREEROOM(m) < pkt_len + 2)
994 {
995 m_inc(m, pkt_len + 2);
996 }
997 m->m_len = pkt_len + 2;
998 memcpy(m->m_data + 2, pkt, pkt_len);
999
1000 m->m_data += 2 + ETH_HLEN;
1001 m->m_len -= 2 + ETH_HLEN;
1002
1003 ip_input(pData, m);
1004 break;
1005 default:
1006 break;
1007 }
1008}
1009
1010/* output the IP packet to the ethernet device */
1011void if_encap(PNATState pData, const uint8_t *ip_data, int ip_data_len)
1012{
1013 uint8_t buf[1600];
1014 struct ethhdr *eh = (struct ethhdr *)buf;
1015
1016 if (ip_data_len + ETH_HLEN > sizeof(buf))
1017 return;
1018
1019 memcpy(eh->h_dest, client_ethaddr, ETH_ALEN);
1020 memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 1);
1021 /* XXX: not correct */
1022 eh->h_source[5] = CTL_ALIAS;
1023 eh->h_proto = htons(ETH_P_IP);
1024 memcpy(buf + sizeof(struct ethhdr), ip_data, ip_data_len);
1025 slirp_output(pData->pvUser, buf, ip_data_len + ETH_HLEN);
1026}
1027
1028int slirp_redir(PNATState pData, int is_udp, int host_port,
1029 struct in_addr guest_addr, int guest_port)
1030{
1031 if (is_udp)
1032 {
1033 if (!udp_listen(pData, htons(host_port), guest_addr.s_addr,
1034 htons(guest_port), 0))
1035 return -1;
1036 }
1037 else
1038 {
1039 if (!solisten(pData, htons(host_port), guest_addr.s_addr,
1040 htons(guest_port), 0))
1041 return -1;
1042 }
1043 return 0;
1044}
1045
1046int slirp_add_exec(PNATState pData, int do_pty, const char *args, int addr_low_byte,
1047 int guest_port)
1048{
1049 return add_exec(&exec_list, do_pty, (char *)args,
1050 addr_low_byte, htons(guest_port));
1051}
1052
1053void slirp_set_ethaddr(PNATState pData, const uint8_t *ethaddr)
1054{
1055 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1056}
1057
1058#if defined(VBOX_WITH_SIMPLIFIED_SLIRP_SYNC) && defined(RT_OS_WINDOWS)
1059HANDLE *slirp_get_events(PNATState pData)
1060{
1061 return pData->phEvents;
1062}
1063void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1064{
1065 pData->phEvents[index] = hEvent;
1066}
1067#endif
1068
1069unsigned int slirp_get_timeout_ms(PNATState pData)
1070{
1071 if (link_up)
1072 {
1073 if (time_fasttimo)
1074 return 2;
1075 if (do_slowtimo)
1076 return 500; /* see PR_SLOWHZ */
1077 }
1078 return 0;
1079}
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