VirtualBox

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

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

NAT: these two calls of activate_port_forwarding are now obsolete since this is done in slirp_input()

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