VirtualBox

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

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

slirp:cpp:UDP_NFDS declaration

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