VirtualBox

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

最後變更 在這個檔案從16226是 16226,由 vboxsync 提交於 16 年 前

NAT:

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

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