VirtualBox

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

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

NAT: clonning socket without creating real socket(2).

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