VirtualBox

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

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

NAT: bugfix for registering xfds_poll at poll()

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