VirtualBox

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

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

slirp: readability

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