VirtualBox

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

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

NAT: applied patch from xtracker 4710 (fix graceful connection termination on Windows hosts)

  • 屬性 svn:eol-style 設為 native
檔案大小: 66.0 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#include <iprt/file.h>
10#ifndef RT_OS_WINDOWS
11# include <sys/ioctl.h>
12# include <poll.h>
13#else
14# include <Winnls.h>
15# define _WINSOCK2API_
16# include <IPHlpApi.h>
17#endif
18#include <alias.h>
19
20#ifndef RT_OS_WINDOWS
21
22# define DO_ENGAGE_EVENT1(so, fdset, label) \
23 do { \
24 if ( so->so_poll_index != -1 \
25 && so->s == polls[so->so_poll_index].fd) \
26 { \
27 polls[so->so_poll_index].events |= N_(fdset ## _poll); \
28 break; \
29 } \
30 AssertRelease(poll_index < (nfds)); \
31 AssertRelease(poll_index >= 0 && poll_index < (nfds)); \
32 polls[poll_index].fd = (so)->s; \
33 (so)->so_poll_index = poll_index; \
34 polls[poll_index].events = N_(fdset ## _poll); \
35 polls[poll_index].revents = 0; \
36 poll_index++; \
37 } while (0)
38
39# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
40 do { \
41 if ( so->so_poll_index != -1 \
42 && so->s == polls[so->so_poll_index].fd) \
43 { \
44 polls[so->so_poll_index].events |= \
45 N_(fdset1 ## _poll) | N_(fdset2 ## _poll); \
46 break; \
47 } \
48 AssertRelease(poll_index < (nfds)); \
49 polls[poll_index].fd = (so)->s; \
50 (so)->so_poll_index = poll_index; \
51 polls[poll_index].events = \
52 N_(fdset1 ## _poll) | N_(fdset2 ## _poll); \
53 poll_index++; \
54 } while (0)
55
56# define DO_POLL_EVENTS(rc, error, so, events, label) do {} while (0)
57
58# define DO_CHECK_FD_SET(so, events, fdset) \
59 ( ((so)->so_poll_index != -1) \
60 && ((so)->so_poll_index <= ndfs) \
61 && ((so)->s == polls[so->so_poll_index].fd) \
62 && (polls[(so)->so_poll_index].revents & N_(fdset ## _poll)))
63
64 /* specific for Unix API */
65# define DO_UNIX_CHECK_FD_SET(so, events, fdset) DO_CHECK_FD_SET((so), (events), fdset)
66 /* specific for Windows Winsock API */
67# define DO_WIN_CHECK_FD_SET(so, events, fdset) 0
68
69# ifndef RT_OS_LINUX
70# define readfds_poll (POLLRDNORM)
71# define writefds_poll (POLLWRNORM)
72# else
73# define readfds_poll (POLLIN)
74# define writefds_poll (POLLOUT)
75# endif
76# define xfds_poll (POLLPRI)
77# define closefds_poll (POLLHUP)
78# define rderr_poll (POLLERR)
79# define rdhup_poll (POLLHUP)
80# define nval_poll (POLLNVAL)
81
82# define ICMP_ENGAGE_EVENT(so, fdset) \
83 do { \
84 if (pData->icmp_socket.s != -1) \
85 DO_ENGAGE_EVENT1((so), fdset, ICMP); \
86 } while (0)
87
88#else /* RT_OS_WINDOWS */
89
90/*
91 * On Windows, we will be notified by IcmpSendEcho2() when the response arrives.
92 * So no call to WSAEventSelect necessary.
93 */
94# define ICMP_ENGAGE_EVENT(so, fdset) do {} while (0)
95
96/*
97 * On Windows we use FD_ALL_EVENTS to ensure that we don't miss any event.
98 */
99# define DO_ENGAGE_EVENT1(so, fdset1, label) \
100 do { \
101 rc = WSAEventSelect((so)->s, VBOX_SOCKET_EVENT, FD_ALL_EVENTS); \
102 if (rc == SOCKET_ERROR) \
103 { \
104 /* This should not happen */ \
105 error = WSAGetLastError(); \
106 LogRel(("WSAEventSelect (" #label ") error %d (so=%x, socket=%s, event=%x)\n", \
107 error, (so), (so)->s, VBOX_SOCKET_EVENT)); \
108 } \
109 } while (0); \
110 CONTINUE(label)
111
112# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
113 DO_ENGAGE_EVENT1((so), (fdset1), label)
114
115# define DO_POLL_EVENTS(rc, error, so, events, label) \
116 (rc) = WSAEnumNetworkEvents((so)->s, VBOX_SOCKET_EVENT, (events)); \
117 if ((rc) == SOCKET_ERROR) \
118 { \
119 (error) = WSAGetLastError(); \
120 LogRel(("WSAEnumNetworkEvents " #label " error %d\n", (error))); \
121 CONTINUE(label); \
122 }
123
124# define acceptds_win FD_ACCEPT
125# define acceptds_win_bit FD_ACCEPT_BIT
126# define readfds_win FD_READ
127# define readfds_win_bit FD_READ_BIT
128# define writefds_win FD_WRITE
129# define writefds_win_bit FD_WRITE_BIT
130# define xfds_win FD_OOB
131# define xfds_win_bit FD_OOB_BIT
132# define closefds_win FD_CLOSE
133# define closefds_win_bit FD_CLOSE_BIT
134
135# define DO_CHECK_FD_SET(so, events, fdset) \
136 (((events).lNetworkEvents & fdset ## _win) && ((events).iErrorCode[fdset ## _win_bit] == 0))
137
138# define DO_WIN_CHECK_FD_SET(so, events, fdset) DO_CHECK_FD_SET((so), (events), fdset)
139# define DO_UNIX_CHECK_FD_SET(so, events, fdset) 1 /*specific for Unix API */
140
141#endif /* RT_OS_WINDOWS */
142
143#define TCP_ENGAGE_EVENT1(so, fdset) \
144 DO_ENGAGE_EVENT1((so), fdset, tcp)
145
146#define TCP_ENGAGE_EVENT2(so, fdset1, fdset2) \
147 DO_ENGAGE_EVENT2((so), fdset1, fdset2, tcp)
148
149#define UDP_ENGAGE_EVENT(so, fdset) \
150 DO_ENGAGE_EVENT1((so), fdset, udp)
151
152#define POLL_TCP_EVENTS(rc, error, so, events) \
153 DO_POLL_EVENTS((rc), (error), (so), (events), tcp)
154
155#define POLL_UDP_EVENTS(rc, error, so, events) \
156 DO_POLL_EVENTS((rc), (error), (so), (events), udp)
157
158#define CHECK_FD_SET(so, events, set) \
159 (DO_CHECK_FD_SET((so), (events), set))
160
161#define WIN_CHECK_FD_SET(so, events, set) \
162 (DO_WIN_CHECK_FD_SET((so), (events), set))
163
164#define UNIX_CHECK_FD_SET(so, events, set) \
165 (DO_UNIX_CHECK_FD_SET(so, events, set))
166
167/*
168 * Loging macros
169 */
170#if VBOX_WITH_DEBUG_NAT_SOCKETS
171# if defined(RT_OS_WINDOWS)
172# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
173 do { \
174 LogRel((" " #proto " %R[natsock] %R[natwinnetevents]\n", (so), (winevent))); \
175 } while (0)
176# else /* !RT_OS_WINDOWS */
177# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
178 do { \
179 LogRel((" " #proto " %R[natsock] %s %s %s er: %s, %s, %s\n", (so), \
180 CHECK_FD_SET(so, ign ,r_fdset) ? "READ":"", \
181 CHECK_FD_SET(so, ign, w_fdset) ? "WRITE":"", \
182 CHECK_FD_SET(so, ign, x_fdset) ? "OOB":"", \
183 CHECK_FD_SET(so, ign, rderr) ? "RDERR":"", \
184 CHECK_FD_SET(so, ign, rdhup) ? "RDHUP":"", \
185 CHECK_FD_SET(so, ign, nval) ? "RDNVAL":"")); \
186 } while (0)
187# endif /* !RT_OS_WINDOWS */
188#else /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
189# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) do {} while (0)
190#endif /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
191
192#define LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
193 DO_LOG_NAT_SOCK((so), proto, (winevent), r_fdset, w_fdset, x_fdset)
194
195static void activate_port_forwarding(PNATState, const uint8_t *pEther);
196
197static const uint8_t special_ethaddr[6] =
198{
199 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
200};
201
202static const uint8_t broadcast_ethaddr[6] =
203{
204 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
205};
206
207const uint8_t zerro_ethaddr[6] =
208{
209 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
210};
211
212#ifdef RT_OS_WINDOWS
213static int get_dns_addr_domain(PNATState pData, bool fVerbose,
214 struct in_addr *pdns_addr,
215 const char **ppszDomain)
216{
217 ULONG flags = GAA_FLAG_INCLUDE_PREFIX; /*GAA_FLAG_INCLUDE_ALL_INTERFACES;*/ /* all interfaces registered in NDIS */
218 PIP_ADAPTER_ADDRESSES pAdapterAddr = NULL;
219 PIP_ADAPTER_ADDRESSES pAddr = NULL;
220 PIP_ADAPTER_DNS_SERVER_ADDRESS pDnsAddr = NULL;
221 ULONG size;
222 int wlen = 0;
223 char *pszSuffix;
224 struct dns_domain_entry *pDomain = NULL;
225 ULONG ret = ERROR_SUCCESS;
226
227 /* @todo add SKIPing flags to get only required information */
228
229 /* determine size of buffer */
230 size = 0;
231 ret = pData->pfGetAdaptersAddresses(AF_INET, 0, NULL /* reserved */, pAdapterAddr, &size);
232 if (ret != ERROR_BUFFER_OVERFLOW)
233 {
234 LogRel(("NAT: error %lu occurred on capacity detection operation\n", ret));
235 return -1;
236 }
237 if (size == 0)
238 {
239 LogRel(("NAT: Win socket API returns non capacity\n"));
240 return -1;
241 }
242
243 pAdapterAddr = RTMemAllocZ(size);
244 if (!pAdapterAddr)
245 {
246 LogRel(("NAT: No memory available \n"));
247 return -1;
248 }
249 ret = pData->pfGetAdaptersAddresses(AF_INET, 0, NULL /* reserved */, pAdapterAddr, &size);
250 if (ret != ERROR_SUCCESS)
251 {
252 LogRel(("NAT: error %lu occurred on fetching adapters info\n", ret));
253 RTMemFree(pAdapterAddr);
254 return -1;
255 }
256
257 for (pAddr = pAdapterAddr; pAddr != NULL; pAddr = pAddr->Next)
258 {
259 int found;
260 if (pAddr->OperStatus != IfOperStatusUp)
261 continue;
262
263 for (pDnsAddr = pAddr->FirstDnsServerAddress; pDnsAddr != NULL; pDnsAddr = pDnsAddr->Next)
264 {
265 struct sockaddr *SockAddr = pDnsAddr->Address.lpSockaddr;
266 struct in_addr InAddr;
267 struct dns_entry *pDns;
268
269 if (SockAddr->sa_family != AF_INET)
270 continue;
271
272 InAddr = ((struct sockaddr_in *)SockAddr)->sin_addr;
273
274 /* add dns server to list */
275 pDns = RTMemAllocZ(sizeof(struct dns_entry));
276 if (!pDns)
277 {
278 LogRel(("NAT: Can't allocate buffer for DNS entry\n"));
279 RTMemFree(pAdapterAddr);
280 return VERR_NO_MEMORY;
281 }
282
283 LogRel(("NAT: adding %R[IP4] to DNS server list\n", &InAddr));
284 if ((InAddr.s_addr & RT_H2N_U32_C(IN_CLASSA_NET)) == RT_N2H_U32_C(INADDR_LOOPBACK & IN_CLASSA_NET))
285 pDns->de_addr.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
286 else
287 pDns->de_addr.s_addr = InAddr.s_addr;
288
289 TAILQ_INSERT_HEAD(&pData->pDnsList, pDns, de_list);
290
291 if (pAddr->DnsSuffix == NULL)
292 continue;
293
294 /* uniq */
295 RTUtf16ToUtf8(pAddr->DnsSuffix, &pszSuffix);
296 if (!pszSuffix || strlen(pszSuffix) == 0)
297 {
298 RTStrFree(pszSuffix);
299 continue;
300 }
301
302 found = 0;
303 LIST_FOREACH(pDomain, &pData->pDomainList, dd_list)
304 {
305 if ( pDomain->dd_pszDomain != NULL
306 && strcmp(pDomain->dd_pszDomain, pszSuffix) == 0)
307 {
308 found = 1;
309 RTStrFree(pszSuffix);
310 break;
311 }
312 }
313 if (!found)
314 {
315 pDomain = RTMemAllocZ(sizeof(struct dns_domain_entry));
316 if (!pDomain)
317 {
318 LogRel(("NAT: not enough memory\n"));
319 RTStrFree(pszSuffix);
320 RTMemFree(pAdapterAddr);
321 return VERR_NO_MEMORY;
322 }
323 pDomain->dd_pszDomain = pszSuffix;
324 LogRel(("NAT: adding domain name %s to search list\n", pDomain->dd_pszDomain));
325 LIST_INSERT_HEAD(&pData->pDomainList, pDomain, dd_list);
326 }
327 }
328 }
329 RTMemFree(pAdapterAddr);
330 return 0;
331}
332
333#else /* !RT_OS_WINDOWS */
334
335static int RTFileGets(RTFILE File, void *pvBuf, size_t cbBufSize, size_t *pcbRead)
336{
337 size_t cbRead;
338 char bTest;
339 int rc = VERR_NO_MEMORY;
340 char *pu8Buf = (char *)pvBuf;
341 *pcbRead = 0;
342
343 while ( RT_SUCCESS(rc = RTFileRead(File, &bTest, 1, &cbRead))
344 && (pu8Buf - (char *)pvBuf) < cbBufSize)
345 {
346 if (cbRead == 0)
347 return VERR_EOF;
348
349 if (bTest == '\r' || bTest == '\n')
350 {
351 *pu8Buf = 0;
352 return VINF_SUCCESS;
353 }
354 *pu8Buf = bTest;
355 pu8Buf++;
356 (*pcbRead)++;
357 }
358 return rc;
359}
360
361static int get_dns_addr_domain(PNATState pData, bool fVerbose,
362 struct in_addr *pdns_addr,
363 const char **ppszDomain)
364{
365 char buff[512];
366 char buff2[256];
367 RTFILE f;
368 int fFoundNameserver = 0;
369 struct in_addr tmp_addr;
370 int rc;
371 size_t bytes;
372
373# ifdef RT_OS_OS2
374 /* Try various locations. */
375 char *etc = getenv("ETC");
376 if (etc)
377 {
378 RTStrmPrintf(buff, sizeof(buff), "%s/RESOLV2", etc);
379 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
380 }
381 if (RT_FAILURE(rc))
382 {
383 RTStrmPrintf(buff, sizeof(buff), "%s/RESOLV2", _PATH_ETC);
384 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
385 }
386 if (RT_FAILURE(rc))
387 {
388 RTStrmPrintf(buff, sizeof(buff), "%s/resolv.conf", _PATH_ETC);
389 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
390 }
391# else /* !RT_OS_OS2 */
392# ifndef DEBUG_vvl
393 rc = RTFileOpen(&f, "/etc/resolv.conf", RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
394# else
395 char *home = getenv("HOME");
396 RTStrPrintf(buff, sizeof(buff), "%s/resolv.conf", home);
397 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
398 if (RT_SUCCESS(rc))
399 {
400 Log(("NAT: DNS we're using %s\n", buff));
401 }
402 else
403 {
404 rc = RTFileOpen(&f, "/etc/resolv.conf", RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
405 Log(("NAT: DNS we're using %s\n", buff));
406 }
407# endif
408# endif /* !RT_OS_OS2 */
409 if (RT_FAILURE(rc))
410 return -1;
411
412 if (ppszDomain)
413 *ppszDomain = NULL;
414
415 Log(("NAT: DNS Servers:\n"));
416 while ( RT_SUCCESS(rc = RTFileGets(f, buff, 512, &bytes))
417 && rc != VERR_EOF)
418 {
419 struct dns_entry *pDns = NULL;
420 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1)
421 {
422 if (!inet_aton(buff2, &tmp_addr))
423 continue;
424
425 /* localhost mask */
426 pDns = RTMemAllocZ(sizeof (struct dns_entry));
427 if (!pDns)
428 {
429 LogRel(("can't alloc memory for DNS entry\n"));
430 return -1;
431 }
432
433 /* check */
434 pDns->de_addr.s_addr = tmp_addr.s_addr;
435 if ((pDns->de_addr.s_addr & RT_H2N_U32_C(IN_CLASSA_NET)) == RT_N2H_U32_C(INADDR_LOOPBACK & IN_CLASSA_NET))
436 {
437 pDns->de_addr.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
438 }
439 TAILQ_INSERT_HEAD(&pData->pDnsList, pDns, de_list);
440 fFoundNameserver++;
441 }
442 if ((!strncmp(buff, "domain", 6) || !strncmp(buff, "search", 6)))
443 {
444 char *tok;
445 char *saveptr;
446 struct dns_domain_entry *pDomain = NULL;
447 int fFoundDomain = 0;
448 tok = strtok_r(&buff[6], " \t\n", &saveptr);
449 LIST_FOREACH(pDomain, &pData->pDomainList, dd_list)
450 {
451 if ( tok != NULL
452 && strcmp(tok, pDomain->dd_pszDomain) == 0)
453 {
454 fFoundDomain = 1;
455 break;
456 }
457 }
458 if (tok != NULL && !fFoundDomain)
459 {
460 pDomain = RTMemAllocZ(sizeof(struct dns_domain_entry));
461 if (!pDomain)
462 {
463 LogRel(("NAT: not enought memory to add domain list\n"));
464 return VERR_NO_MEMORY;
465 }
466 pDomain->dd_pszDomain = RTStrDup(tok);
467 LogRel(("NAT: adding domain name %s to search list\n", pDomain->dd_pszDomain));
468 LIST_INSERT_HEAD(&pData->pDomainList, pDomain, dd_list);
469 }
470 }
471 }
472 RTFileClose(f);
473 if (!fFoundNameserver)
474 return -1;
475 return 0;
476}
477
478#endif /* !RT_OS_WINDOWS */
479
480static int slirp_init_dns_list(PNATState pData)
481{
482 TAILQ_INIT(&pData->pDnsList);
483 LIST_INIT(&pData->pDomainList);
484 return get_dns_addr_domain(pData, true, NULL, NULL);
485}
486
487static void slirp_release_dns_list(PNATState pData)
488{
489 struct dns_entry *pDns = NULL;
490 struct dns_domain_entry *pDomain = NULL;
491
492 while (!TAILQ_EMPTY(&pData->pDnsList))
493 {
494 pDns = TAILQ_FIRST(&pData->pDnsList);
495 TAILQ_REMOVE(&pData->pDnsList, pDns, de_list);
496 RTMemFree(pDns);
497 }
498
499 while (!LIST_EMPTY(&pData->pDomainList))
500 {
501 pDomain = LIST_FIRST(&pData->pDomainList);
502 LIST_REMOVE(pDomain, dd_list);
503 if (pDomain->dd_pszDomain != NULL)
504 RTStrFree(pDomain->dd_pszDomain);
505 RTMemFree(pDomain);
506 }
507}
508
509int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
510{
511 return get_dns_addr_domain(pData, false, pdns_addr, NULL);
512}
513
514#ifndef VBOX_WITH_NAT_SERVICE
515int slirp_init(PNATState *ppData, const char *pszNetAddr, uint32_t u32Netmask,
516 bool fPassDomain, bool fUseHostResolver, void *pvUser)
517#else
518int slirp_init(PNATState *ppData, uint32_t u32NetAddr, uint32_t u32Netmask,
519 bool fPassDomain, void *pvUser)
520#endif
521{
522 int fNATfailed = 0;
523 int rc;
524 PNATState pData = RTMemAllocZ(sizeof(NATState));
525 *ppData = pData;
526 if (!pData)
527 return VERR_NO_MEMORY;
528 if (u32Netmask & 0x1f)
529 /* CTL is x.x.x.15, bootp passes up to 16 IPs (15..31) */
530 return VERR_INVALID_PARAMETER;
531 pData->fPassDomain = !fUseHostResolver ? fPassDomain : false;
532 pData->use_host_resolver = fUseHostResolver;
533 pData->pvUser = pvUser;
534 pData->netmask = u32Netmask;
535
536 /* sockets & TCP defaults */
537 pData->socket_rcv = 64 * _1K;
538 pData->socket_snd = 64 * _1K;
539 tcp_sndspace = 64 * _1K;
540 tcp_rcvspace = 64 * _1K;
541
542#ifdef RT_OS_WINDOWS
543 {
544 WSADATA Data;
545 WSAStartup(MAKEWORD(2, 0), &Data);
546 }
547 pData->phEvents[VBOX_SOCKET_EVENT_INDEX] = CreateEvent(NULL, FALSE, FALSE, NULL);
548#endif
549#ifdef VBOX_WITH_SLIRP_MT
550 QSOCKET_LOCK_CREATE(tcb);
551 QSOCKET_LOCK_CREATE(udb);
552 rc = RTReqCreateQueue(&pData->pReqQueue);
553 AssertReleaseRC(rc);
554#endif
555
556 link_up = 1;
557
558 rc = bootp_dhcp_init(pData);
559 if (rc != 0)
560 {
561 LogRel(("NAT: DHCP server initialization was failed\n"));
562 return VINF_NAT_DNS;
563 }
564 debug_init();
565 if_init(pData);
566 ip_init(pData);
567 icmp_init(pData);
568
569 /* Initialise mbufs *after* setting the MTU */
570#ifndef VBOX_WITH_SLIRP_BSD_MBUF
571 m_init(pData);
572#else
573 mbuf_init(pData);
574#endif
575
576#ifndef VBOX_WITH_NAT_SERVICE
577 inet_aton(pszNetAddr, &pData->special_addr);
578#else
579 pData->special_addr.s_addr = u32NetAddr;
580#endif
581 pData->slirp_ethaddr = &special_ethaddr[0];
582 alias_addr.s_addr = pData->special_addr.s_addr | RT_H2N_U32_C(CTL_ALIAS);
583 /* @todo: add ability to configure this staff */
584
585 /* set default addresses */
586 inet_aton("127.0.0.1", &loopback_addr);
587 if (!pData->use_host_resolver)
588 {
589 if (slirp_init_dns_list(pData) < 0)
590 fNATfailed = 1;
591
592 dnsproxy_init(pData);
593 }
594
595 getouraddr(pData);
596 {
597 int flags = 0;
598 struct in_addr proxy_addr;
599 pData->proxy_alias = LibAliasInit(pData, NULL);
600 if (pData->proxy_alias == NULL)
601 {
602 LogRel(("NAT: LibAlias default rule wasn't initialized\n"));
603 AssertMsgFailed(("NAT: LibAlias default rule wasn't initialized\n"));
604 }
605 flags = LibAliasSetMode(pData->proxy_alias, 0, 0);
606#ifndef NO_FW_PUNCH
607 flags |= PKT_ALIAS_PUNCH_FW;
608#endif
609 flags |= PKT_ALIAS_LOG; /* set logging */
610 flags = LibAliasSetMode(pData->proxy_alias, flags, ~0);
611 proxy_addr.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
612 LibAliasSetAddress(pData->proxy_alias, proxy_addr);
613 ftp_alias_load(pData);
614 nbt_alias_load(pData);
615 if (pData->use_host_resolver)
616 dns_alias_load(pData);
617 }
618 return fNATfailed ? VINF_NAT_DNS : VINF_SUCCESS;
619}
620
621/**
622 * Register statistics.
623 */
624void slirp_register_statistics(PNATState pData, PPDMDRVINS pDrvIns)
625{
626#ifdef VBOX_WITH_STATISTICS
627# define PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pData, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
628# define COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pData, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
629# include "counters.h"
630# undef COUNTER
631/** @todo register statistics for the variables dumped by:
632 * ipstats(pData); tcpstats(pData); udpstats(pData); icmpstats(pData);
633 * mbufstats(pData); sockstats(pData); */
634#endif /* VBOX_WITH_STATISTICS */
635}
636
637/**
638 * Deregister statistics.
639 */
640void slirp_deregister_statistics(PNATState pData, PPDMDRVINS pDrvIns)
641{
642#ifdef VBOX_WITH_STATISTICS
643# define PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pData)
644# define COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pData)
645# include "counters.h"
646#endif /* VBOX_WITH_STATISTICS */
647}
648
649/**
650 * Marks the link as up, making it possible to establish new connections.
651 */
652void slirp_link_up(PNATState pData)
653{
654 struct arp_cache_entry *ac;
655 link_up = 1;
656
657 if (LIST_EMPTY(&pData->arp_cache))
658 return;
659
660 LIST_FOREACH(ac, &pData->arp_cache, list)
661 {
662 activate_port_forwarding(pData, ac->ether);
663 }
664}
665
666/**
667 * Marks the link as down and cleans up the current connections.
668 */
669void slirp_link_down(PNATState pData)
670{
671 struct socket *so;
672 struct port_forward_rule *rule;
673
674 while ((so = tcb.so_next) != &tcb)
675 {
676 if (so->so_state & SS_NOFDREF || so->s == -1)
677 sofree(pData, so);
678 else
679 tcp_drop(pData, sototcpcb(so), 0);
680 }
681
682 while ((so = udb.so_next) != &udb)
683 udp_detach(pData, so);
684
685 /*
686 * Clear the active state of port-forwarding rules to force
687 * re-setup on restoration of communications.
688 */
689 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
690 {
691 rule->activated = 0;
692 }
693 pData->cRedirectionsActive = 0;
694
695 link_up = 0;
696}
697
698/**
699 * Terminates the slirp component.
700 */
701void slirp_term(PNATState pData)
702{
703#ifdef RT_OS_WINDOWS
704 pData->pfIcmpCloseHandle(pData->icmp_socket.sh);
705 FreeLibrary(pData->hmIcmpLibrary);
706 RTMemFree(pData->pvIcmpBuffer);
707#else
708 closesocket(pData->icmp_socket.s);
709#endif
710
711 slirp_link_down(pData);
712 slirp_release_dns_list(pData);
713 ftp_alias_unload(pData);
714 nbt_alias_unload(pData);
715 if (pData->use_host_resolver)
716 dns_alias_unload(pData);
717 while (!LIST_EMPTY(&instancehead))
718 {
719 struct libalias *la = LIST_FIRST(&instancehead);
720 /* libalias do all clean up */
721 LibAliasUninit(la);
722 }
723 while (!LIST_EMPTY(&pData->arp_cache))
724 {
725 struct arp_cache_entry *ac = LIST_FIRST(&pData->arp_cache);
726 LIST_REMOVE(ac, list);
727 RTMemFree(ac);
728 }
729 bootp_dhcp_fini(pData);
730 m_fini(pData);
731#ifdef RT_OS_WINDOWS
732 WSACleanup();
733#endif
734#ifdef LOG_ENABLED
735 Log(("\n"
736 "NAT statistics\n"
737 "--------------\n"
738 "\n"));
739 ipstats(pData);
740 tcpstats(pData);
741 udpstats(pData);
742 icmpstats(pData);
743 mbufstats(pData);
744 sockstats(pData);
745 Log(("\n"
746 "\n"
747 "\n"));
748#endif
749 RTMemFree(pData);
750}
751
752
753#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
754#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
755
756/*
757 * curtime kept to an accuracy of 1ms
758 */
759static void updtime(PNATState pData)
760{
761#ifdef RT_OS_WINDOWS
762 struct _timeb tb;
763
764 _ftime(&tb);
765 curtime = (u_int)tb.time * (u_int)1000;
766 curtime += (u_int)tb.millitm;
767#else
768 gettimeofday(&tt, 0);
769
770 curtime = (u_int)tt.tv_sec * (u_int)1000;
771 curtime += (u_int)tt.tv_usec / (u_int)1000;
772
773 if ((tt.tv_usec % 1000) >= 500)
774 curtime++;
775#endif
776}
777
778#ifdef RT_OS_WINDOWS
779void slirp_select_fill(PNATState pData, int *pnfds)
780#else /* RT_OS_WINDOWS */
781void slirp_select_fill(PNATState pData, int *pnfds, struct pollfd *polls)
782#endif /* !RT_OS_WINDOWS */
783{
784 struct socket *so, *so_next;
785 int nfds;
786#if defined(RT_OS_WINDOWS)
787 int rc;
788 int error;
789#else
790 int poll_index = 0;
791#endif
792 int i;
793
794 STAM_PROFILE_START(&pData->StatFill, a);
795
796 nfds = *pnfds;
797
798 /*
799 * First, TCP sockets
800 */
801 do_slowtimo = 0;
802 if (!link_up)
803 goto done;
804
805 /*
806 * *_slowtimo needs calling if there are IP fragments
807 * in the fragment queue, or there are TCP connections active
808 */
809 /* XXX:
810 * triggering of fragment expiration should be the same but use new macroses
811 */
812 do_slowtimo = (tcb.so_next != &tcb);
813 if (!do_slowtimo)
814 {
815 for (i = 0; i < IPREASS_NHASH; i++)
816 {
817 if (!TAILQ_EMPTY(&ipq[i]))
818 {
819 do_slowtimo = 1;
820 slirp_arm_slow_timer(pData->pvUser);
821 break;
822 }
823 }
824 }
825 ICMP_ENGAGE_EVENT(&pData->icmp_socket, readfds);
826
827 STAM_COUNTER_RESET(&pData->StatTCP);
828 STAM_COUNTER_RESET(&pData->StatTCPHot);
829
830 QSOCKET_FOREACH(so, so_next, tcp)
831 /* { */
832#if !defined(RT_OS_WINDOWS)
833 so->so_poll_index = -1;
834#endif
835#ifndef VBOX_WITH_SLIRP_BSD_MBUF
836 if (pData->fmbuf_water_line == 1)
837 {
838 if (mbuf_alloced < pData->mbuf_water_line_limit/2)
839 {
840 pData->fmbuf_water_warn_sent = 0;
841 pData->fmbuf_water_line = 0;
842 }
843# ifndef RT_OS_WINDOWS
844 poll_index = 0;
845# endif
846 goto done;
847 }
848#endif /* !VBOX_WITH_SLIRP_BSD_MBUF */
849 STAM_COUNTER_INC(&pData->StatTCP);
850
851 /*
852 * See if we need a tcp_fasttimo
853 */
854 if ( time_fasttimo == 0
855 && so->so_tcpcb != NULL
856 && so->so_tcpcb->t_flags & TF_DELACK)
857 {
858 time_fasttimo = curtime; /* Flag when we want a fasttimo */
859 slirp_arm_fast_timer(pData->pvUser);
860 }
861
862 /*
863 * NOFDREF can include still connecting to local-host,
864 * newly socreated() sockets etc. Don't want to select these.
865 */
866 if (so->so_state & SS_NOFDREF || so->s == -1)
867 CONTINUE(tcp);
868
869 /*
870 * Set for reading sockets which are accepting
871 */
872 if (so->so_state & SS_FACCEPTCONN)
873 {
874 STAM_COUNTER_INC(&pData->StatTCPHot);
875 TCP_ENGAGE_EVENT1(so, readfds);
876 CONTINUE(tcp);
877 }
878
879 /*
880 * Set for writing sockets which are connecting
881 */
882 if (so->so_state & SS_ISFCONNECTING)
883 {
884 Log2(("connecting %R[natsock] engaged\n",so));
885 STAM_COUNTER_INC(&pData->StatTCPHot);
886 TCP_ENGAGE_EVENT1(so, writefds);
887 }
888
889 /*
890 * Set for writing if we are connected, can send more, and
891 * we have something to send
892 */
893 if (CONN_CANFSEND(so) && so->so_rcv.sb_cc)
894 {
895 STAM_COUNTER_INC(&pData->StatTCPHot);
896 TCP_ENGAGE_EVENT1(so, writefds);
897 }
898
899 /*
900 * Set for reading (and urgent data) if we are connected, can
901 * receive more, and we have room for it XXX /2 ?
902 */
903 if (CONN_CANFRCV(so) && (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2)))
904 {
905 STAM_COUNTER_INC(&pData->StatTCPHot);
906 TCP_ENGAGE_EVENT2(so, readfds, xfds);
907 }
908 LOOP_LABEL(tcp, so, so_next);
909 }
910
911 /*
912 * UDP sockets
913 */
914 STAM_COUNTER_RESET(&pData->StatUDP);
915 STAM_COUNTER_RESET(&pData->StatUDPHot);
916
917 QSOCKET_FOREACH(so, so_next, udp)
918 /* { */
919
920#ifndef VBOX_WITH_SLIRP_BSD_MBUF
921 if (pData->fmbuf_water_line == 1)
922 {
923 if (mbuf_alloced < pData->mbuf_water_line_limit/2)
924 {
925 pData->fmbuf_water_line = 0;
926 pData->fmbuf_water_warn_sent = 0;
927 }
928# ifndef RT_OS_WINDOWS
929 poll_index = 0;
930# endif
931 goto done;
932 }
933#endif /* !VBOX_WITH_SLIRP_BSD_MBUF */
934 STAM_COUNTER_INC(&pData->StatUDP);
935#if !defined(RT_OS_WINDOWS)
936 so->so_poll_index = -1;
937#endif
938
939 /*
940 * See if it's timed out
941 */
942 if (so->so_expire)
943 {
944 if (so->so_expire <= curtime)
945 {
946 Log2(("NAT: %R[natsock] expired\n", so));
947 if (so->so_timeout != NULL)
948 {
949 so->so_timeout(pData, so, so->so_timeout_arg);
950 }
951#ifdef VBOX_WITH_SLIRP_MT
952 /* we need so_next for continue our cycle*/
953 so_next = so->so_next;
954#endif
955 UDP_DETACH(pData, so, so_next);
956 CONTINUE_NO_UNLOCK(udp);
957 }
958 else
959 {
960 do_slowtimo = 1; /* Let socket expire */
961 slirp_arm_slow_timer(pData->pvUser);
962 }
963 }
964
965 /*
966 * When UDP packets are received from over the link, they're
967 * sendto()'d straight away, so no need for setting for writing
968 * Limit the number of packets queued by this session to 4.
969 * Note that even though we try and limit this to 4 packets,
970 * the session could have more queued if the packets needed
971 * to be fragmented.
972 *
973 * (XXX <= 4 ?)
974 */
975 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4)
976 {
977 STAM_COUNTER_INC(&pData->StatUDPHot);
978 UDP_ENGAGE_EVENT(so, readfds);
979 }
980 LOOP_LABEL(udp, so, so_next);
981 }
982done:
983
984#if defined(RT_OS_WINDOWS)
985 *pnfds = VBOX_EVENT_COUNT;
986#else /* RT_OS_WINDOWS */
987 AssertRelease(poll_index <= *pnfds);
988 *pnfds = poll_index;
989#endif /* !RT_OS_WINDOWS */
990
991 STAM_PROFILE_STOP(&pData->StatFill, a);
992}
993
994#if defined(RT_OS_WINDOWS)
995void slirp_select_poll(PNATState pData, int fTimeout, int fIcmp)
996#else /* RT_OS_WINDOWS */
997void slirp_select_poll(PNATState pData, struct pollfd *polls, int ndfs)
998#endif /* !RT_OS_WINDOWS */
999{
1000 struct socket *so, *so_next;
1001 int ret;
1002#if defined(RT_OS_WINDOWS)
1003 WSANETWORKEVENTS NetworkEvents;
1004 int rc;
1005 int error;
1006#else
1007 int poll_index = 0;
1008#endif
1009
1010 STAM_PROFILE_START(&pData->StatPoll, a);
1011
1012 /* Update time */
1013 updtime(pData);
1014
1015 /*
1016 * See if anything has timed out
1017 */
1018 if (link_up)
1019 {
1020 if (time_fasttimo && ((curtime - time_fasttimo) >= 2))
1021 {
1022 STAM_PROFILE_START(&pData->StatFastTimer, b);
1023 tcp_fasttimo(pData);
1024 time_fasttimo = 0;
1025 STAM_PROFILE_STOP(&pData->StatFastTimer, b);
1026 }
1027 if (do_slowtimo && ((curtime - last_slowtimo) >= 499))
1028 {
1029 STAM_PROFILE_START(&pData->StatSlowTimer, c);
1030 ip_slowtimo(pData);
1031 tcp_slowtimo(pData);
1032 last_slowtimo = curtime;
1033 STAM_PROFILE_STOP(&pData->StatSlowTimer, c);
1034 }
1035 }
1036#if defined(RT_OS_WINDOWS)
1037 if (fTimeout)
1038 return; /* only timer update */
1039#endif
1040
1041 /*
1042 * Check sockets
1043 */
1044 if (!link_up)
1045 goto done;
1046#if defined(RT_OS_WINDOWS)
1047 /*XXX: before renaming please make see define
1048 * fIcmp in slirp_state.h
1049 */
1050 if (fIcmp)
1051 sorecvfrom(pData, &pData->icmp_socket);
1052#else
1053 if ( (pData->icmp_socket.s != -1)
1054 && CHECK_FD_SET(&pData->icmp_socket, ignored, readfds))
1055 sorecvfrom(pData, &pData->icmp_socket);
1056#endif
1057 /*
1058 * Check TCP sockets
1059 */
1060 QSOCKET_FOREACH(so, so_next, tcp)
1061 /* { */
1062#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1063 if (pData->fmbuf_water_line == 1)
1064 {
1065 if (mbuf_alloced < pData->mbuf_water_line_limit/2)
1066 {
1067 pData->fmbuf_water_line = 0;
1068 pData->fmbuf_water_warn_sent = 0;
1069 }
1070 goto done;
1071 }
1072#endif
1073
1074#ifdef VBOX_WITH_SLIRP_MT
1075 if ( so->so_state & SS_NOFDREF
1076 && so->so_deleted == 1)
1077 {
1078 struct socket *son, *sop = NULL;
1079 QSOCKET_LOCK(tcb);
1080 if (so->so_next != NULL)
1081 {
1082 if (so->so_next != &tcb)
1083 SOCKET_LOCK(so->so_next);
1084 son = so->so_next;
1085 }
1086 if ( so->so_prev != &tcb
1087 && so->so_prev != NULL)
1088 {
1089 SOCKET_LOCK(so->so_prev);
1090 sop = so->so_prev;
1091 }
1092 QSOCKET_UNLOCK(tcb);
1093 remque(pData, so);
1094 NSOCK_DEC();
1095 SOCKET_UNLOCK(so);
1096 SOCKET_LOCK_DESTROY(so);
1097 RTMemFree(so);
1098 so_next = son;
1099 if (sop != NULL)
1100 SOCKET_UNLOCK(sop);
1101 CONTINUE_NO_UNLOCK(tcp);
1102 }
1103#endif
1104 /*
1105 * FD_ISSET is meaningless on these sockets
1106 * (and they can crash the program)
1107 */
1108 if (so->so_state & SS_NOFDREF || so->s == -1)
1109 CONTINUE(tcp);
1110
1111 POLL_TCP_EVENTS(rc, error, so, &NetworkEvents);
1112
1113 LOG_NAT_SOCK(so, TCP, &NetworkEvents, readfds, writefds, xfds);
1114
1115
1116 /*
1117 * Check for URG data
1118 * This will soread as well, so no need to
1119 * test for readfds below if this succeeds
1120 */
1121
1122 /* out-of-band data */
1123 if (CHECK_FD_SET(so, NetworkEvents, xfds))
1124 {
1125 sorecvoob(pData, so);
1126 }
1127
1128 /*
1129 * Check sockets for reading
1130 */
1131 else if ( CHECK_FD_SET(so, NetworkEvents, readfds)
1132 || WIN_CHECK_FD_SET(so, NetworkEvents, acceptds))
1133 {
1134 /*
1135 * Check for incoming connections
1136 */
1137 if (so->so_state & SS_FACCEPTCONN)
1138 {
1139 TCP_CONNECT(pData, so);
1140#if defined(RT_OS_WINDOWS)
1141 if (!CHECK_FD_SET(so, NetworkEvents, closefds))
1142#endif
1143 CONTINUE(tcp);
1144 }
1145
1146 ret = soread(pData, so);
1147 /* Output it if we read something */
1148 if (RT_LIKELY(ret > 0))
1149 TCP_OUTPUT(pData, sototcpcb(so));
1150 }
1151
1152#if defined(RT_OS_WINDOWS)
1153 /*
1154 * Check for FD_CLOSE events.
1155 * in some cases once FD_CLOSE engaged on socket it could be flashed latter (for some reasons)
1156 */
1157 if ( CHECK_FD_SET(so, NetworkEvents, closefds)
1158 || (so->so_close == 1))
1159 {
1160 /*
1161 * drain the socket
1162 */
1163 for (;;)
1164 {
1165 ret = soread(pData, so);
1166 if (ret > 0)
1167 TCP_OUTPUT(pData, sototcpcb(so));
1168 else
1169 break;
1170 }
1171 /* mark the socket for termination _after_ it was drained */
1172 so->so_close = 1;
1173 CONTINUE(tcp);
1174 }
1175#endif
1176
1177 /*
1178 * Check sockets for writing
1179 */
1180 if (CHECK_FD_SET(so, NetworkEvents, writefds))
1181 {
1182 /*
1183 * Check for non-blocking, still-connecting sockets
1184 */
1185 if (so->so_state & SS_ISFCONNECTING)
1186 {
1187 Log2(("connecting %R[natsock] catched\n", so));
1188 /* Connected */
1189 so->so_state &= ~SS_ISFCONNECTING;
1190
1191 /*
1192 * This should be probably guarded by PROBE_CONN too. Anyway,
1193 * we disable it on OS/2 because the below send call returns
1194 * EFAULT which causes the opened TCP socket to close right
1195 * after it has been opened and connected.
1196 */
1197#ifndef RT_OS_OS2
1198 ret = send(so->s, (const char *)&ret, 0, 0);
1199 if (ret < 0)
1200 {
1201 /* XXXXX Must fix, zero bytes is a NOP */
1202 if ( errno == EAGAIN
1203 || errno == EWOULDBLOCK
1204 || errno == EINPROGRESS
1205 || errno == ENOTCONN)
1206 CONTINUE(tcp);
1207
1208 /* else failed */
1209 so->so_state = SS_NOFDREF;
1210 }
1211 /* else so->so_state &= ~SS_ISFCONNECTING; */
1212#endif
1213
1214 /*
1215 * Continue tcp_input
1216 */
1217 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1218 /* continue; */
1219 }
1220 else
1221 SOWRITE(ret, pData, so);
1222 /*
1223 * XXX If we wrote something (a lot), there could be the need
1224 * for a window update. In the worst case, the remote will send
1225 * a window probe to get things going again.
1226 */
1227 }
1228
1229 /*
1230 * Probe a still-connecting, non-blocking socket
1231 * to check if it's still alive
1232 */
1233#ifdef PROBE_CONN
1234 if (so->so_state & SS_ISFCONNECTING)
1235 {
1236 ret = recv(so->s, (char *)&ret, 0, 0);
1237
1238 if (ret < 0)
1239 {
1240 /* XXX */
1241 if ( errno == EAGAIN
1242 || errno == EWOULDBLOCK
1243 || errno == EINPROGRESS
1244 || errno == ENOTCONN)
1245 {
1246 CONTINUE(tcp); /* Still connecting, continue */
1247 }
1248
1249 /* else failed */
1250 so->so_state = SS_NOFDREF;
1251
1252 /* tcp_input will take care of it */
1253 }
1254 else
1255 {
1256 ret = send(so->s, &ret, 0, 0);
1257 if (ret < 0)
1258 {
1259 /* XXX */
1260 if ( errno == EAGAIN
1261 || errno == EWOULDBLOCK
1262 || errno == EINPROGRESS
1263 || errno == ENOTCONN)
1264 {
1265 CONTINUE(tcp);
1266 }
1267 /* else failed */
1268 so->so_state = SS_NOFDREF;
1269 }
1270 else
1271 so->so_state &= ~SS_ISFCONNECTING;
1272
1273 }
1274 TCP_INPUT((struct mbuf *)NULL, sizeof(struct ip),so);
1275 } /* SS_ISFCONNECTING */
1276#endif
1277#ifndef RT_OS_WINDOWS
1278 if ( UNIX_CHECK_FD_SET(so, NetworkEvents, rdhup)
1279 || UNIX_CHECK_FD_SET(so, NetworkEvents, rderr))
1280 {
1281 int err;
1282 int inq, outq;
1283 int status;
1284 socklen_t optlen = sizeof(int);
1285 inq = outq = 0;
1286 status = getsockopt(so->s, SOL_SOCKET, SO_ERROR, &err, &optlen);
1287 if (status != 0)
1288 Log(("NAT: can't get error status from %R[natsock]\n", so));
1289#ifndef RT_OS_SOLARIS
1290 status = ioctl(so->s, FIONREAD, &inq); /* tcp(7) recommends SIOCINQ which is Linux specific */
1291 if (status != 0 || status != EINVAL)
1292 {
1293 /* EINVAL returned if socket in listen state tcp(7)*/
1294 Log(("NAT: can't get depth of IN queue status from %R[natsock]\n", so));
1295 }
1296 status = ioctl(so->s, TIOCOUTQ, &outq); /* SIOCOUTQ see previous comment */
1297 if (status != 0)
1298 Log(("NAT: can't get depth of OUT queue from %R[natsock]\n", so));
1299#else
1300 /*
1301 * Solaris has bit different ioctl commands and its handlings
1302 * hint: streamio(7) I_NREAD
1303 */
1304#endif
1305 if ( so->so_state & SS_ISFCONNECTING
1306 || UNIX_CHECK_FD_SET(so, NetworkEvents, readfds))
1307 {
1308 /**
1309 * Check if we need here take care about gracefull connection
1310 * @todo try with proxy server
1311 */
1312 if (UNIX_CHECK_FD_SET(so, NetworkEvents, readfds))
1313 {
1314 /*
1315 * Never meet inq != 0 or outq != 0, anyway let it stay for a while
1316 * in case it happens we'll able to detect it.
1317 * Give TCP/IP stack wait or expire the socket.
1318 */
1319 Log(("NAT: %R[natsock] err(%d:%s) s(in:%d,out:%d)happens on read I/O, "
1320 "other side close connection \n", so, err, strerror(err), inq, outq));
1321 CONTINUE(tcp);
1322 }
1323 goto tcp_input_close;
1324 }
1325 if ( !UNIX_CHECK_FD_SET(so, NetworkEvents, readfds)
1326 && !UNIX_CHECK_FD_SET(so, NetworkEvents, writefds)
1327 && !UNIX_CHECK_FD_SET(so, NetworkEvents, xfds))
1328 {
1329 Log(("NAT: system expires the socket %R[natsock] err(%d:%s) s(in:%d,out:%d) happens on non-I/O. ",
1330 so, err, strerror(err), inq, outq));
1331 goto tcp_input_close;
1332 }
1333 Log(("NAT: %R[natsock] we've met(%d:%s) s(in:%d, out:%d) unhandled combination hup (%d) "
1334 "rederr(%d) on (r:%d, w:%d, x:%d)\n",
1335 so, err, strerror(err),
1336 inq, outq,
1337 UNIX_CHECK_FD_SET(so, ign, rdhup),
1338 UNIX_CHECK_FD_SET(so, ign, rderr),
1339 UNIX_CHECK_FD_SET(so, ign, readfds),
1340 UNIX_CHECK_FD_SET(so, ign, writefds),
1341 UNIX_CHECK_FD_SET(so, ign, xfds)));
1342 /*
1343 * Give OS's TCP/IP stack a chance to resolve an issue or expire the socket.
1344 */
1345 CONTINUE(tcp);
1346tcp_input_close:
1347 so->so_state = SS_NOFDREF; /*cause connection valid tcp connection termination and socket closing */
1348 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1349 CONTINUE(tcp);
1350 }
1351#endif
1352 LOOP_LABEL(tcp, so, so_next);
1353 }
1354
1355 /*
1356 * Now UDP sockets.
1357 * Incoming packets are sent straight away, they're not buffered.
1358 * Incoming UDP data isn't buffered either.
1359 */
1360 QSOCKET_FOREACH(so, so_next, udp)
1361 /* { */
1362#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1363 if (pData->fmbuf_water_line == 1)
1364 {
1365 if (mbuf_alloced < pData->mbuf_water_line_limit/2)
1366 {
1367 pData->fmbuf_water_line = 0;
1368 pData->fmbuf_water_warn_sent = 0;
1369 }
1370 goto done;
1371 }
1372#endif
1373#ifdef VBOX_WITH_SLIRP_MT
1374 if ( so->so_state & SS_NOFDREF
1375 && so->so_deleted == 1)
1376 {
1377 struct socket *son, *sop = NULL;
1378 QSOCKET_LOCK(udb);
1379 if (so->so_next != NULL)
1380 {
1381 if (so->so_next != &udb)
1382 SOCKET_LOCK(so->so_next);
1383 son = so->so_next;
1384 }
1385 if ( so->so_prev != &udb
1386 && so->so_prev != NULL)
1387 {
1388 SOCKET_LOCK(so->so_prev);
1389 sop = so->so_prev;
1390 }
1391 QSOCKET_UNLOCK(udb);
1392 remque(pData, so);
1393 NSOCK_DEC();
1394 SOCKET_UNLOCK(so);
1395 SOCKET_LOCK_DESTROY(so);
1396 RTMemFree(so);
1397 so_next = son;
1398 if (sop != NULL)
1399 SOCKET_UNLOCK(sop);
1400 CONTINUE_NO_UNLOCK(udp);
1401 }
1402#endif
1403 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
1404
1405 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
1406
1407 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
1408 {
1409 SORECVFROM(pData, so);
1410 }
1411 LOOP_LABEL(udp, so, so_next);
1412 }
1413
1414done:
1415#if 0
1416 /*
1417 * See if we can start outputting
1418 */
1419 if (if_queued && link_up)
1420 if_start(pData);
1421#endif
1422
1423 STAM_PROFILE_STOP(&pData->StatPoll, a);
1424}
1425
1426
1427struct arphdr
1428{
1429 unsigned short ar_hrd; /* format of hardware address */
1430 unsigned short ar_pro; /* format of protocol address */
1431 unsigned char ar_hln; /* length of hardware address */
1432 unsigned char ar_pln; /* length of protocol address */
1433 unsigned short ar_op; /* ARP opcode (command) */
1434
1435 /*
1436 * Ethernet looks like this : This bit is variable sized however...
1437 */
1438 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1439 unsigned char ar_sip[4]; /* sender IP address */
1440 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1441 unsigned char ar_tip[4]; /* target IP address */
1442};
1443AssertCompileSize(struct arphdr, 28);
1444
1445static void arp_input(PNATState pData, struct mbuf *m)
1446{
1447 struct ethhdr *eh;
1448 struct ethhdr *reh;
1449 struct arphdr *ah;
1450 struct arphdr *rah;
1451 int ar_op;
1452 struct ex_list *ex_ptr;
1453 uint32_t htip;
1454 uint32_t tip;
1455 struct mbuf *mr;
1456 eh = mtod(m, struct ethhdr *);
1457 ah = (struct arphdr *)&eh[1];
1458 htip = RT_N2H_U32(*(uint32_t*)ah->ar_tip);
1459 tip = *(uint32_t*)ah->ar_tip;
1460
1461 ar_op = RT_N2H_U16(ah->ar_op);
1462
1463 switch (ar_op)
1464 {
1465 case ARPOP_REQUEST:
1466#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1467 mr = m_get(pData);
1468
1469 reh = mtod(mr, struct ethhdr *);
1470 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1471 Log4(("NAT: arp:%R[ether]->%R[ether]\n",
1472 reh->h_source, reh->h_dest));
1473 Log4(("NAT: arp: %R[IP4]\n", &tip));
1474
1475 mr->m_data += if_maxlinkhdr;
1476 mr->m_len = sizeof(struct arphdr);
1477 rah = mtod(mr, struct arphdr *);
1478#else
1479 mr = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
1480 reh = mtod(mr, struct ethhdr *);
1481 mr->m_data += ETH_HLEN;
1482 rah = mtod(mr, struct arphdr *);
1483 mr->m_len = sizeof(struct arphdr);
1484 Assert(mr);
1485 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1486#endif
1487#ifdef VBOX_WITH_NAT_SERVICE
1488 if (tip == pData->special_addr.s_addr)
1489 goto arp_ok;
1490#endif
1491 if ((htip & pData->netmask) == RT_N2H_U32(pData->special_addr.s_addr))
1492 {
1493 if ( CTL_CHECK(htip, CTL_DNS)
1494 || CTL_CHECK(htip, CTL_ALIAS)
1495 || CTL_CHECK(htip, CTL_TFTP))
1496 goto arp_ok;
1497 for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)
1498 {
1499 if ((htip & ~pData->netmask) == ex_ptr->ex_addr)
1500 {
1501 goto arp_ok;
1502 }
1503 }
1504 m_free(pData, m);
1505 m_free(pData, mr);
1506 return;
1507
1508 arp_ok:
1509 rah->ar_hrd = RT_H2N_U16_C(1);
1510 rah->ar_pro = RT_H2N_U16_C(ETH_P_IP);
1511 rah->ar_hln = ETH_ALEN;
1512 rah->ar_pln = 4;
1513 rah->ar_op = RT_H2N_U16_C(ARPOP_REPLY);
1514 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN);
1515
1516 switch (htip & ~pData->netmask)
1517 {
1518 case CTL_DNS:
1519 case CTL_ALIAS:
1520 rah->ar_sha[5] = (uint8_t)(htip & ~pData->netmask);
1521 break;
1522 default:;
1523 }
1524
1525 memcpy(rah->ar_sip, ah->ar_tip, 4);
1526 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
1527 memcpy(rah->ar_tip, ah->ar_sip, 4);
1528 if_encap(pData, ETH_P_ARP, mr, ETH_ENCAP_URG);
1529 m_free(pData, m);
1530 }
1531 /* Gratuitous ARP */
1532 if ( *(uint32_t *)ah->ar_sip == *(uint32_t *)ah->ar_tip
1533 && memcmp(ah->ar_tha, broadcast_ethaddr, ETH_ALEN) == 0
1534 && memcmp(eh->h_dest, broadcast_ethaddr, ETH_ALEN) == 0)
1535 {
1536 /* we've received anounce about address asignment
1537 * Let's do ARP cache update
1538 */
1539 if (slirp_arp_cache_update(pData, *(uint32_t *)ah->ar_tip, &eh->h_dest[0]) == 0)
1540 {
1541 m_free(pData, mr);
1542 m_free(pData, m);
1543 break;
1544 }
1545 slirp_arp_cache_add(pData, *(uint32_t *)ah->ar_tip, &eh->h_dest[0]);
1546 }
1547 break;
1548
1549 case ARPOP_REPLY:
1550 if (slirp_arp_cache_update(pData, *(uint32_t *)ah->ar_sip, &ah->ar_sha[0]) == 0)
1551 {
1552 m_free(pData, m);
1553 break;
1554 }
1555 slirp_arp_cache_add(pData, *(uint32_t *)ah->ar_sip, ah->ar_sha);
1556 m_free(pData, m);
1557 break;
1558
1559 default:
1560 break;
1561 }
1562}
1563
1564/**
1565 * Feed a packet into the slirp engine.
1566 *
1567 * @param m Data buffer, m_len is not valid.
1568 * @param cbBuf The length of the data in m.
1569 */
1570void slirp_input(PNATState pData, struct mbuf *m, size_t cbBuf)
1571{
1572 int proto;
1573 static bool fWarnedIpv6;
1574 struct ethhdr *eh;
1575 uint8_t au8Ether[ETH_ALEN];
1576
1577 m->m_len = cbBuf;
1578 if (cbBuf < ETH_HLEN)
1579 {
1580 LogRel(("NAT: packet having size %d has been ignored\n", m->m_len));
1581 m_free(pData, m);
1582 return;
1583 }
1584 eh = mtod(m, struct ethhdr *);
1585 proto = RT_N2H_U16(eh->h_proto);
1586
1587 memcpy(au8Ether, eh->h_source, ETH_ALEN);
1588
1589 switch(proto)
1590 {
1591 case ETH_P_ARP:
1592 arp_input(pData, m);
1593 break;
1594
1595 case ETH_P_IP:
1596 /* Update time. Important if the network is very quiet, as otherwise
1597 * the first outgoing connection gets an incorrect timestamp. */
1598 updtime(pData);
1599 m_adj(m, ETH_HLEN);
1600#ifdef VBOX_WITH_SLIRP_BSD_MBUF
1601 M_ASSERTPKTHDR(m);
1602 m->m_pkthdr.header = mtod(m, void *);
1603#else /* !VBOX_WITH_SLIRP_BSD_MBUF */
1604 if ( pData->fmbuf_water_line
1605 && pData->fmbuf_water_warn_sent == 0
1606 && (curtime - pData->tsmbuf_water_warn_sent) > 500)
1607 {
1608 icmp_error(pData, m, ICMP_SOURCEQUENCH, 0, 0, "Out of resources!!!");
1609 pData->fmbuf_water_warn_sent = 1;
1610 pData->tsmbuf_water_warn_sent = curtime;
1611 }
1612#endif /* !VBOX_WITH_SLIRP_BSD_MBUF */
1613 ip_input(pData, m);
1614 break;
1615
1616 case ETH_P_IPV6:
1617 m_free(pData, m);
1618 if (!fWarnedIpv6)
1619 {
1620 LogRel(("NAT: IPv6 not supported\n"));
1621 fWarnedIpv6 = true;
1622 }
1623 break;
1624
1625 default:
1626 Log(("NAT: Unsupported protocol %x\n", proto));
1627 m_free(pData, m);
1628 break;
1629 }
1630
1631 if (pData->cRedirectionsActive != pData->cRedirectionsStored)
1632 activate_port_forwarding(pData, au8Ether);
1633}
1634
1635/* output the IP packet to the ethernet device */
1636void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m, int flags)
1637{
1638 struct ethhdr *eh;
1639 uint8_t *buf = NULL;
1640 size_t mlen = 0;
1641 STAM_PROFILE_START(&pData->StatIF_encap, a);
1642
1643#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1644 m->m_data -= if_maxlinkhdr;
1645 m->m_len += ETH_HLEN;
1646 eh = mtod(m, struct ethhdr *);
1647
1648 if (MBUF_HEAD(m) != m->m_data)
1649 {
1650 LogRel(("NAT: ethernet detects corruption of the packet"));
1651 AssertMsgFailed(("!!Ethernet frame corrupted!!"));
1652 }
1653#else
1654 M_ASSERTPKTHDR(m);
1655 m->m_data -= ETH_HLEN;
1656 m->m_len += ETH_HLEN;
1657 eh = mtod(m, struct ethhdr *);
1658#endif
1659
1660 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) != 0)
1661 {
1662 memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
1663 memcpy(eh->h_source, special_ethaddr, ETH_ALEN);
1664 Assert(memcmp(eh->h_dest, special_ethaddr, ETH_ALEN) != 0);
1665 if (memcmp(eh->h_dest, zerro_ethaddr, ETH_ALEN) == 0)
1666 {
1667 /* don't do anything */
1668 m_free(pData, m);
1669 goto done;
1670 }
1671 }
1672#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1673 mlen = m->m_len;
1674#else
1675 mlen = m_length(m, NULL);
1676 buf = RTMemAlloc(mlen);
1677 if (buf == NULL)
1678 {
1679 LogRel(("NAT: Can't alloc memory for outgoing buffer\n"));
1680 m_free(pData, m);
1681 goto done;
1682 }
1683#endif
1684 eh->h_proto = RT_H2N_U16(eth_proto);
1685#ifdef VBOX_WITH_SLIRP_BSD_MBUF
1686 m_copydata(m, 0, mlen, (char *)buf);
1687 if (flags & ETH_ENCAP_URG)
1688 slirp_urg_output(pData->pvUser, m, buf, mlen);
1689 else
1690 slirp_output(pData->pvUser, m, buf, mlen);
1691#else
1692 if (flags & ETH_ENCAP_URG)
1693 slirp_urg_output(pData->pvUser, m, mtod(m, const uint8_t *), mlen);
1694 else
1695 slirp_output(pData->pvUser, m, mtod(m, const uint8_t *), mlen);
1696#endif
1697done:
1698 STAM_PROFILE_STOP(&pData->StatIF_encap, a);
1699}
1700
1701/**
1702 * Still we're using dhcp server leasing to map ether to IP
1703 * @todo see rt_lookup_in_cache
1704 */
1705static uint32_t find_guest_ip(PNATState pData, const uint8_t *eth_addr)
1706{
1707 uint32_t ip = INADDR_ANY;
1708 int rc;
1709
1710 if (eth_addr == NULL)
1711 return INADDR_ANY;
1712
1713 if ( memcmp(eth_addr, zerro_ethaddr, ETH_ALEN) == 0
1714 || memcmp(eth_addr, broadcast_ethaddr, ETH_ALEN) == 0)
1715 return INADDR_ANY;
1716
1717 rc = slirp_arp_lookup_ip_by_ether(pData, eth_addr, &ip);
1718 if (RT_SUCCESS(rc))
1719 return ip;
1720
1721 bootp_cache_lookup_ip_by_ether(pData, eth_addr, &ip);
1722 /* ignore return code, ip will be set to INADDR_ANY on error */
1723 return ip;
1724}
1725
1726/**
1727 * We need check if we've activated port forwarding
1728 * for specific machine ... that of course relates to
1729 * service mode
1730 * @todo finish this for service case
1731 */
1732static void activate_port_forwarding(PNATState pData, const uint8_t *h_source)
1733{
1734 struct port_forward_rule *rule;
1735
1736 /* check mac here */
1737 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1738 {
1739 struct socket *so;
1740 struct alias_link *alias_link;
1741 struct libalias *lib;
1742 int flags;
1743 struct sockaddr sa;
1744 struct sockaddr_in *psin;
1745 socklen_t socketlen;
1746 struct in_addr alias;
1747 int rc;
1748 uint32_t guest_addr; /* need to understand if we already give address to guest */
1749
1750 if (rule->activated)
1751 continue;
1752
1753#ifdef VBOX_WITH_NAT_SERVICE
1754 if (memcmp(rule->mac_address, h_source, ETH_ALEN) != 0)
1755 continue; /*not right mac, @todo: it'd be better do the list port forwarding per mac */
1756 guest_addr = find_guest_ip(pData, h_source);
1757#else
1758#if 0
1759 if (memcmp(client_ethaddr, h_source, ETH_ALEN) != 0)
1760 continue;
1761#endif
1762 guest_addr = find_guest_ip(pData, h_source);
1763#endif
1764 if (guest_addr == INADDR_ANY)
1765 {
1766 /* the address wasn't granted */
1767 return;
1768 }
1769
1770#if !defined(VBOX_WITH_NAT_SERVICE)
1771 if (rule->guest_addr.s_addr != guest_addr)
1772 continue;
1773#endif
1774
1775 LogRel(("NAT: set redirect %s host port %d => guest port %d @ %R[IP4]\n",
1776 (rule->proto == IPPROTO_UDP?"UDP":"TCP"),
1777 rule->host_port, rule->guest_port, &guest_addr));
1778
1779 if (rule->proto == IPPROTO_UDP)
1780 so = udp_listen(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1781 RT_H2N_U16(rule->guest_port), 0);
1782 else
1783 so = solisten(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1784 RT_H2N_U16(rule->guest_port), 0);
1785
1786 if (so == NULL)
1787 goto remove_port_forwarding;
1788
1789 psin = (struct sockaddr_in *)&sa;
1790 psin->sin_family = AF_INET;
1791 psin->sin_port = 0;
1792 psin->sin_addr.s_addr = INADDR_ANY;
1793 socketlen = sizeof(struct sockaddr);
1794
1795 rc = getsockname(so->s, &sa, &socketlen);
1796 if (rc < 0 || sa.sa_family != AF_INET)
1797 goto remove_port_forwarding;
1798
1799 psin = (struct sockaddr_in *)&sa;
1800
1801 lib = LibAliasInit(pData, NULL);
1802 flags = LibAliasSetMode(lib, 0, 0);
1803 flags |= PKT_ALIAS_LOG; /* set logging */
1804 flags |= PKT_ALIAS_REVERSE; /* set logging */
1805 flags = LibAliasSetMode(lib, flags, ~0);
1806
1807 alias.s_addr = RT_H2N_U32(RT_N2H_U32(guest_addr) | CTL_ALIAS);
1808 alias_link = LibAliasRedirectPort(lib, psin->sin_addr, RT_H2N_U16(rule->host_port),
1809 alias, RT_H2N_U16(rule->guest_port),
1810 pData->special_addr, -1, /* not very clear for now */
1811 rule->proto);
1812 if (!alias_link)
1813 goto remove_port_forwarding;
1814
1815 so->so_la = lib;
1816 rule->activated = 1;
1817 pData->cRedirectionsActive++;
1818 continue;
1819
1820 remove_port_forwarding:
1821 LogRel(("NAT: failed to redirect %s %d => %d\n",
1822 (rule->proto == IPPROTO_UDP?"UDP":"TCP"), rule->host_port, rule->guest_port));
1823 LIST_REMOVE(rule, list);
1824 pData->cRedirectionsStored--;
1825 RTMemFree(rule);
1826 }
1827}
1828
1829/**
1830 * Changes in 3.1 instead of opening new socket do the following:
1831 * gain more information:
1832 * 1. bind IP
1833 * 2. host port
1834 * 3. guest port
1835 * 4. proto
1836 * 5. guest MAC address
1837 * the guest's MAC address is rather important for service, but we easily
1838 * could get it from VM configuration in DrvNAT or Service, the idea is activating
1839 * corresponding port-forwarding
1840 */
1841int slirp_redir(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1842 struct in_addr guest_addr, int guest_port, const uint8_t *ethaddr)
1843{
1844 struct port_forward_rule *rule = NULL;
1845 Assert(memcmp(ethaddr, zerro_ethaddr, ETH_ALEN) == 0);
1846
1847 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1848 if (rule == NULL)
1849 return 1;
1850
1851 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1852 rule->host_port = host_port;
1853 rule->guest_port = guest_port;
1854#ifndef VBOX_WITH_NAT_SERVICE
1855 rule->guest_addr.s_addr = guest_addr.s_addr;
1856#endif
1857 rule->bind_ip.s_addr = host_addr.s_addr;
1858 memcpy(rule->mac_address, ethaddr, ETH_ALEN);
1859 /* @todo add mac address */
1860 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1861 pData->cRedirectionsStored++;
1862 return 0;
1863}
1864
1865int slirp_add_exec(PNATState pData, int do_pty, const char *args, int addr_low_byte,
1866 int guest_port)
1867{
1868 return add_exec(&exec_list, do_pty, (char *)args,
1869 addr_low_byte, RT_H2N_U16(guest_port));
1870}
1871
1872void slirp_set_ethaddr_and_activate_port_forwarding(PNATState pData, const uint8_t *ethaddr, uint32_t GuestIP)
1873{
1874#ifndef VBOX_WITH_NAT_SERVICE
1875 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1876#endif
1877 if (GuestIP != INADDR_ANY)
1878 {
1879 slirp_arp_cache_update_or_add(pData, GuestIP, ethaddr);
1880 activate_port_forwarding(pData, ethaddr);
1881 }
1882}
1883
1884#if defined(RT_OS_WINDOWS)
1885HANDLE *slirp_get_events(PNATState pData)
1886{
1887 return pData->phEvents;
1888}
1889void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1890{
1891 pData->phEvents[index] = hEvent;
1892}
1893#endif
1894
1895unsigned int slirp_get_timeout_ms(PNATState pData)
1896{
1897 if (link_up)
1898 {
1899 if (time_fasttimo)
1900 return 2;
1901 if (do_slowtimo)
1902 return 500; /* see PR_SLOWHZ */
1903 }
1904 return 0;
1905}
1906
1907#ifndef RT_OS_WINDOWS
1908int slirp_get_nsock(PNATState pData)
1909{
1910 return pData->nsock;
1911}
1912#endif
1913
1914/*
1915 * this function called from NAT thread
1916 */
1917void slirp_post_sent(PNATState pData, void *pvArg)
1918{
1919 struct socket *so = 0;
1920 struct tcpcb *tp = 0;
1921 struct mbuf *m = (struct mbuf *)pvArg;
1922 m_free(pData, m);
1923}
1924#ifdef VBOX_WITH_SLIRP_MT
1925void slirp_process_queue(PNATState pData)
1926{
1927 RTReqProcess(pData->pReqQueue, RT_INDEFINITE_WAIT);
1928}
1929void *slirp_get_queue(PNATState pData)
1930{
1931 return pData->pReqQueue;
1932}
1933#endif
1934
1935void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1936{
1937 Log2(("tftp_prefix:%s\n", tftpPrefix));
1938 tftp_prefix = tftpPrefix;
1939}
1940
1941void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1942{
1943 Log2(("bootFile:%s\n", bootFile));
1944 bootp_filename = bootFile;
1945}
1946
1947void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1948{
1949 Log2(("next_server:%s\n", next_server));
1950 if (next_server == NULL)
1951 pData->tftp_server.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_TFTP);
1952 else
1953 inet_aton(next_server, &pData->tftp_server);
1954}
1955
1956int slirp_set_binding_address(PNATState pData, char *addr)
1957{
1958 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1959 {
1960 pData->bindIP.s_addr = INADDR_ANY;
1961 return 1;
1962 }
1963 return 0;
1964}
1965
1966void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1967{
1968 if (!pData->use_host_resolver)
1969 {
1970 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1971 pData->use_dns_proxy = fDNSProxy;
1972 }
1973 else
1974 LogRel(("NAT: Host Resolver conflicts with DNS proxy, the last one was forcely ignored\n"));
1975}
1976
1977#define CHECK_ARG(name, val, lim_min, lim_max) \
1978 do { \
1979 if ((val) < (lim_min) || (val) > (lim_max)) \
1980 { \
1981 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1982 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1983 return; \
1984 } \
1985 else \
1986 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1987 } while (0)
1988
1989/* don't allow user set less 8kB and more than 1M values */
1990#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
1991void slirp_set_rcvbuf(PNATState pData, int kilobytes)
1992{
1993 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
1994 pData->socket_rcv = kilobytes;
1995}
1996void slirp_set_sndbuf(PNATState pData, int kilobytes)
1997{
1998 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
1999 pData->socket_snd = kilobytes * _1K;
2000}
2001void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
2002{
2003 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
2004 tcp_rcvspace = kilobytes * _1K;
2005}
2006void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
2007{
2008 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
2009 tcp_sndspace = kilobytes * _1K;
2010}
2011
2012/*
2013 * Looking for Ether by ip in ARP-cache
2014 * Note: it´s responsible of caller to allocate buffer for result
2015 * @returns iprt status code
2016 */
2017int slirp_arp_lookup_ether_by_ip(PNATState pData, uint32_t ip, uint8_t *ether)
2018{
2019 struct arp_cache_entry *ac;
2020
2021 if (ether == NULL)
2022 return VERR_INVALID_PARAMETER;
2023
2024 if (LIST_EMPTY(&pData->arp_cache))
2025 return VERR_NOT_FOUND;
2026
2027 LIST_FOREACH(ac, &pData->arp_cache, list)
2028 {
2029 if (ac->ip == ip)
2030 {
2031 memcpy(ether, ac->ether, ETH_ALEN);
2032 return VINF_SUCCESS;
2033 }
2034 }
2035 return VERR_NOT_FOUND;
2036}
2037
2038/*
2039 * Looking for IP by Ether in ARP-cache
2040 * Note: it´s responsible of caller to allocate buffer for result
2041 * @returns 0 - if found, 1 - otherwise
2042 */
2043int slirp_arp_lookup_ip_by_ether(PNATState pData, const uint8_t *ether, uint32_t *ip)
2044{
2045 struct arp_cache_entry *ac;
2046 *ip = INADDR_ANY;
2047
2048 if (LIST_EMPTY(&pData->arp_cache))
2049 return VERR_NOT_FOUND;
2050
2051 LIST_FOREACH(ac, &pData->arp_cache, list)
2052 {
2053 if (memcmp(ether, ac->ether, ETH_ALEN) == 0)
2054 {
2055 *ip = ac->ip;
2056 return VINF_SUCCESS;
2057 }
2058 }
2059 return VERR_NOT_FOUND;
2060}
2061
2062void slirp_arp_who_has(PNATState pData, uint32_t dst)
2063{
2064 struct mbuf *m;
2065 struct ethhdr *ehdr;
2066 struct arphdr *ahdr;
2067
2068#ifndef VBOX_WITH_SLIRP_BSD_MBUF
2069 m = m_get(pData);
2070#else
2071 m = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
2072#endif
2073 if (m == NULL)
2074 {
2075 LogRel(("NAT: Can't alloc mbuf for ARP request\n"));
2076 return;
2077 }
2078 ehdr = mtod(m, struct ethhdr *);
2079 memset(ehdr->h_source, 0xff, ETH_ALEN);
2080 ahdr = (struct arphdr *)&ehdr[1];
2081 ahdr->ar_hrd = RT_H2N_U16_C(1);
2082 ahdr->ar_pro = RT_H2N_U16_C(ETH_P_IP);
2083 ahdr->ar_hln = ETH_ALEN;
2084 ahdr->ar_pln = 4;
2085 ahdr->ar_op = RT_H2N_U16_C(ARPOP_REQUEST);
2086 memcpy(ahdr->ar_sha, special_ethaddr, ETH_ALEN);
2087 *(uint32_t *)ahdr->ar_sip = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
2088 memset(ahdr->ar_tha, 0xff, ETH_ALEN); /*broadcast*/
2089 *(uint32_t *)ahdr->ar_tip = dst;
2090#ifndef VBOX_WITH_SLIRP_BSD_MBUF
2091 m->m_data += if_maxlinkhdr;
2092 m->m_len = sizeof(struct arphdr);
2093#else
2094 /* warn!!! should falls in mbuf minimal size */
2095 m->m_len = sizeof(struct arphdr) + ETH_HLEN;
2096#endif
2097 if_encap(pData, ETH_P_ARP, m, ETH_ENCAP_URG);
2098}
2099
2100int slirp_arp_cache_update_or_add(PNATState pData, uint32_t dst, const uint8_t *mac)
2101{
2102 if (slirp_arp_cache_update(pData, dst, mac))
2103 slirp_arp_cache_add(pData, dst, mac);
2104
2105 return 0;
2106}
2107
2108/* updates the arp cache
2109 * @returns 0 - if has found and updated
2110 * 1 - if hasn't found.
2111 */
2112int slirp_arp_cache_update(PNATState pData, uint32_t dst, const uint8_t *mac)
2113{
2114 struct arp_cache_entry *ac;
2115 LIST_FOREACH(ac, &pData->arp_cache, list)
2116 {
2117 if (memcmp(ac->ether, mac, ETH_ALEN) == 0)
2118 {
2119 ac->ip = dst;
2120 return 0;
2121 }
2122 }
2123 return 1;
2124}
2125
2126void slirp_arp_cache_add(PNATState pData, uint32_t ip, const uint8_t *ether)
2127{
2128 struct arp_cache_entry *ac = NULL;
2129 ac = RTMemAllocZ(sizeof(struct arp_cache_entry));
2130 if (ac == NULL)
2131 {
2132 LogRel(("NAT: Can't allocate arp cache entry\n"));
2133 return;
2134 }
2135 ac->ip = ip;
2136 memcpy(ac->ether, ether, ETH_ALEN);
2137 LIST_INSERT_HEAD(&pData->arp_cache, ac, list);
2138}
2139
2140#ifdef VBOX_WITH_SLIRP_BSD_MBUF
2141void slirp_set_mtu(PNATState pData, int mtu)
2142{
2143 if (mtu < 20 || mtu >= 16000)
2144 {
2145 LogRel(("NAT: mtu(%d) is out of range (20;16000] mtu forcely assigned to 1500\n", mtu));
2146 mtu = 1500;
2147 }
2148 if_mtu =
2149 if_mru = mtu;
2150}
2151#endif
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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