VirtualBox

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

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

NAT: Hrmpf

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