VirtualBox

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

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

NAT: experiment with FD_CONNECT processing on Windows host (disabled by default).

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