VirtualBox

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

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

NAT: "sending to home" on wide cast and cloning udp sockets. Both disabled.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 69.0 KB
Line 
1/* $Id: slirp.c 39287 2011-11-14 09:41:52Z 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
916 /*
917 * See if we need a tcp_fasttimo
918 */
919 if ( time_fasttimo == 0
920 && so->so_tcpcb != NULL
921 && so->so_tcpcb->t_flags & TF_DELACK)
922 {
923 time_fasttimo = curtime; /* Flag when we want a fasttimo */
924 }
925
926 /*
927 * NOFDREF can include still connecting to local-host,
928 * newly socreated() sockets etc. Don't want to select these.
929 */
930 if (so->so_state & SS_NOFDREF || so->s == -1)
931 CONTINUE(tcp);
932
933 /*
934 * Set for reading sockets which are accepting
935 */
936 if (so->so_state & SS_FACCEPTCONN)
937 {
938 STAM_COUNTER_INC(&pData->StatTCPHot);
939 TCP_ENGAGE_EVENT1(so, readfds);
940 CONTINUE(tcp);
941 }
942
943 /*
944 * Set for writing sockets which are connecting
945 */
946 if (so->so_state & SS_ISFCONNECTING)
947 {
948 Log2(("connecting %R[natsock] engaged\n",so));
949 STAM_COUNTER_INC(&pData->StatTCPHot);
950#ifdef RT_OS_WINDOWS
951 WIN_TCP_ENGAGE_EVENT2(so, writefds, connectfds);
952#else
953 TCP_ENGAGE_EVENT1(so, writefds);
954#endif
955 }
956
957 /*
958 * Set for writing if we are connected, can send more, and
959 * we have something to send
960 */
961 if (CONN_CANFSEND(so) && SBUF_LEN(&so->so_rcv))
962 {
963 STAM_COUNTER_INC(&pData->StatTCPHot);
964 TCP_ENGAGE_EVENT1(so, writefds);
965 }
966
967 /*
968 * Set for reading (and urgent data) if we are connected, can
969 * receive more, and we have room for it XXX /2 ?
970 */
971 /* @todo: vvl - check which predicat here will be more useful here in rerm of new sbufs. */
972 if ( CONN_CANFRCV(so)
973 && (SBUF_LEN(&so->so_snd) < (SBUF_SIZE(&so->so_snd)/2))
974#ifdef RT_OS_WINDOWS
975 && !(so->so_state & SS_ISFCONNECTING)
976#endif
977 )
978 {
979 STAM_COUNTER_INC(&pData->StatTCPHot);
980 TCP_ENGAGE_EVENT2(so, readfds, xfds);
981 }
982 LOOP_LABEL(tcp, so, so_next);
983 }
984
985 /*
986 * UDP sockets
987 */
988 STAM_COUNTER_RESET(&pData->StatUDP);
989 STAM_COUNTER_RESET(&pData->StatUDPHot);
990
991 QSOCKET_FOREACH(so, so_next, udp)
992 /* { */
993
994 STAM_COUNTER_INC(&pData->StatUDP);
995#if !defined(RT_OS_WINDOWS)
996 so->so_poll_index = -1;
997#endif
998
999 /*
1000 * See if it's timed out
1001 */
1002 if (so->so_expire)
1003 {
1004 if (so->so_expire <= curtime)
1005 {
1006 Log2(("NAT: %R[natsock] expired\n", so));
1007 if (so->so_timeout != NULL)
1008 {
1009 so->so_timeout(pData, so, so->so_timeout_arg);
1010 }
1011#ifdef VBOX_WITH_SLIRP_MT
1012 /* we need so_next for continue our cycle*/
1013 so_next = so->so_next;
1014#endif
1015 UDP_DETACH(pData, so, so_next);
1016 CONTINUE_NO_UNLOCK(udp);
1017 }
1018 }
1019
1020 /*
1021 * When UDP packets are received from over the link, they're
1022 * sendto()'d straight away, so no need for setting for writing
1023 * Limit the number of packets queued by this session to 4.
1024 * Note that even though we try and limit this to 4 packets,
1025 * the session could have more queued if the packets needed
1026 * to be fragmented.
1027 *
1028 * (XXX <= 4 ?)
1029 */
1030 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4)
1031 {
1032 STAM_COUNTER_INC(&pData->StatUDPHot);
1033 UDP_ENGAGE_EVENT(so, readfds);
1034 }
1035 LOOP_LABEL(udp, so, so_next);
1036 }
1037done:
1038
1039#if defined(RT_OS_WINDOWS)
1040 *pnfds = VBOX_EVENT_COUNT;
1041#else /* RT_OS_WINDOWS */
1042 AssertRelease(poll_index <= *pnfds);
1043 *pnfds = poll_index;
1044#endif /* !RT_OS_WINDOWS */
1045
1046 STAM_PROFILE_STOP(&pData->StatFill, a);
1047}
1048
1049
1050static bool slirpConnectOrWrite(PNATState pData, struct socket *so, bool fConnectOnly)
1051{
1052 int ret;
1053 LogFlowFunc(("ENTER: so:%R[natsock], fConnectOnly:%RTbool\n", so, fConnectOnly));
1054 /*
1055 * Check for non-blocking, still-connecting sockets
1056 */
1057 if (so->so_state & SS_ISFCONNECTING)
1058 {
1059 Log2(("connecting %R[natsock] catched\n", so));
1060 /* Connected */
1061 so->so_state &= ~SS_ISFCONNECTING;
1062
1063 /*
1064 * This should be probably guarded by PROBE_CONN too. Anyway,
1065 * we disable it on OS/2 because the below send call returns
1066 * EFAULT which causes the opened TCP socket to close right
1067 * after it has been opened and connected.
1068 */
1069#ifndef RT_OS_OS2
1070 ret = send(so->s, (const char *)&ret, 0, 0);
1071 if (ret < 0)
1072 {
1073 /* XXXXX Must fix, zero bytes is a NOP */
1074 if ( errno == EAGAIN
1075 || errno == EWOULDBLOCK
1076 || errno == EINPROGRESS
1077 || errno == ENOTCONN)
1078 {
1079 LogFlowFunc(("LEAVE: true"));
1080 return false;
1081 }
1082
1083 /* else failed */
1084 so->so_state = SS_NOFDREF;
1085 }
1086 /* else so->so_state &= ~SS_ISFCONNECTING; */
1087#endif
1088
1089 /*
1090 * Continue tcp_input
1091 */
1092 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1093 /* continue; */
1094 }
1095 else if (!fConnectOnly)
1096 SOWRITE(ret, pData, so);
1097 /*
1098 * XXX If we wrote something (a lot), there could be the need
1099 * for a window update. In the worst case, the remote will send
1100 * a window probe to get things going again.
1101 */
1102 LogFlowFunc(("LEAVE: true"));
1103 return true;
1104}
1105
1106#if defined(RT_OS_WINDOWS)
1107void slirp_select_poll(PNATState pData, int fTimeout, int fIcmp)
1108#else /* RT_OS_WINDOWS */
1109void slirp_select_poll(PNATState pData, struct pollfd *polls, int ndfs)
1110#endif /* !RT_OS_WINDOWS */
1111{
1112 struct socket *so, *so_next;
1113 int ret;
1114#if defined(RT_OS_WINDOWS)
1115 WSANETWORKEVENTS NetworkEvents;
1116 int rc;
1117 int error;
1118#endif
1119
1120 STAM_PROFILE_START(&pData->StatPoll, a);
1121
1122 /* Update time */
1123 updtime(pData);
1124
1125 /*
1126 * See if anything has timed out
1127 */
1128 if (link_up)
1129 {
1130 if (time_fasttimo && ((curtime - time_fasttimo) >= 2))
1131 {
1132 STAM_PROFILE_START(&pData->StatFastTimer, b);
1133 tcp_fasttimo(pData);
1134 time_fasttimo = 0;
1135 STAM_PROFILE_STOP(&pData->StatFastTimer, b);
1136 }
1137 if (do_slowtimo && ((curtime - last_slowtimo) >= 499))
1138 {
1139 STAM_PROFILE_START(&pData->StatSlowTimer, c);
1140 ip_slowtimo(pData);
1141 tcp_slowtimo(pData);
1142 last_slowtimo = curtime;
1143 STAM_PROFILE_STOP(&pData->StatSlowTimer, c);
1144 }
1145 }
1146#if defined(RT_OS_WINDOWS)
1147 if (fTimeout)
1148 return; /* only timer update */
1149#endif
1150
1151 /*
1152 * Check sockets
1153 */
1154 if (!link_up)
1155 goto done;
1156#if defined(RT_OS_WINDOWS)
1157 /*XXX: before renaming please make see define
1158 * fIcmp in slirp_state.h
1159 */
1160 if (fIcmp)
1161 sorecvfrom(pData, &pData->icmp_socket);
1162#else
1163 if ( (pData->icmp_socket.s != -1)
1164 && CHECK_FD_SET(&pData->icmp_socket, ignored, readfds))
1165 sorecvfrom(pData, &pData->icmp_socket);
1166#endif
1167 /*
1168 * Check TCP sockets
1169 */
1170 QSOCKET_FOREACH(so, so_next, tcp)
1171 /* { */
1172
1173#ifdef VBOX_WITH_SLIRP_MT
1174 if ( so->so_state & SS_NOFDREF
1175 && so->so_deleted == 1)
1176 {
1177 struct socket *son, *sop = NULL;
1178 QSOCKET_LOCK(tcb);
1179 if (so->so_next != NULL)
1180 {
1181 if (so->so_next != &tcb)
1182 SOCKET_LOCK(so->so_next);
1183 son = so->so_next;
1184 }
1185 if ( so->so_prev != &tcb
1186 && so->so_prev != NULL)
1187 {
1188 SOCKET_LOCK(so->so_prev);
1189 sop = so->so_prev;
1190 }
1191 QSOCKET_UNLOCK(tcb);
1192 remque(pData, so);
1193 NSOCK_DEC();
1194 SOCKET_UNLOCK(so);
1195 SOCKET_LOCK_DESTROY(so);
1196 RTMemFree(so);
1197 so_next = son;
1198 if (sop != NULL)
1199 SOCKET_UNLOCK(sop);
1200 CONTINUE_NO_UNLOCK(tcp);
1201 }
1202#endif
1203 /*
1204 * FD_ISSET is meaningless on these sockets
1205 * (and they can crash the program)
1206 */
1207 if (so->so_state & SS_NOFDREF || so->s == -1)
1208 CONTINUE(tcp);
1209
1210 POLL_TCP_EVENTS(rc, error, so, &NetworkEvents);
1211
1212 LOG_NAT_SOCK(so, TCP, &NetworkEvents, readfds, writefds, xfds);
1213
1214
1215 /*
1216 * Check for URG data
1217 * This will soread as well, so no need to
1218 * test for readfds below if this succeeds
1219 */
1220
1221 /* out-of-band data */
1222 if ( CHECK_FD_SET(so, NetworkEvents, xfds)
1223#ifdef RT_OS_DARWIN
1224 /* Darwin and probably BSD hosts generates POLLPRI|POLLHUP event on receiving TCP.flags.{ACK|URG|FIN} this
1225 * combination on other Unixs hosts doesn't enter to this branch
1226 */
1227 && !CHECK_FD_SET(so, NetworkEvents, closefds)
1228#endif
1229#ifdef RT_OS_WINDOWS
1230 /**
1231 * In some cases FD_CLOSE comes with FD_OOB, that confuse tcp processing.
1232 */
1233 && !WIN_CHECK_FD_SET(so, NetworkEvents, closefds)
1234#endif
1235 )
1236 {
1237 sorecvoob(pData, so);
1238 }
1239
1240 /*
1241 * Check sockets for reading
1242 */
1243 else if ( CHECK_FD_SET(so, NetworkEvents, readfds)
1244 || WIN_CHECK_FD_SET(so, NetworkEvents, acceptds))
1245 {
1246
1247#ifdef RT_OS_WINDOWS
1248 if (WIN_CHECK_FD_SET(so, NetworkEvents, connectfds))
1249 {
1250 /* Finish connection first */
1251 /* should we ignore return value? */
1252 bool fRet = slirpConnectOrWrite(pData, so, true);
1253 LogFunc(("fRet:%RTbool\n", fRet));
1254 }
1255#endif
1256 /*
1257 * Check for incoming connections
1258 */
1259 if (so->so_state & SS_FACCEPTCONN)
1260 {
1261 TCP_CONNECT(pData, so);
1262 if (!CHECK_FD_SET(so, NetworkEvents, closefds))
1263 CONTINUE(tcp);
1264 }
1265
1266 ret = soread(pData, so);
1267 /* Output it if we read something */
1268 if (RT_LIKELY(ret > 0))
1269 TCP_OUTPUT(pData, sototcpcb(so));
1270 }
1271
1272 /*
1273 * Check for FD_CLOSE events.
1274 * in some cases once FD_CLOSE engaged on socket it could be flashed latter (for some reasons)
1275 */
1276 if ( CHECK_FD_SET(so, NetworkEvents, closefds)
1277 || (so->so_close == 1))
1278 {
1279 /*
1280 * drain the socket
1281 */
1282 for (;;)
1283 {
1284 ret = soread(pData, so);
1285 if (ret > 0)
1286 TCP_OUTPUT(pData, sototcpcb(so));
1287 else
1288 {
1289 Log2(("%R[natsock] errno %d (%s)\n", so, errno, strerror(errno)));
1290 break;
1291 }
1292 }
1293 /* mark the socket for termination _after_ it was drained */
1294 so->so_close = 1;
1295 /* No idea about Windows but on Posix, POLLHUP means that we can't send more.
1296 * Actually in the specific error scenario, POLLERR is set as well. */
1297#ifndef RT_OS_WINDOWS
1298 if (CHECK_FD_SET(so, NetworkEvents, rderr))
1299 sofcantsendmore(so);
1300#endif
1301 CONTINUE(tcp);
1302 }
1303
1304 /*
1305 * Check sockets for writing
1306 */
1307 if ( CHECK_FD_SET(so, NetworkEvents, writefds)
1308#ifdef RT_OS_WINDOWS
1309 || WIN_CHECK_FD_SET(so, NetworkEvents, connectfds)
1310#endif
1311 )
1312 {
1313 if(!slirpConnectOrWrite(pData, so, false))
1314 CONTINUE(tcp);
1315 }
1316
1317 /*
1318 * Probe a still-connecting, non-blocking socket
1319 * to check if it's still alive
1320 */
1321#ifdef PROBE_CONN
1322 if (so->so_state & SS_ISFCONNECTING)
1323 {
1324 ret = recv(so->s, (char *)&ret, 0, 0);
1325
1326 if (ret < 0)
1327 {
1328 /* XXX */
1329 if ( errno == EAGAIN
1330 || errno == EWOULDBLOCK
1331 || errno == EINPROGRESS
1332 || errno == ENOTCONN)
1333 {
1334 CONTINUE(tcp); /* Still connecting, continue */
1335 }
1336
1337 /* else failed */
1338 so->so_state = SS_NOFDREF;
1339
1340 /* tcp_input will take care of it */
1341 }
1342 else
1343 {
1344 ret = send(so->s, &ret, 0, 0);
1345 if (ret < 0)
1346 {
1347 /* XXX */
1348 if ( errno == EAGAIN
1349 || errno == EWOULDBLOCK
1350 || errno == EINPROGRESS
1351 || errno == ENOTCONN)
1352 {
1353 CONTINUE(tcp);
1354 }
1355 /* else failed */
1356 so->so_state = SS_NOFDREF;
1357 }
1358 else
1359 so->so_state &= ~SS_ISFCONNECTING;
1360
1361 }
1362 TCP_INPUT((struct mbuf *)NULL, sizeof(struct ip),so);
1363 } /* SS_ISFCONNECTING */
1364#endif
1365 LOOP_LABEL(tcp, so, so_next);
1366 }
1367
1368 /*
1369 * Now UDP sockets.
1370 * Incoming packets are sent straight away, they're not buffered.
1371 * Incoming UDP data isn't buffered either.
1372 */
1373 QSOCKET_FOREACH(so, so_next, udp)
1374 /* { */
1375#ifdef VBOX_WITH_SLIRP_MT
1376 if ( so->so_state & SS_NOFDREF
1377 && so->so_deleted == 1)
1378 {
1379 struct socket *son, *sop = NULL;
1380 QSOCKET_LOCK(udb);
1381 if (so->so_next != NULL)
1382 {
1383 if (so->so_next != &udb)
1384 SOCKET_LOCK(so->so_next);
1385 son = so->so_next;
1386 }
1387 if ( so->so_prev != &udb
1388 && so->so_prev != NULL)
1389 {
1390 SOCKET_LOCK(so->so_prev);
1391 sop = so->so_prev;
1392 }
1393 QSOCKET_UNLOCK(udb);
1394 remque(pData, so);
1395 NSOCK_DEC();
1396 SOCKET_UNLOCK(so);
1397 SOCKET_LOCK_DESTROY(so);
1398 RTMemFree(so);
1399 so_next = son;
1400 if (sop != NULL)
1401 SOCKET_UNLOCK(sop);
1402 CONTINUE_NO_UNLOCK(udp);
1403 }
1404#endif
1405 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
1406
1407 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
1408
1409 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
1410 {
1411 SORECVFROM(pData, so);
1412 }
1413 LOOP_LABEL(udp, so, so_next);
1414 }
1415
1416done:
1417
1418 STAM_PROFILE_STOP(&pData->StatPoll, a);
1419}
1420
1421
1422struct arphdr
1423{
1424 unsigned short ar_hrd; /* format of hardware address */
1425 unsigned short ar_pro; /* format of protocol address */
1426 unsigned char ar_hln; /* length of hardware address */
1427 unsigned char ar_pln; /* length of protocol address */
1428 unsigned short ar_op; /* ARP opcode (command) */
1429
1430 /*
1431 * Ethernet looks like this : This bit is variable sized however...
1432 */
1433 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1434 unsigned char ar_sip[4]; /* sender IP address */
1435 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1436 unsigned char ar_tip[4]; /* target IP address */
1437};
1438AssertCompileSize(struct arphdr, 28);
1439
1440/**
1441 * @note This function will free m!
1442 */
1443static void arp_input(PNATState pData, struct mbuf *m)
1444{
1445 struct ethhdr *eh;
1446 struct ethhdr *reh;
1447 struct arphdr *ah;
1448 struct arphdr *rah;
1449 int ar_op;
1450 uint32_t htip;
1451 uint32_t tip;
1452 struct mbuf *mr;
1453 eh = mtod(m, struct ethhdr *);
1454 ah = (struct arphdr *)&eh[1];
1455 htip = RT_N2H_U32(*(uint32_t*)ah->ar_tip);
1456 tip = *(uint32_t*)ah->ar_tip;
1457
1458 ar_op = RT_N2H_U16(ah->ar_op);
1459
1460 switch (ar_op)
1461 {
1462 case ARPOP_REQUEST:
1463 mr = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
1464 if (!mr)
1465 break;
1466 reh = mtod(mr, struct ethhdr *);
1467 mr->m_data += ETH_HLEN;
1468 rah = mtod(mr, struct arphdr *);
1469 mr->m_len = sizeof(struct arphdr);
1470 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1471 if ( 0
1472#ifdef VBOX_WITH_NAT_SERVICE
1473 || (tip == pData->special_addr.s_addr)
1474#endif
1475 || ( ((htip & pData->netmask) == RT_N2H_U32(pData->special_addr.s_addr))
1476 && ( CTL_CHECK(htip, CTL_DNS)
1477 || CTL_CHECK(htip, CTL_ALIAS)
1478 || CTL_CHECK(htip, CTL_TFTP))
1479 )
1480 )
1481 {
1482 rah->ar_hrd = RT_H2N_U16_C(1);
1483 rah->ar_pro = RT_H2N_U16_C(ETH_P_IP);
1484 rah->ar_hln = ETH_ALEN;
1485 rah->ar_pln = 4;
1486 rah->ar_op = RT_H2N_U16_C(ARPOP_REPLY);
1487 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN);
1488
1489 switch (htip & ~pData->netmask)
1490 {
1491 case CTL_DNS:
1492 case CTL_ALIAS:
1493 case CTL_TFTP:
1494 if (!slirpMbufTagService(pData, mr, (uint8_t)(htip & ~pData->netmask)))
1495 {
1496 static bool fTagErrorReported;
1497 if (!fTagErrorReported)
1498 {
1499 LogRel(("NAT: couldn't add the tag(PACKET_SERVICE:%d) to mbuf:%p\n",
1500 (uint8_t)(htip & ~pData->netmask), m));
1501 fTagErrorReported = true;
1502 }
1503 }
1504 rah->ar_sha[5] = (uint8_t)(htip & ~pData->netmask);
1505 break;
1506 default:;
1507 }
1508
1509 memcpy(rah->ar_sip, ah->ar_tip, 4);
1510 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
1511 memcpy(rah->ar_tip, ah->ar_sip, 4);
1512 if_encap(pData, ETH_P_ARP, mr, ETH_ENCAP_URG);
1513 }
1514 else
1515 m_freem(pData, mr);
1516
1517 /* Gratuitous ARP */
1518 if ( *(uint32_t *)ah->ar_sip == *(uint32_t *)ah->ar_tip
1519 && memcmp(ah->ar_tha, broadcast_ethaddr, ETH_ALEN) == 0
1520 && memcmp(eh->h_dest, broadcast_ethaddr, ETH_ALEN) == 0)
1521 {
1522 /* We've received an announce about address assignment,
1523 * let's do an ARP cache update
1524 */
1525 static bool fGratuitousArpReported;
1526 if (!fGratuitousArpReported)
1527 {
1528 LogRel(("NAT: Gratuitous ARP [IP:%RTnaipv4, ether:%RTmac]\n",
1529 ah->ar_sip, ah->ar_sha));
1530 fGratuitousArpReported = true;
1531 }
1532 slirp_arp_cache_update_or_add(pData, *(uint32_t *)ah->ar_sip, &ah->ar_sha[0]);
1533 }
1534 break;
1535
1536 case ARPOP_REPLY:
1537 slirp_arp_cache_update_or_add(pData, *(uint32_t *)ah->ar_sip, &ah->ar_sha[0]);
1538 break;
1539
1540 default:
1541 break;
1542 }
1543
1544 m_freem(pData, m);
1545}
1546
1547/**
1548 * Feed a packet into the slirp engine.
1549 *
1550 * @param m Data buffer, m_len is not valid.
1551 * @param cbBuf The length of the data in m.
1552 */
1553void slirp_input(PNATState pData, struct mbuf *m, size_t cbBuf)
1554{
1555 int proto;
1556 static bool fWarnedIpv6;
1557 struct ethhdr *eh;
1558 uint8_t au8Ether[ETH_ALEN];
1559
1560 m->m_len = cbBuf;
1561 if (cbBuf < ETH_HLEN)
1562 {
1563 Log(("NAT: packet having size %d has been ignored\n", m->m_len));
1564 m_freem(pData, m);
1565 return;
1566 }
1567 eh = mtod(m, struct ethhdr *);
1568 proto = RT_N2H_U16(eh->h_proto);
1569
1570 memcpy(au8Ether, eh->h_source, ETH_ALEN);
1571
1572 switch(proto)
1573 {
1574 case ETH_P_ARP:
1575 arp_input(pData, m);
1576 break;
1577
1578 case ETH_P_IP:
1579 /* Update time. Important if the network is very quiet, as otherwise
1580 * the first outgoing connection gets an incorrect timestamp. */
1581 updtime(pData);
1582 m_adj(m, ETH_HLEN);
1583 M_ASSERTPKTHDR(m);
1584 m->m_pkthdr.header = mtod(m, void *);
1585 ip_input(pData, m);
1586 break;
1587
1588 case ETH_P_IPV6:
1589 m_freem(pData, m);
1590 if (!fWarnedIpv6)
1591 {
1592 LogRel(("NAT: IPv6 not supported\n"));
1593 fWarnedIpv6 = true;
1594 }
1595 break;
1596
1597 default:
1598 Log(("NAT: Unsupported protocol %x\n", proto));
1599 m_freem(pData, m);
1600 break;
1601 }
1602
1603 if (pData->cRedirectionsActive != pData->cRedirectionsStored)
1604 activate_port_forwarding(pData, au8Ether);
1605}
1606
1607/**
1608 * Output the IP packet to the ethernet device.
1609 *
1610 * @note This function will free m!
1611 */
1612void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m, int flags)
1613{
1614 struct ethhdr *eh;
1615 uint8_t *mbuf = NULL;
1616 size_t mlen = 0;
1617 STAM_PROFILE_START(&pData->StatIF_encap, a);
1618 LogFlowFunc(("ENTER: pData:%p, eth_proto:%RX16, m:%p, flags:%d\n",
1619 pData, eth_proto, m, flags));
1620
1621 M_ASSERTPKTHDR(m);
1622 m->m_data -= ETH_HLEN;
1623 m->m_len += ETH_HLEN;
1624 eh = mtod(m, struct ethhdr *);
1625 mlen = m->m_len;
1626
1627 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) != 0)
1628 {
1629 struct m_tag *t = m_tag_first(m);
1630 uint8_t u8ServiceId = CTL_ALIAS;
1631 memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
1632 memcpy(eh->h_source, special_ethaddr, ETH_ALEN);
1633 Assert(memcmp(eh->h_dest, special_ethaddr, ETH_ALEN) != 0);
1634 if (memcmp(eh->h_dest, zerro_ethaddr, ETH_ALEN) == 0)
1635 {
1636 /* don't do anything */
1637 m_freem(pData, m);
1638 goto done;
1639 }
1640 if ( t
1641 && (t = m_tag_find(m, PACKET_SERVICE, NULL)))
1642 {
1643 Assert(t);
1644 u8ServiceId = *(uint8_t *)&t[1];
1645 }
1646 eh->h_source[5] = u8ServiceId;
1647 }
1648 /*
1649 * we're processing the chain, that isn't not expected.
1650 */
1651 Assert((!m->m_next));
1652 if (m->m_next)
1653 {
1654 Log(("NAT: if_encap's recived the chain, dropping...\n"));
1655 m_freem(pData, m);
1656 goto done;
1657 }
1658 mbuf = mtod(m, uint8_t *);
1659 eh->h_proto = RT_H2N_U16(eth_proto);
1660 LogFunc(("eh(dst:%RTmac, src:%RTmac)\n", eh->h_dest, eh->h_source));
1661 if (flags & ETH_ENCAP_URG)
1662 slirp_urg_output(pData->pvUser, m, mbuf, mlen);
1663 else
1664 slirp_output(pData->pvUser, m, mbuf, mlen);
1665done:
1666 STAM_PROFILE_STOP(&pData->StatIF_encap, a);
1667 LogFlowFuncLeave();
1668}
1669
1670/**
1671 * Still we're using dhcp server leasing to map ether to IP
1672 * @todo see rt_lookup_in_cache
1673 */
1674static uint32_t find_guest_ip(PNATState pData, const uint8_t *eth_addr)
1675{
1676 uint32_t ip = INADDR_ANY;
1677 int rc;
1678
1679 if (eth_addr == NULL)
1680 return INADDR_ANY;
1681
1682 if ( memcmp(eth_addr, zerro_ethaddr, ETH_ALEN) == 0
1683 || memcmp(eth_addr, broadcast_ethaddr, ETH_ALEN) == 0)
1684 return INADDR_ANY;
1685
1686 rc = slirp_arp_lookup_ip_by_ether(pData, eth_addr, &ip);
1687 if (RT_SUCCESS(rc))
1688 return ip;
1689
1690 bootp_cache_lookup_ip_by_ether(pData, eth_addr, &ip);
1691 /* ignore return code, ip will be set to INADDR_ANY on error */
1692 return ip;
1693}
1694
1695/**
1696 * We need check if we've activated port forwarding
1697 * for specific machine ... that of course relates to
1698 * service mode
1699 * @todo finish this for service case
1700 */
1701static void activate_port_forwarding(PNATState pData, const uint8_t *h_source)
1702{
1703 struct port_forward_rule *rule, *tmp;
1704
1705 /* check mac here */
1706 LIST_FOREACH_SAFE(rule, &pData->port_forward_rule_head, list, tmp)
1707 {
1708 struct socket *so;
1709 struct alias_link *alias_link;
1710 struct libalias *lib;
1711 int flags;
1712 struct sockaddr sa;
1713 struct sockaddr_in *psin;
1714 socklen_t socketlen;
1715 struct in_addr alias;
1716 int rc;
1717 uint32_t guest_addr; /* need to understand if we already give address to guest */
1718
1719 if (rule->activated)
1720 continue;
1721
1722#ifdef VBOX_WITH_NAT_SERVICE
1723 if (memcmp(rule->mac_address, h_source, ETH_ALEN) != 0)
1724 continue; /*not right mac, @todo: it'd be better do the list port forwarding per mac */
1725 guest_addr = find_guest_ip(pData, h_source);
1726#else
1727#if 0
1728 if (memcmp(client_ethaddr, h_source, ETH_ALEN) != 0)
1729 continue;
1730#endif
1731 guest_addr = find_guest_ip(pData, h_source);
1732#endif
1733 if (guest_addr == INADDR_ANY)
1734 {
1735 /* the address wasn't granted */
1736 return;
1737 }
1738
1739#if !defined(VBOX_WITH_NAT_SERVICE)
1740 if ( rule->guest_addr.s_addr != guest_addr
1741 && rule->guest_addr.s_addr != INADDR_ANY)
1742 continue;
1743 if (rule->guest_addr.s_addr == INADDR_ANY)
1744 rule->guest_addr.s_addr = guest_addr;
1745#endif
1746
1747 LogRel(("NAT: set redirect %s host port %d => guest port %d @ %RTnaipv4\n",
1748 rule->proto == IPPROTO_UDP ? "UDP" : "TCP", rule->host_port, rule->guest_port, guest_addr));
1749
1750 if (rule->proto == IPPROTO_UDP)
1751 so = udp_listen(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1752 RT_H2N_U16(rule->guest_port), 0);
1753 else
1754 so = solisten(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1755 RT_H2N_U16(rule->guest_port), 0);
1756
1757 if (so == NULL)
1758 goto remove_port_forwarding;
1759
1760 psin = (struct sockaddr_in *)&sa;
1761 psin->sin_family = AF_INET;
1762 psin->sin_port = 0;
1763 psin->sin_addr.s_addr = INADDR_ANY;
1764 socketlen = sizeof(struct sockaddr);
1765
1766 rc = getsockname(so->s, &sa, &socketlen);
1767 if (rc < 0 || sa.sa_family != AF_INET)
1768 goto remove_port_forwarding;
1769
1770 psin = (struct sockaddr_in *)&sa;
1771
1772 lib = LibAliasInit(pData, NULL);
1773 flags = LibAliasSetMode(lib, 0, 0);
1774 flags |= pData->i32AliasMode;
1775 flags |= PKT_ALIAS_REVERSE; /* set reverse */
1776 flags = LibAliasSetMode(lib, flags, ~0);
1777
1778 alias.s_addr = RT_H2N_U32(RT_N2H_U32(guest_addr) | CTL_ALIAS);
1779 alias_link = LibAliasRedirectPort(lib, psin->sin_addr, RT_H2N_U16(rule->host_port),
1780 alias, RT_H2N_U16(rule->guest_port),
1781 pData->special_addr, -1, /* not very clear for now */
1782 rule->proto);
1783 if (!alias_link)
1784 goto remove_port_forwarding;
1785
1786 so->so_la = lib;
1787 rule->activated = 1;
1788 rule->so = so;
1789 pData->cRedirectionsActive++;
1790 continue;
1791
1792 remove_port_forwarding:
1793 LogRel(("NAT: failed to redirect %s %d => %d\n",
1794 (rule->proto == IPPROTO_UDP?"UDP":"TCP"), rule->host_port, rule->guest_port));
1795 LIST_REMOVE(rule, list);
1796 pData->cRedirectionsStored--;
1797 RTMemFree(rule);
1798 }
1799}
1800
1801/**
1802 * Changes in 3.1 instead of opening new socket do the following:
1803 * gain more information:
1804 * 1. bind IP
1805 * 2. host port
1806 * 3. guest port
1807 * 4. proto
1808 * 5. guest MAC address
1809 * the guest's MAC address is rather important for service, but we easily
1810 * could get it from VM configuration in DrvNAT or Service, the idea is activating
1811 * corresponding port-forwarding
1812 */
1813int slirp_add_redirect(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1814 struct in_addr guest_addr, int guest_port, const uint8_t *ethaddr)
1815{
1816 struct port_forward_rule *rule = NULL;
1817 Assert(ethaddr);
1818 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1819 {
1820 if ( rule->proto == (is_udp ? IPPROTO_UDP : IPPROTO_TCP)
1821 && rule->host_port == host_port
1822 && rule->bind_ip.s_addr == host_addr.s_addr
1823 && rule->guest_port == guest_port
1824 && rule->guest_addr.s_addr == guest_addr.s_addr
1825 )
1826 return 0; /* rule has been already registered */
1827 }
1828
1829 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1830 if (rule == NULL)
1831 return 1;
1832
1833 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1834 rule->host_port = host_port;
1835 rule->guest_port = guest_port;
1836 rule->guest_addr.s_addr = guest_addr.s_addr;
1837 rule->bind_ip.s_addr = host_addr.s_addr;
1838 memcpy(rule->mac_address, ethaddr, ETH_ALEN);
1839 /* @todo add mac address */
1840 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1841 pData->cRedirectionsStored++;
1842 /* activate port-forwarding if guest has already got assigned IP */
1843 if (memcmp(ethaddr, zerro_ethaddr, ETH_ALEN))
1844 activate_port_forwarding(pData, ethaddr);
1845 return 0;
1846}
1847
1848int slirp_remove_redirect(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1849 struct in_addr guest_addr, int guest_port)
1850{
1851 struct port_forward_rule *rule = NULL;
1852 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1853 {
1854 if ( rule->proto == (is_udp ? IPPROTO_UDP : IPPROTO_TCP)
1855 && rule->host_port == host_port
1856 && rule->guest_port == guest_port
1857 && rule->bind_ip.s_addr == host_addr.s_addr
1858 && rule->guest_addr.s_addr == guest_addr.s_addr
1859 && rule->activated)
1860 {
1861 LogRel(("NAT: remove redirect %s host port %d => guest port %d @ %RTnaipv4\n",
1862 rule->proto == IPPROTO_UDP ? "UDP" : "TCP", rule->host_port, rule->guest_port, guest_addr));
1863
1864 LibAliasUninit(rule->so->so_la);
1865 if (is_udp)
1866 udp_detach(pData, rule->so);
1867 else
1868 tcp_close(pData, sototcpcb(rule->so));
1869 LIST_REMOVE(rule, list);
1870 RTMemFree(rule);
1871 pData->cRedirectionsStored--;
1872 break;
1873 }
1874
1875 }
1876 return 0;
1877}
1878
1879void slirp_set_ethaddr_and_activate_port_forwarding(PNATState pData, const uint8_t *ethaddr, uint32_t GuestIP)
1880{
1881#ifndef VBOX_WITH_NAT_SERVICE
1882 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1883#endif
1884 if (GuestIP != INADDR_ANY)
1885 {
1886 slirp_arp_cache_update_or_add(pData, GuestIP, ethaddr);
1887 activate_port_forwarding(pData, ethaddr);
1888 }
1889}
1890
1891#if defined(RT_OS_WINDOWS)
1892HANDLE *slirp_get_events(PNATState pData)
1893{
1894 return pData->phEvents;
1895}
1896void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1897{
1898 pData->phEvents[index] = hEvent;
1899}
1900#endif
1901
1902unsigned int slirp_get_timeout_ms(PNATState pData)
1903{
1904 if (link_up)
1905 {
1906 if (time_fasttimo)
1907 return 2;
1908 if (do_slowtimo)
1909 return 500; /* see PR_SLOWHZ */
1910 }
1911 return 3600*1000; /* one hour */
1912}
1913
1914#ifndef RT_OS_WINDOWS
1915int slirp_get_nsock(PNATState pData)
1916{
1917 return pData->nsock;
1918}
1919#endif
1920
1921/*
1922 * this function called from NAT thread
1923 */
1924void slirp_post_sent(PNATState pData, void *pvArg)
1925{
1926 struct mbuf *m = (struct mbuf *)pvArg;
1927 m_freem(pData, m);
1928}
1929#ifdef VBOX_WITH_SLIRP_MT
1930void slirp_process_queue(PNATState pData)
1931{
1932 RTReqProcess(pData->pReqQueue, RT_INDEFINITE_WAIT);
1933}
1934void *slirp_get_queue(PNATState pData)
1935{
1936 return pData->pReqQueue;
1937}
1938#endif
1939
1940void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1941{
1942 Log2(("tftp_prefix: %s\n", tftpPrefix));
1943 tftp_prefix = tftpPrefix;
1944}
1945
1946void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1947{
1948 Log2(("bootFile: %s\n", bootFile));
1949 bootp_filename = bootFile;
1950}
1951
1952void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1953{
1954 Log2(("next_server: %s\n", next_server));
1955 if (next_server == NULL)
1956 pData->tftp_server.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_TFTP);
1957 else
1958 inet_aton(next_server, &pData->tftp_server);
1959}
1960
1961int slirp_set_binding_address(PNATState pData, char *addr)
1962{
1963 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1964 {
1965 pData->bindIP.s_addr = INADDR_ANY;
1966 return 1;
1967 }
1968 return 0;
1969}
1970
1971void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1972{
1973 if (!pData->fUseHostResolver)
1974 {
1975 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1976 pData->fUseDnsProxy = fDNSProxy;
1977 }
1978 else
1979 LogRel(("NAT: Host Resolver conflicts with DNS proxy, the last one was forcely ignored\n"));
1980}
1981
1982#define CHECK_ARG(name, val, lim_min, lim_max) \
1983 do { \
1984 if ((val) < (lim_min) || (val) > (lim_max)) \
1985 { \
1986 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1987 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1988 return; \
1989 } \
1990 else \
1991 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1992 } while (0)
1993
1994void slirp_set_somaxconn(PNATState pData, int iSoMaxConn)
1995{
1996 LogFlowFunc(("iSoMaxConn:d\n", iSoMaxConn));
1997 if (iSoMaxConn > SOMAXCONN)
1998 {
1999 LogRel(("New value of somaxconn(%d) bigger than SOMAXCONN(%d)\n", iSoMaxConn, SOMAXCONN));
2000 iSoMaxConn = SOMAXCONN;
2001 }
2002 pData->soMaxConn = iSoMaxConn > 0 ? iSoMaxConn : pData->soMaxConn;
2003 if (pData->soMaxConn > 1)
2004 LogRel(("New value of somaxconn: %d\n", pData->soMaxConn));
2005 LogFlowFuncLeave();
2006}
2007/* don't allow user set less 8kB and more than 1M values */
2008#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
2009void slirp_set_rcvbuf(PNATState pData, int kilobytes)
2010{
2011 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
2012 pData->socket_rcv = kilobytes;
2013}
2014void slirp_set_sndbuf(PNATState pData, int kilobytes)
2015{
2016 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
2017 pData->socket_snd = kilobytes * _1K;
2018}
2019void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
2020{
2021 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
2022 tcp_rcvspace = kilobytes * _1K;
2023}
2024void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
2025{
2026 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
2027 tcp_sndspace = kilobytes * _1K;
2028}
2029
2030/*
2031 * Looking for Ether by ip in ARP-cache
2032 * Note: it´s responsible of caller to allocate buffer for result
2033 * @returns iprt status code
2034 */
2035int slirp_arp_lookup_ether_by_ip(PNATState pData, uint32_t ip, uint8_t *ether)
2036{
2037 struct arp_cache_entry *ac;
2038
2039 if (ether == NULL)
2040 return VERR_INVALID_PARAMETER;
2041
2042 if (LIST_EMPTY(&pData->arp_cache))
2043 return VERR_NOT_FOUND;
2044
2045 LIST_FOREACH(ac, &pData->arp_cache, list)
2046 {
2047 if ( ac->ip == ip
2048 && memcmp(ac->ether, broadcast_ethaddr, ETH_ALEN) != 0)
2049 {
2050 memcpy(ether, ac->ether, ETH_ALEN);
2051 return VINF_SUCCESS;
2052 }
2053 }
2054 return VERR_NOT_FOUND;
2055}
2056
2057/*
2058 * Looking for IP by Ether in ARP-cache
2059 * Note: it´s responsible of caller to allocate buffer for result
2060 * @returns 0 - if found, 1 - otherwise
2061 */
2062int slirp_arp_lookup_ip_by_ether(PNATState pData, const uint8_t *ether, uint32_t *ip)
2063{
2064 struct arp_cache_entry *ac;
2065 *ip = INADDR_ANY;
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 (memcmp(ether, ac->ether, ETH_ALEN) == 0)
2073 {
2074 *ip = ac->ip;
2075 return VINF_SUCCESS;
2076 }
2077 }
2078 return VERR_NOT_FOUND;
2079}
2080
2081void slirp_arp_who_has(PNATState pData, uint32_t dst)
2082{
2083 struct mbuf *m;
2084 struct ethhdr *ehdr;
2085 struct arphdr *ahdr;
2086 LogFlowFunc(("ENTER: %RTnaipv4\n", dst));
2087
2088 m = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
2089 if (m == NULL)
2090 {
2091 Log(("NAT: Can't alloc mbuf for ARP request\n"));
2092 LogFlowFuncLeave();
2093 return;
2094 }
2095 ehdr = mtod(m, struct ethhdr *);
2096 memset(ehdr->h_source, 0xff, ETH_ALEN);
2097 ahdr = (struct arphdr *)&ehdr[1];
2098 ahdr->ar_hrd = RT_H2N_U16_C(1);
2099 ahdr->ar_pro = RT_H2N_U16_C(ETH_P_IP);
2100 ahdr->ar_hln = ETH_ALEN;
2101 ahdr->ar_pln = 4;
2102 ahdr->ar_op = RT_H2N_U16_C(ARPOP_REQUEST);
2103 memcpy(ahdr->ar_sha, special_ethaddr, ETH_ALEN);
2104 /* we assume that this request come from gw, but not from DNS or TFTP */
2105 ahdr->ar_sha[5] = CTL_ALIAS;
2106 *(uint32_t *)ahdr->ar_sip = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
2107 memset(ahdr->ar_tha, 0xff, ETH_ALEN); /*broadcast*/
2108 *(uint32_t *)ahdr->ar_tip = dst;
2109 /* warn!!! should falls in mbuf minimal size */
2110 m->m_len = sizeof(struct arphdr) + ETH_HLEN;
2111 m->m_data += ETH_HLEN;
2112 m->m_len -= ETH_HLEN;
2113 if_encap(pData, ETH_P_ARP, m, ETH_ENCAP_URG);
2114 LogFlowFuncLeave();
2115}
2116
2117/* updates the arp cache
2118 * @note: this is helper function, slirp_arp_cache_update_or_add should be used.
2119 * @returns 0 - if has found and updated
2120 * 1 - if hasn't found.
2121 */
2122static inline int slirp_arp_cache_update(PNATState pData, uint32_t dst, const uint8_t *mac)
2123{
2124 struct arp_cache_entry *ac;
2125 Assert(( memcmp(mac, broadcast_ethaddr, ETH_ALEN)
2126 && memcmp(mac, zerro_ethaddr, ETH_ALEN)));
2127 LIST_FOREACH(ac, &pData->arp_cache, list)
2128 {
2129 if (!memcmp(ac->ether, mac, ETH_ALEN))
2130 {
2131 ac->ip = dst;
2132 return 0;
2133 }
2134 }
2135 return 1;
2136}
2137/**
2138 * add entry to the arp cache
2139 * @note: this is helper function, slirp_arp_cache_update_or_add should be used.
2140 */
2141
2142static inline void slirp_arp_cache_add(PNATState pData, uint32_t ip, const uint8_t *ether)
2143{
2144 struct arp_cache_entry *ac = NULL;
2145 Assert(( memcmp(ether, broadcast_ethaddr, ETH_ALEN)
2146 && memcmp(ether, zerro_ethaddr, ETH_ALEN)));
2147 ac = RTMemAllocZ(sizeof(struct arp_cache_entry));
2148 if (ac == NULL)
2149 {
2150 Log(("NAT: Can't allocate arp cache entry\n"));
2151 return;
2152 }
2153 ac->ip = ip;
2154 memcpy(ac->ether, ether, ETH_ALEN);
2155 LIST_INSERT_HEAD(&pData->arp_cache, ac, list);
2156}
2157
2158/* updates or adds entry to the arp cache
2159 * @returns 0 - if has found and updated
2160 * 1 - if hasn't found.
2161 */
2162int slirp_arp_cache_update_or_add(PNATState pData, uint32_t dst, const uint8_t *mac)
2163{
2164 if ( !memcmp(mac, broadcast_ethaddr, ETH_ALEN)
2165 || !memcmp(mac, zerro_ethaddr, ETH_ALEN))
2166 {
2167 static bool fBroadcastEtherAddReported;
2168 if (!fBroadcastEtherAddReported)
2169 {
2170 LogRel(("NAT: Attempt to add pair [%RTmac:%RTnaipv4] in ARP cache was ignored\n",
2171 mac, dst));
2172 fBroadcastEtherAddReported = true;
2173 }
2174 return 1;
2175 }
2176 if (slirp_arp_cache_update(pData, dst, mac))
2177 slirp_arp_cache_add(pData, dst, mac);
2178
2179 return 0;
2180}
2181
2182
2183void slirp_set_mtu(PNATState pData, int mtu)
2184{
2185 if (mtu < 20 || mtu >= 16000)
2186 {
2187 LogRel(("NAT: mtu(%d) is out of range (20;16000] mtu forcely assigned to 1500\n", mtu));
2188 mtu = 1500;
2189 }
2190 /* MTU is maximum transition unit on */
2191 if_mtu =
2192 if_mru = mtu;
2193}
2194
2195/**
2196 * Info handler.
2197 */
2198void slirp_info(PNATState pData, PCDBGFINFOHLP pHlp, const char *pszArgs)
2199{
2200 struct socket *so, *so_next;
2201 struct arp_cache_entry *ac;
2202 struct port_forward_rule *rule;
2203 NOREF(pszArgs);
2204
2205 pHlp->pfnPrintf(pHlp, "NAT parameters: MTU=%d\n", if_mtu);
2206 pHlp->pfnPrintf(pHlp, "NAT TCP ports:\n");
2207 QSOCKET_FOREACH(so, so_next, tcp)
2208 /* { */
2209 pHlp->pfnPrintf(pHlp, " %R[natsock]\n", so);
2210 }
2211
2212 pHlp->pfnPrintf(pHlp, "NAT UDP ports:\n");
2213 QSOCKET_FOREACH(so, so_next, udp)
2214 /* { */
2215 pHlp->pfnPrintf(pHlp, " %R[natsock]\n", so);
2216 }
2217
2218 pHlp->pfnPrintf(pHlp, "NAT ARP cache:\n");
2219 LIST_FOREACH(ac, &pData->arp_cache, list)
2220 {
2221 pHlp->pfnPrintf(pHlp, " %RTnaipv4 %RTmac\n", ac->ip, &ac->ether);
2222 }
2223
2224 pHlp->pfnPrintf(pHlp, "NAT rules:\n");
2225 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
2226 {
2227 pHlp->pfnPrintf(pHlp, " %s %d => %RTnaipv4:%d %c\n",
2228 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
2229 rule->host_port, rule->guest_addr.s_addr, rule->guest_port,
2230 rule->activated ? ' ' : '*');
2231 }
2232}
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