VirtualBox

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

Last change on this file since 26598 was 26574, checked in by vboxsync, 15 years ago

Networking: Preparing to make the driver return a send buffer to the device emulation.

  • Property svn:eol-style set to native
File size: 65.9 KB
Line 
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 so->so_close = 1; /* mark it */
1161 /*
1162 * drain the socket
1163 */
1164 for (;;)
1165 {
1166 ret = soread(pData, so);
1167 if (ret > 0)
1168 TCP_OUTPUT(pData, sototcpcb(so));
1169 else
1170 break;
1171 }
1172 CONTINUE(tcp);
1173 }
1174#endif
1175
1176 /*
1177 * Check sockets for writing
1178 */
1179 if (CHECK_FD_SET(so, NetworkEvents, writefds))
1180 {
1181 /*
1182 * Check for non-blocking, still-connecting sockets
1183 */
1184 if (so->so_state & SS_ISFCONNECTING)
1185 {
1186 Log2(("connecting %R[natsock] catched\n", so));
1187 /* Connected */
1188 so->so_state &= ~SS_ISFCONNECTING;
1189
1190 /*
1191 * This should be probably guarded by PROBE_CONN too. Anyway,
1192 * we disable it on OS/2 because the below send call returns
1193 * EFAULT which causes the opened TCP socket to close right
1194 * after it has been opened and connected.
1195 */
1196#ifndef RT_OS_OS2
1197 ret = send(so->s, (const char *)&ret, 0, 0);
1198 if (ret < 0)
1199 {
1200 /* XXXXX Must fix, zero bytes is a NOP */
1201 if ( errno == EAGAIN
1202 || errno == EWOULDBLOCK
1203 || errno == EINPROGRESS
1204 || errno == ENOTCONN)
1205 CONTINUE(tcp);
1206
1207 /* else failed */
1208 so->so_state = SS_NOFDREF;
1209 }
1210 /* else so->so_state &= ~SS_ISFCONNECTING; */
1211#endif
1212
1213 /*
1214 * Continue tcp_input
1215 */
1216 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1217 /* continue; */
1218 }
1219 else
1220 SOWRITE(ret, pData, so);
1221 /*
1222 * XXX If we wrote something (a lot), there could be the need
1223 * for a window update. In the worst case, the remote will send
1224 * a window probe to get things going again.
1225 */
1226 }
1227
1228 /*
1229 * Probe a still-connecting, non-blocking socket
1230 * to check if it's still alive
1231 */
1232#ifdef PROBE_CONN
1233 if (so->so_state & SS_ISFCONNECTING)
1234 {
1235 ret = recv(so->s, (char *)&ret, 0, 0);
1236
1237 if (ret < 0)
1238 {
1239 /* XXX */
1240 if ( errno == EAGAIN
1241 || errno == EWOULDBLOCK
1242 || errno == EINPROGRESS
1243 || errno == ENOTCONN)
1244 {
1245 CONTINUE(tcp); /* Still connecting, continue */
1246 }
1247
1248 /* else failed */
1249 so->so_state = SS_NOFDREF;
1250
1251 /* tcp_input will take care of it */
1252 }
1253 else
1254 {
1255 ret = send(so->s, &ret, 0, 0);
1256 if (ret < 0)
1257 {
1258 /* XXX */
1259 if ( errno == EAGAIN
1260 || errno == EWOULDBLOCK
1261 || errno == EINPROGRESS
1262 || errno == ENOTCONN)
1263 {
1264 CONTINUE(tcp);
1265 }
1266 /* else failed */
1267 so->so_state = SS_NOFDREF;
1268 }
1269 else
1270 so->so_state &= ~SS_ISFCONNECTING;
1271
1272 }
1273 TCP_INPUT((struct mbuf *)NULL, sizeof(struct ip),so);
1274 } /* SS_ISFCONNECTING */
1275#endif
1276#ifndef RT_OS_WINDOWS
1277 if ( UNIX_CHECK_FD_SET(so, NetworkEvents, rdhup)
1278 || UNIX_CHECK_FD_SET(so, NetworkEvents, rderr))
1279 {
1280 int err;
1281 int inq, outq;
1282 int status;
1283 socklen_t optlen = sizeof(int);
1284 inq = outq = 0;
1285 status = getsockopt(so->s, SOL_SOCKET, SO_ERROR, &err, &optlen);
1286 if (status != 0)
1287 Log(("NAT: can't get error status from %R[natsock]\n", so));
1288#ifndef RT_OS_SOLARIS
1289 status = ioctl(so->s, FIONREAD, &inq); /* tcp(7) recommends SIOCINQ which is Linux specific */
1290 if (status != 0 || status != EINVAL)
1291 {
1292 /* EINVAL returned if socket in listen state tcp(7)*/
1293 Log(("NAT: can't get depth of IN queue status from %R[natsock]\n", so));
1294 }
1295 status = ioctl(so->s, TIOCOUTQ, &outq); /* SIOCOUTQ see previous comment */
1296 if (status != 0)
1297 Log(("NAT: can't get depth of OUT queue from %R[natsock]\n", so));
1298#else
1299 /*
1300 * Solaris has bit different ioctl commands and its handlings
1301 * hint: streamio(7) I_NREAD
1302 */
1303#endif
1304 if ( so->so_state & SS_ISFCONNECTING
1305 || UNIX_CHECK_FD_SET(so, NetworkEvents, readfds))
1306 {
1307 /**
1308 * Check if we need here take care about gracefull connection
1309 * @todo try with proxy server
1310 */
1311 if (UNIX_CHECK_FD_SET(so, NetworkEvents, readfds))
1312 {
1313 /*
1314 * Never meet inq != 0 or outq != 0, anyway let it stay for a while
1315 * in case it happens we'll able to detect it.
1316 * Give TCP/IP stack wait or expire the socket.
1317 */
1318 Log(("NAT: %R[natsock] err(%d:%s) s(in:%d,out:%d)happens on read I/O, "
1319 "other side close connection \n", so, err, strerror(err), inq, outq));
1320 CONTINUE(tcp);
1321 }
1322 goto tcp_input_close;
1323 }
1324 if ( !UNIX_CHECK_FD_SET(so, NetworkEvents, readfds)
1325 && !UNIX_CHECK_FD_SET(so, NetworkEvents, writefds)
1326 && !UNIX_CHECK_FD_SET(so, NetworkEvents, xfds))
1327 {
1328 Log(("NAT: system expires the socket %R[natsock] err(%d:%s) s(in:%d,out:%d) happens on non-I/O. ",
1329 so, err, strerror(err), inq, outq));
1330 goto tcp_input_close;
1331 }
1332 Log(("NAT: %R[natsock] we've met(%d:%s) s(in:%d, out:%d) unhandled combination hup (%d) "
1333 "rederr(%d) on (r:%d, w:%d, x:%d)\n",
1334 so, err, strerror(err),
1335 inq, outq,
1336 UNIX_CHECK_FD_SET(so, ign, rdhup),
1337 UNIX_CHECK_FD_SET(so, ign, rderr),
1338 UNIX_CHECK_FD_SET(so, ign, readfds),
1339 UNIX_CHECK_FD_SET(so, ign, writefds),
1340 UNIX_CHECK_FD_SET(so, ign, xfds)));
1341 /*
1342 * Give OS's TCP/IP stack a chance to resolve an issue or expire the socket.
1343 */
1344 CONTINUE(tcp);
1345tcp_input_close:
1346 so->so_state = SS_NOFDREF; /*cause connection valid tcp connection termination and socket closing */
1347 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1348 CONTINUE(tcp);
1349 }
1350#endif
1351 LOOP_LABEL(tcp, so, so_next);
1352 }
1353
1354 /*
1355 * Now UDP sockets.
1356 * Incoming packets are sent straight away, they're not buffered.
1357 * Incoming UDP data isn't buffered either.
1358 */
1359 QSOCKET_FOREACH(so, so_next, udp)
1360 /* { */
1361#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1362 if (pData->fmbuf_water_line == 1)
1363 {
1364 if (mbuf_alloced < pData->mbuf_water_line_limit/2)
1365 {
1366 pData->fmbuf_water_line = 0;
1367 pData->fmbuf_water_warn_sent = 0;
1368 }
1369 goto done;
1370 }
1371#endif
1372#ifdef VBOX_WITH_SLIRP_MT
1373 if ( so->so_state & SS_NOFDREF
1374 && so->so_deleted == 1)
1375 {
1376 struct socket *son, *sop = NULL;
1377 QSOCKET_LOCK(udb);
1378 if (so->so_next != NULL)
1379 {
1380 if (so->so_next != &udb)
1381 SOCKET_LOCK(so->so_next);
1382 son = so->so_next;
1383 }
1384 if ( so->so_prev != &udb
1385 && so->so_prev != NULL)
1386 {
1387 SOCKET_LOCK(so->so_prev);
1388 sop = so->so_prev;
1389 }
1390 QSOCKET_UNLOCK(udb);
1391 remque(pData, so);
1392 NSOCK_DEC();
1393 SOCKET_UNLOCK(so);
1394 SOCKET_LOCK_DESTROY(so);
1395 RTMemFree(so);
1396 so_next = son;
1397 if (sop != NULL)
1398 SOCKET_UNLOCK(sop);
1399 CONTINUE_NO_UNLOCK(udp);
1400 }
1401#endif
1402 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
1403
1404 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
1405
1406 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
1407 {
1408 SORECVFROM(pData, so);
1409 }
1410 LOOP_LABEL(udp, so, so_next);
1411 }
1412
1413done:
1414#if 0
1415 /*
1416 * See if we can start outputting
1417 */
1418 if (if_queued && link_up)
1419 if_start(pData);
1420#endif
1421
1422 STAM_PROFILE_STOP(&pData->StatPoll, a);
1423}
1424
1425
1426struct arphdr
1427{
1428 unsigned short ar_hrd; /* format of hardware address */
1429 unsigned short ar_pro; /* format of protocol address */
1430 unsigned char ar_hln; /* length of hardware address */
1431 unsigned char ar_pln; /* length of protocol address */
1432 unsigned short ar_op; /* ARP opcode (command) */
1433
1434 /*
1435 * Ethernet looks like this : This bit is variable sized however...
1436 */
1437 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1438 unsigned char ar_sip[4]; /* sender IP address */
1439 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1440 unsigned char ar_tip[4]; /* target IP address */
1441};
1442AssertCompileSize(struct arphdr, 28);
1443
1444static void arp_input(PNATState pData, struct mbuf *m)
1445{
1446 struct ethhdr *eh;
1447 struct ethhdr *reh;
1448 struct arphdr *ah;
1449 struct arphdr *rah;
1450 int ar_op;
1451 struct ex_list *ex_ptr;
1452 uint32_t htip;
1453 uint32_t tip;
1454 struct mbuf *mr;
1455 eh = mtod(m, struct ethhdr *);
1456 ah = (struct arphdr *)&eh[1];
1457 htip = RT_N2H_U32(*(uint32_t*)ah->ar_tip);
1458 tip = *(uint32_t*)ah->ar_tip;
1459
1460 ar_op = RT_N2H_U16(ah->ar_op);
1461
1462 switch (ar_op)
1463 {
1464 case ARPOP_REQUEST:
1465#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1466 mr = m_get(pData);
1467
1468 reh = mtod(mr, struct ethhdr *);
1469 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1470 Log4(("NAT: arp:%R[ether]->%R[ether]\n",
1471 reh->h_source, reh->h_dest));
1472 Log4(("NAT: arp: %R[IP4]\n", &tip));
1473
1474 mr->m_data += if_maxlinkhdr;
1475 mr->m_len = sizeof(struct arphdr);
1476 rah = mtod(mr, struct arphdr *);
1477#else
1478 mr = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
1479 reh = mtod(mr, struct ethhdr *);
1480 mr->m_data += ETH_HLEN;
1481 rah = mtod(mr, struct arphdr *);
1482 mr->m_len = sizeof(struct arphdr);
1483 Assert(mr);
1484 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1485#endif
1486#ifdef VBOX_WITH_NAT_SERVICE
1487 if (tip == pData->special_addr.s_addr)
1488 goto arp_ok;
1489#endif
1490 if ((htip & pData->netmask) == RT_N2H_U32(pData->special_addr.s_addr))
1491 {
1492 if ( CTL_CHECK(htip, CTL_DNS)
1493 || CTL_CHECK(htip, CTL_ALIAS)
1494 || CTL_CHECK(htip, CTL_TFTP))
1495 goto arp_ok;
1496 for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)
1497 {
1498 if ((htip & ~pData->netmask) == ex_ptr->ex_addr)
1499 {
1500 goto arp_ok;
1501 }
1502 }
1503 m_free(pData, m);
1504 m_free(pData, mr);
1505 return;
1506
1507 arp_ok:
1508 rah->ar_hrd = RT_H2N_U16_C(1);
1509 rah->ar_pro = RT_H2N_U16_C(ETH_P_IP);
1510 rah->ar_hln = ETH_ALEN;
1511 rah->ar_pln = 4;
1512 rah->ar_op = RT_H2N_U16_C(ARPOP_REPLY);
1513 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN);
1514
1515 switch (htip & ~pData->netmask)
1516 {
1517 case CTL_DNS:
1518 case CTL_ALIAS:
1519 rah->ar_sha[5] = (uint8_t)(htip & ~pData->netmask);
1520 break;
1521 default:;
1522 }
1523
1524 memcpy(rah->ar_sip, ah->ar_tip, 4);
1525 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
1526 memcpy(rah->ar_tip, ah->ar_sip, 4);
1527 if_encap(pData, ETH_P_ARP, mr, ETH_ENCAP_URG);
1528 m_free(pData, m);
1529 }
1530 /* Gratuitous ARP */
1531 if ( *(uint32_t *)ah->ar_sip == *(uint32_t *)ah->ar_tip
1532 && memcmp(ah->ar_tha, broadcast_ethaddr, ETH_ALEN) == 0
1533 && memcmp(eh->h_dest, broadcast_ethaddr, ETH_ALEN) == 0)
1534 {
1535 /* we've received anounce about address asignment
1536 * Let's do ARP cache update
1537 */
1538 if (slirp_arp_cache_update(pData, *(uint32_t *)ah->ar_tip, &eh->h_dest[0]) == 0)
1539 {
1540 m_free(pData, mr);
1541 m_free(pData, m);
1542 break;
1543 }
1544 slirp_arp_cache_add(pData, *(uint32_t *)ah->ar_tip, &eh->h_dest[0]);
1545 }
1546 break;
1547
1548 case ARPOP_REPLY:
1549 if (slirp_arp_cache_update(pData, *(uint32_t *)ah->ar_sip, &ah->ar_sha[0]) == 0)
1550 {
1551 m_free(pData, m);
1552 break;
1553 }
1554 slirp_arp_cache_add(pData, *(uint32_t *)ah->ar_sip, ah->ar_sha);
1555 m_free(pData, m);
1556 break;
1557
1558 default:
1559 break;
1560 }
1561}
1562
1563/**
1564 * Feed a packet into the slirp engine.
1565 *
1566 * @param m Data buffer, m_len is not valid.
1567 * @param cbBuf The length of the data in m.
1568 */
1569void slirp_input(PNATState pData, struct mbuf *m, size_t cbBuf)
1570{
1571 int proto;
1572 static bool fWarnedIpv6;
1573 struct ethhdr *eh;
1574 uint8_t au8Ether[ETH_ALEN];
1575
1576 m->m_len = cbBuf;
1577 if (cbBuf < ETH_HLEN)
1578 {
1579 LogRel(("NAT: packet having size %d has been ignored\n", m->m_len));
1580 m_free(pData, m);
1581 return;
1582 }
1583 eh = mtod(m, struct ethhdr *);
1584 proto = RT_N2H_U16(eh->h_proto);
1585
1586 memcpy(au8Ether, eh->h_source, ETH_ALEN);
1587
1588 switch(proto)
1589 {
1590 case ETH_P_ARP:
1591 arp_input(pData, m);
1592 break;
1593
1594 case ETH_P_IP:
1595 /* Update time. Important if the network is very quiet, as otherwise
1596 * the first outgoing connection gets an incorrect timestamp. */
1597 updtime(pData);
1598 m_adj(m, ETH_HLEN);
1599#ifdef VBOX_WITH_SLIRP_BSD_MBUF
1600 M_ASSERTPKTHDR(m);
1601 m->m_pkthdr.header = mtod(m, void *);
1602#else /* !VBOX_WITH_SLIRP_BSD_MBUF */
1603 if ( pData->fmbuf_water_line
1604 && pData->fmbuf_water_warn_sent == 0
1605 && (curtime - pData->tsmbuf_water_warn_sent) > 500)
1606 {
1607 icmp_error(pData, m, ICMP_SOURCEQUENCH, 0, 0, "Out of resources!!!");
1608 pData->fmbuf_water_warn_sent = 1;
1609 pData->tsmbuf_water_warn_sent = curtime;
1610 }
1611#endif /* !VBOX_WITH_SLIRP_BSD_MBUF */
1612 ip_input(pData, m);
1613 break;
1614
1615 case ETH_P_IPV6:
1616 m_free(pData, m);
1617 if (!fWarnedIpv6)
1618 {
1619 LogRel(("NAT: IPv6 not supported\n"));
1620 fWarnedIpv6 = true;
1621 }
1622 break;
1623
1624 default:
1625 Log(("NAT: Unsupported protocol %x\n", proto));
1626 m_free(pData, m);
1627 break;
1628 }
1629
1630 if (pData->cRedirectionsActive != pData->cRedirectionsStored)
1631 activate_port_forwarding(pData, au8Ether);
1632}
1633
1634/* output the IP packet to the ethernet device */
1635void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m, int flags)
1636{
1637 struct ethhdr *eh;
1638 uint8_t *buf = NULL;
1639 size_t mlen = 0;
1640 STAM_PROFILE_START(&pData->StatIF_encap, a);
1641
1642#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1643 m->m_data -= if_maxlinkhdr;
1644 m->m_len += ETH_HLEN;
1645 eh = mtod(m, struct ethhdr *);
1646
1647 if (MBUF_HEAD(m) != m->m_data)
1648 {
1649 LogRel(("NAT: ethernet detects corruption of the packet"));
1650 AssertMsgFailed(("!!Ethernet frame corrupted!!"));
1651 }
1652#else
1653 M_ASSERTPKTHDR(m);
1654 m->m_data -= ETH_HLEN;
1655 m->m_len += ETH_HLEN;
1656 eh = mtod(m, struct ethhdr *);
1657#endif
1658
1659 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) != 0)
1660 {
1661 memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
1662 memcpy(eh->h_source, special_ethaddr, ETH_ALEN);
1663 Assert(memcmp(eh->h_dest, special_ethaddr, ETH_ALEN) != 0);
1664 if (memcmp(eh->h_dest, zerro_ethaddr, ETH_ALEN) == 0)
1665 {
1666 /* don't do anything */
1667 m_free(pData, m);
1668 goto done;
1669 }
1670 }
1671#ifndef VBOX_WITH_SLIRP_BSD_MBUF
1672 mlen = m->m_len;
1673#else
1674 mlen = m_length(m, NULL);
1675 buf = RTMemAlloc(mlen);
1676 if (buf == NULL)
1677 {
1678 LogRel(("NAT: Can't alloc memory for outgoing buffer\n"));
1679 m_free(pData, m);
1680 goto done;
1681 }
1682#endif
1683 eh->h_proto = RT_H2N_U16(eth_proto);
1684#ifdef VBOX_WITH_SLIRP_BSD_MBUF
1685 m_copydata(m, 0, mlen, (char *)buf);
1686 if (flags & ETH_ENCAP_URG)
1687 slirp_urg_output(pData->pvUser, m, buf, mlen);
1688 else
1689 slirp_output(pData->pvUser, m, buf, mlen);
1690#else
1691 if (flags & ETH_ENCAP_URG)
1692 slirp_urg_output(pData->pvUser, m, mtod(m, const uint8_t *), mlen);
1693 else
1694 slirp_output(pData->pvUser, m, mtod(m, const uint8_t *), mlen);
1695#endif
1696done:
1697 STAM_PROFILE_STOP(&pData->StatIF_encap, a);
1698}
1699
1700/**
1701 * Still we're using dhcp server leasing to map ether to IP
1702 * @todo see rt_lookup_in_cache
1703 */
1704static uint32_t find_guest_ip(PNATState pData, const uint8_t *eth_addr)
1705{
1706 uint32_t ip = INADDR_ANY;
1707 int rc;
1708
1709 if (eth_addr == NULL)
1710 return INADDR_ANY;
1711
1712 if ( memcmp(eth_addr, zerro_ethaddr, ETH_ALEN) == 0
1713 || memcmp(eth_addr, broadcast_ethaddr, ETH_ALEN) == 0)
1714 return INADDR_ANY;
1715
1716 rc = slirp_arp_lookup_ip_by_ether(pData, eth_addr, &ip);
1717 if (RT_SUCCESS(rc))
1718 return ip;
1719
1720 bootp_cache_lookup_ip_by_ether(pData, eth_addr, &ip);
1721 /* ignore return code, ip will be set to INADDR_ANY on error */
1722 return ip;
1723}
1724
1725/**
1726 * We need check if we've activated port forwarding
1727 * for specific machine ... that of course relates to
1728 * service mode
1729 * @todo finish this for service case
1730 */
1731static void activate_port_forwarding(PNATState pData, const uint8_t *h_source)
1732{
1733 struct port_forward_rule *rule;
1734
1735 /* check mac here */
1736 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1737 {
1738 struct socket *so;
1739 struct alias_link *alias_link;
1740 struct libalias *lib;
1741 int flags;
1742 struct sockaddr sa;
1743 struct sockaddr_in *psin;
1744 socklen_t socketlen;
1745 struct in_addr alias;
1746 int rc;
1747 uint32_t guest_addr; /* need to understand if we already give address to guest */
1748
1749 if (rule->activated)
1750 continue;
1751
1752#ifdef VBOX_WITH_NAT_SERVICE
1753 if (memcmp(rule->mac_address, h_source, ETH_ALEN) != 0)
1754 continue; /*not right mac, @todo: it'd be better do the list port forwarding per mac */
1755 guest_addr = find_guest_ip(pData, h_source);
1756#else
1757#if 0
1758 if (memcmp(client_ethaddr, h_source, ETH_ALEN) != 0)
1759 continue;
1760#endif
1761 guest_addr = find_guest_ip(pData, h_source);
1762#endif
1763 if (guest_addr == INADDR_ANY)
1764 {
1765 /* the address wasn't granted */
1766 return;
1767 }
1768
1769#if !defined(VBOX_WITH_NAT_SERVICE)
1770 if (rule->guest_addr.s_addr != guest_addr)
1771 continue;
1772#endif
1773
1774 LogRel(("NAT: set redirect %s host port %d => guest port %d @ %R[IP4]\n",
1775 (rule->proto == IPPROTO_UDP?"UDP":"TCP"),
1776 rule->host_port, rule->guest_port, &guest_addr));
1777
1778 if (rule->proto == IPPROTO_UDP)
1779 so = udp_listen(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1780 RT_H2N_U16(rule->guest_port), 0);
1781 else
1782 so = solisten(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1783 RT_H2N_U16(rule->guest_port), 0);
1784
1785 if (so == NULL)
1786 goto remove_port_forwarding;
1787
1788 psin = (struct sockaddr_in *)&sa;
1789 psin->sin_family = AF_INET;
1790 psin->sin_port = 0;
1791 psin->sin_addr.s_addr = INADDR_ANY;
1792 socketlen = sizeof(struct sockaddr);
1793
1794 rc = getsockname(so->s, &sa, &socketlen);
1795 if (rc < 0 || sa.sa_family != AF_INET)
1796 goto remove_port_forwarding;
1797
1798 psin = (struct sockaddr_in *)&sa;
1799
1800 lib = LibAliasInit(pData, NULL);
1801 flags = LibAliasSetMode(lib, 0, 0);
1802 flags |= PKT_ALIAS_LOG; /* set logging */
1803 flags |= PKT_ALIAS_REVERSE; /* set logging */
1804 flags = LibAliasSetMode(lib, flags, ~0);
1805
1806 alias.s_addr = RT_H2N_U32(RT_N2H_U32(guest_addr) | CTL_ALIAS);
1807 alias_link = LibAliasRedirectPort(lib, psin->sin_addr, RT_H2N_U16(rule->host_port),
1808 alias, RT_H2N_U16(rule->guest_port),
1809 pData->special_addr, -1, /* not very clear for now */
1810 rule->proto);
1811 if (!alias_link)
1812 goto remove_port_forwarding;
1813
1814 so->so_la = lib;
1815 rule->activated = 1;
1816 pData->cRedirectionsActive++;
1817 continue;
1818
1819 remove_port_forwarding:
1820 LogRel(("NAT: failed to redirect %s %d => %d\n",
1821 (rule->proto == IPPROTO_UDP?"UDP":"TCP"), rule->host_port, rule->guest_port));
1822 LIST_REMOVE(rule, list);
1823 pData->cRedirectionsStored--;
1824 RTMemFree(rule);
1825 }
1826}
1827
1828/**
1829 * Changes in 3.1 instead of opening new socket do the following:
1830 * gain more information:
1831 * 1. bind IP
1832 * 2. host port
1833 * 3. guest port
1834 * 4. proto
1835 * 5. guest MAC address
1836 * the guest's MAC address is rather important for service, but we easily
1837 * could get it from VM configuration in DrvNAT or Service, the idea is activating
1838 * corresponding port-forwarding
1839 */
1840int slirp_redir(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1841 struct in_addr guest_addr, int guest_port, const uint8_t *ethaddr)
1842{
1843 struct port_forward_rule *rule = NULL;
1844 Assert(memcmp(ethaddr, zerro_ethaddr, ETH_ALEN) == 0);
1845
1846 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1847 if (rule == NULL)
1848 return 1;
1849
1850 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1851 rule->host_port = host_port;
1852 rule->guest_port = guest_port;
1853#ifndef VBOX_WITH_NAT_SERVICE
1854 rule->guest_addr.s_addr = guest_addr.s_addr;
1855#endif
1856 rule->bind_ip.s_addr = host_addr.s_addr;
1857 memcpy(rule->mac_address, ethaddr, ETH_ALEN);
1858 /* @todo add mac address */
1859 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1860 pData->cRedirectionsStored++;
1861 return 0;
1862}
1863
1864int slirp_add_exec(PNATState pData, int do_pty, const char *args, int addr_low_byte,
1865 int guest_port)
1866{
1867 return add_exec(&exec_list, do_pty, (char *)args,
1868 addr_low_byte, RT_H2N_U16(guest_port));
1869}
1870
1871void slirp_set_ethaddr_and_activate_port_forwarding(PNATState pData, const uint8_t *ethaddr, uint32_t GuestIP)
1872{
1873#ifndef VBOX_WITH_NAT_SERVICE
1874 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1875#endif
1876 if (GuestIP != INADDR_ANY)
1877 {
1878 slirp_arp_cache_update_or_add(pData, GuestIP, ethaddr);
1879 activate_port_forwarding(pData, ethaddr);
1880 }
1881}
1882
1883#if defined(RT_OS_WINDOWS)
1884HANDLE *slirp_get_events(PNATState pData)
1885{
1886 return pData->phEvents;
1887}
1888void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1889{
1890 pData->phEvents[index] = hEvent;
1891}
1892#endif
1893
1894unsigned int slirp_get_timeout_ms(PNATState pData)
1895{
1896 if (link_up)
1897 {
1898 if (time_fasttimo)
1899 return 2;
1900 if (do_slowtimo)
1901 return 500; /* see PR_SLOWHZ */
1902 }
1903 return 0;
1904}
1905
1906#ifndef RT_OS_WINDOWS
1907int slirp_get_nsock(PNATState pData)
1908{
1909 return pData->nsock;
1910}
1911#endif
1912
1913/*
1914 * this function called from NAT thread
1915 */
1916void slirp_post_sent(PNATState pData, void *pvArg)
1917{
1918 struct socket *so = 0;
1919 struct tcpcb *tp = 0;
1920 struct mbuf *m = (struct mbuf *)pvArg;
1921 m_free(pData, m);
1922}
1923#ifdef VBOX_WITH_SLIRP_MT
1924void slirp_process_queue(PNATState pData)
1925{
1926 RTReqProcess(pData->pReqQueue, RT_INDEFINITE_WAIT);
1927}
1928void *slirp_get_queue(PNATState pData)
1929{
1930 return pData->pReqQueue;
1931}
1932#endif
1933
1934void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1935{
1936 Log2(("tftp_prefix:%s\n", tftpPrefix));
1937 tftp_prefix = tftpPrefix;
1938}
1939
1940void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1941{
1942 Log2(("bootFile:%s\n", bootFile));
1943 bootp_filename = bootFile;
1944}
1945
1946void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1947{
1948 Log2(("next_server:%s\n", next_server));
1949 if (next_server == NULL)
1950 pData->tftp_server.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_TFTP);
1951 else
1952 inet_aton(next_server, &pData->tftp_server);
1953}
1954
1955int slirp_set_binding_address(PNATState pData, char *addr)
1956{
1957 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1958 {
1959 pData->bindIP.s_addr = INADDR_ANY;
1960 return 1;
1961 }
1962 return 0;
1963}
1964
1965void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1966{
1967 if (!pData->use_host_resolver)
1968 {
1969 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1970 pData->use_dns_proxy = fDNSProxy;
1971 }
1972 else
1973 LogRel(("NAT: Host Resolver conflicts with DNS proxy, the last one was forcely ignored\n"));
1974}
1975
1976#define CHECK_ARG(name, val, lim_min, lim_max) \
1977 do { \
1978 if ((val) < (lim_min) || (val) > (lim_max)) \
1979 { \
1980 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1981 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1982 return; \
1983 } \
1984 else \
1985 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1986 } while (0)
1987
1988/* don't allow user set less 8kB and more than 1M values */
1989#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
1990void slirp_set_rcvbuf(PNATState pData, int kilobytes)
1991{
1992 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
1993 pData->socket_rcv = kilobytes;
1994}
1995void slirp_set_sndbuf(PNATState pData, int kilobytes)
1996{
1997 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
1998 pData->socket_snd = kilobytes * _1K;
1999}
2000void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
2001{
2002 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
2003 tcp_rcvspace = kilobytes * _1K;
2004}
2005void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
2006{
2007 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
2008 tcp_sndspace = kilobytes * _1K;
2009}
2010
2011/*
2012 * Looking for Ether by ip in ARP-cache
2013 * Note: it´s responsible of caller to allocate buffer for result
2014 * @returns iprt status code
2015 */
2016int slirp_arp_lookup_ether_by_ip(PNATState pData, uint32_t ip, uint8_t *ether)
2017{
2018 struct arp_cache_entry *ac;
2019
2020 if (ether == NULL)
2021 return VERR_INVALID_PARAMETER;
2022
2023 if (LIST_EMPTY(&pData->arp_cache))
2024 return VERR_NOT_FOUND;
2025
2026 LIST_FOREACH(ac, &pData->arp_cache, list)
2027 {
2028 if (ac->ip == ip)
2029 {
2030 memcpy(ether, ac->ether, ETH_ALEN);
2031 return VINF_SUCCESS;
2032 }
2033 }
2034 return VERR_NOT_FOUND;
2035}
2036
2037/*
2038 * Looking for IP by Ether in ARP-cache
2039 * Note: it´s responsible of caller to allocate buffer for result
2040 * @returns 0 - if found, 1 - otherwise
2041 */
2042int slirp_arp_lookup_ip_by_ether(PNATState pData, const uint8_t *ether, uint32_t *ip)
2043{
2044 struct arp_cache_entry *ac;
2045 *ip = INADDR_ANY;
2046
2047 if (LIST_EMPTY(&pData->arp_cache))
2048 return VERR_NOT_FOUND;
2049
2050 LIST_FOREACH(ac, &pData->arp_cache, list)
2051 {
2052 if (memcmp(ether, ac->ether, ETH_ALEN) == 0)
2053 {
2054 *ip = ac->ip;
2055 return VINF_SUCCESS;
2056 }
2057 }
2058 return VERR_NOT_FOUND;
2059}
2060
2061void slirp_arp_who_has(PNATState pData, uint32_t dst)
2062{
2063 struct mbuf *m;
2064 struct ethhdr *ehdr;
2065 struct arphdr *ahdr;
2066
2067#ifndef VBOX_WITH_SLIRP_BSD_MBUF
2068 m = m_get(pData);
2069#else
2070 m = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
2071#endif
2072 if (m == NULL)
2073 {
2074 LogRel(("NAT: Can't alloc mbuf for ARP request\n"));
2075 return;
2076 }
2077 ehdr = mtod(m, struct ethhdr *);
2078 memset(ehdr->h_source, 0xff, ETH_ALEN);
2079 ahdr = (struct arphdr *)&ehdr[1];
2080 ahdr->ar_hrd = RT_H2N_U16_C(1);
2081 ahdr->ar_pro = RT_H2N_U16_C(ETH_P_IP);
2082 ahdr->ar_hln = ETH_ALEN;
2083 ahdr->ar_pln = 4;
2084 ahdr->ar_op = RT_H2N_U16_C(ARPOP_REQUEST);
2085 memcpy(ahdr->ar_sha, special_ethaddr, ETH_ALEN);
2086 *(uint32_t *)ahdr->ar_sip = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
2087 memset(ahdr->ar_tha, 0xff, ETH_ALEN); /*broadcast*/
2088 *(uint32_t *)ahdr->ar_tip = dst;
2089#ifndef VBOX_WITH_SLIRP_BSD_MBUF
2090 m->m_data += if_maxlinkhdr;
2091 m->m_len = sizeof(struct arphdr);
2092#else
2093 /* warn!!! should falls in mbuf minimal size */
2094 m->m_len = sizeof(struct arphdr) + ETH_HLEN;
2095#endif
2096 if_encap(pData, ETH_P_ARP, m, ETH_ENCAP_URG);
2097}
2098
2099int slirp_arp_cache_update_or_add(PNATState pData, uint32_t dst, const uint8_t *mac)
2100{
2101 if (slirp_arp_cache_update(pData, dst, mac))
2102 slirp_arp_cache_add(pData, dst, mac);
2103
2104 return 0;
2105}
2106
2107/* updates the arp cache
2108 * @returns 0 - if has found and updated
2109 * 1 - if hasn't found.
2110 */
2111int slirp_arp_cache_update(PNATState pData, uint32_t dst, const uint8_t *mac)
2112{
2113 struct arp_cache_entry *ac;
2114 LIST_FOREACH(ac, &pData->arp_cache, list)
2115 {
2116 if (memcmp(ac->ether, mac, ETH_ALEN) == 0)
2117 {
2118 ac->ip = dst;
2119 return 0;
2120 }
2121 }
2122 return 1;
2123}
2124
2125void slirp_arp_cache_add(PNATState pData, uint32_t ip, const uint8_t *ether)
2126{
2127 struct arp_cache_entry *ac = NULL;
2128 ac = RTMemAllocZ(sizeof(struct arp_cache_entry));
2129 if (ac == NULL)
2130 {
2131 LogRel(("NAT: Can't allocate arp cache entry\n"));
2132 return;
2133 }
2134 ac->ip = ip;
2135 memcpy(ac->ether, ether, ETH_ALEN);
2136 LIST_INSERT_HEAD(&pData->arp_cache, ac, list);
2137}
2138
2139#ifdef VBOX_WITH_SLIRP_BSD_MBUF
2140void slirp_set_mtu(PNATState pData, int mtu)
2141{
2142 if (mtu < 20 || mtu >= 16000)
2143 {
2144 LogRel(("NAT: mtu(%d) is out of range (20;16000] mtu forcely assigned to 1500\n", mtu));
2145 mtu = 1500;
2146 }
2147 if_mtu =
2148 if_mru = mtu;
2149}
2150#endif
Note: See TracBrowser for help on using the repository browser.

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