VirtualBox

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

Last change on this file since 41527 was 41453, checked in by vboxsync, 13 years ago

NAT: clean up (part 1).

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