VirtualBox

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

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

NAT: FD_CONNECT exception in FD_OOB handler under NAT_CONNECT_EXPERIMENT umbrella (disabled by default).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 67.9 KB
Line 
1/* $Id: slirp.c 38044 2011-07-19 04:52:49Z 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#ifdef NAT_CONNECT_EXPERIMENT
1167# ifdef RT_OS_WINDOWS
1168 /**
1169 * In some cases FD_CONNECT comes with FD_OOB, that confuse tcp processing.
1170 */
1171 && !WIN_CHECK_FD_SET(so, NetworkEvents, connectfds)
1172# endif
1173#endif
1174 )
1175 {
1176 sorecvoob(pData, so);
1177 }
1178
1179 /*
1180 * Check sockets for reading
1181 */
1182 else if ( CHECK_FD_SET(so, NetworkEvents, readfds)
1183 || WIN_CHECK_FD_SET(so, NetworkEvents, acceptds))
1184 {
1185#ifdef DEBUG_vvl
1186 Assert(((so->so_state & SS_ISFCONNECTING) == 0));
1187#endif
1188 /*
1189 * Check for incoming connections
1190 */
1191 if (so->so_state & SS_FACCEPTCONN)
1192 {
1193 TCP_CONNECT(pData, so);
1194 if (!CHECK_FD_SET(so, NetworkEvents, closefds))
1195 CONTINUE(tcp);
1196 }
1197
1198 ret = soread(pData, so);
1199 /* Output it if we read something */
1200 if (RT_LIKELY(ret > 0))
1201 TCP_OUTPUT(pData, sototcpcb(so));
1202 }
1203
1204 /*
1205 * Check for FD_CLOSE events.
1206 * in some cases once FD_CLOSE engaged on socket it could be flashed latter (for some reasons)
1207 */
1208 if ( CHECK_FD_SET(so, NetworkEvents, closefds)
1209 || (so->so_close == 1))
1210 {
1211 /*
1212 * drain the socket
1213 */
1214 for (;;)
1215 {
1216 ret = soread(pData, so);
1217 if (ret > 0)
1218 TCP_OUTPUT(pData, sototcpcb(so));
1219 else
1220 {
1221 Log2(("%R[natsock] errno %d (%s)\n", so, errno, strerror(errno)));
1222 break;
1223 }
1224 }
1225 /* mark the socket for termination _after_ it was drained */
1226 so->so_close = 1;
1227 /* No idea about Windows but on Posix, POLLHUP means that we can't send more.
1228 * Actually in the specific error scenario, POLLERR is set as well. */
1229#ifndef RT_OS_WINDOWS
1230 if (CHECK_FD_SET(so, NetworkEvents, rderr))
1231 sofcantsendmore(so);
1232#endif
1233 CONTINUE(tcp);
1234 }
1235
1236 /*
1237 * Check sockets for writing
1238 */
1239 if ( CHECK_FD_SET(so, NetworkEvents, writefds)
1240#if defined(NAT_CONNECT_EXPERIMENT)
1241 || WIN_CHECK_FD_SET(so, NetworkEvents, connectfds)
1242#endif
1243 )
1244 {
1245 /*
1246 * Check for non-blocking, still-connecting sockets
1247 */
1248 if (so->so_state & SS_ISFCONNECTING)
1249 {
1250 Log2(("connecting %R[natsock] catched\n", so));
1251 /* Connected */
1252 so->so_state &= ~SS_ISFCONNECTING;
1253
1254 /*
1255 * This should be probably guarded by PROBE_CONN too. Anyway,
1256 * we disable it on OS/2 because the below send call returns
1257 * EFAULT which causes the opened TCP socket to close right
1258 * after it has been opened and connected.
1259 */
1260#ifndef RT_OS_OS2
1261 ret = send(so->s, (const char *)&ret, 0, 0);
1262 if (ret < 0)
1263 {
1264 /* XXXXX Must fix, zero bytes is a NOP */
1265 if ( errno == EAGAIN
1266 || errno == EWOULDBLOCK
1267 || errno == EINPROGRESS
1268 || errno == ENOTCONN)
1269 CONTINUE(tcp);
1270
1271 /* else failed */
1272 so->so_state = SS_NOFDREF;
1273 }
1274 /* else so->so_state &= ~SS_ISFCONNECTING; */
1275#endif
1276
1277 /*
1278 * Continue tcp_input
1279 */
1280 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
1281 /* continue; */
1282 }
1283 else
1284 SOWRITE(ret, pData, so);
1285 /*
1286 * XXX If we wrote something (a lot), there could be the need
1287 * for a window update. In the worst case, the remote will send
1288 * a window probe to get things going again.
1289 */
1290 }
1291
1292 /*
1293 * Probe a still-connecting, non-blocking socket
1294 * to check if it's still alive
1295 */
1296#ifdef PROBE_CONN
1297 if (so->so_state & SS_ISFCONNECTING)
1298 {
1299 ret = recv(so->s, (char *)&ret, 0, 0);
1300
1301 if (ret < 0)
1302 {
1303 /* XXX */
1304 if ( errno == EAGAIN
1305 || errno == EWOULDBLOCK
1306 || errno == EINPROGRESS
1307 || errno == ENOTCONN)
1308 {
1309 CONTINUE(tcp); /* Still connecting, continue */
1310 }
1311
1312 /* else failed */
1313 so->so_state = SS_NOFDREF;
1314
1315 /* tcp_input will take care of it */
1316 }
1317 else
1318 {
1319 ret = send(so->s, &ret, 0, 0);
1320 if (ret < 0)
1321 {
1322 /* XXX */
1323 if ( errno == EAGAIN
1324 || errno == EWOULDBLOCK
1325 || errno == EINPROGRESS
1326 || errno == ENOTCONN)
1327 {
1328 CONTINUE(tcp);
1329 }
1330 /* else failed */
1331 so->so_state = SS_NOFDREF;
1332 }
1333 else
1334 so->so_state &= ~SS_ISFCONNECTING;
1335
1336 }
1337 TCP_INPUT((struct mbuf *)NULL, sizeof(struct ip),so);
1338 } /* SS_ISFCONNECTING */
1339#endif
1340 LOOP_LABEL(tcp, so, so_next);
1341 }
1342
1343 /*
1344 * Now UDP sockets.
1345 * Incoming packets are sent straight away, they're not buffered.
1346 * Incoming UDP data isn't buffered either.
1347 */
1348 QSOCKET_FOREACH(so, so_next, udp)
1349 /* { */
1350#ifdef VBOX_WITH_SLIRP_MT
1351 if ( so->so_state & SS_NOFDREF
1352 && so->so_deleted == 1)
1353 {
1354 struct socket *son, *sop = NULL;
1355 QSOCKET_LOCK(udb);
1356 if (so->so_next != NULL)
1357 {
1358 if (so->so_next != &udb)
1359 SOCKET_LOCK(so->so_next);
1360 son = so->so_next;
1361 }
1362 if ( so->so_prev != &udb
1363 && so->so_prev != NULL)
1364 {
1365 SOCKET_LOCK(so->so_prev);
1366 sop = so->so_prev;
1367 }
1368 QSOCKET_UNLOCK(udb);
1369 remque(pData, so);
1370 NSOCK_DEC();
1371 SOCKET_UNLOCK(so);
1372 SOCKET_LOCK_DESTROY(so);
1373 RTMemFree(so);
1374 so_next = son;
1375 if (sop != NULL)
1376 SOCKET_UNLOCK(sop);
1377 CONTINUE_NO_UNLOCK(udp);
1378 }
1379#endif
1380 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
1381
1382 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
1383
1384 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
1385 {
1386 SORECVFROM(pData, so);
1387 }
1388 LOOP_LABEL(udp, so, so_next);
1389 }
1390
1391done:
1392
1393 STAM_PROFILE_STOP(&pData->StatPoll, a);
1394}
1395
1396
1397struct arphdr
1398{
1399 unsigned short ar_hrd; /* format of hardware address */
1400 unsigned short ar_pro; /* format of protocol address */
1401 unsigned char ar_hln; /* length of hardware address */
1402 unsigned char ar_pln; /* length of protocol address */
1403 unsigned short ar_op; /* ARP opcode (command) */
1404
1405 /*
1406 * Ethernet looks like this : This bit is variable sized however...
1407 */
1408 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1409 unsigned char ar_sip[4]; /* sender IP address */
1410 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1411 unsigned char ar_tip[4]; /* target IP address */
1412};
1413AssertCompileSize(struct arphdr, 28);
1414
1415/**
1416 * @note This function will free m!
1417 */
1418static void arp_input(PNATState pData, struct mbuf *m)
1419{
1420 struct ethhdr *eh;
1421 struct ethhdr *reh;
1422 struct arphdr *ah;
1423 struct arphdr *rah;
1424 int ar_op;
1425 uint32_t htip;
1426 uint32_t tip;
1427 struct mbuf *mr;
1428 eh = mtod(m, struct ethhdr *);
1429 ah = (struct arphdr *)&eh[1];
1430 htip = RT_N2H_U32(*(uint32_t*)ah->ar_tip);
1431 tip = *(uint32_t*)ah->ar_tip;
1432
1433 ar_op = RT_N2H_U16(ah->ar_op);
1434
1435 switch (ar_op)
1436 {
1437 case ARPOP_REQUEST:
1438 mr = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
1439 if (!mr)
1440 break;
1441 reh = mtod(mr, struct ethhdr *);
1442 mr->m_data += ETH_HLEN;
1443 rah = mtod(mr, struct arphdr *);
1444 mr->m_len = sizeof(struct arphdr);
1445 memcpy(reh->h_source, eh->h_source, ETH_ALEN); /* XXX: if_encap will swap src and dst*/
1446 if ( 0
1447#ifdef VBOX_WITH_NAT_SERVICE
1448 || (tip == pData->special_addr.s_addr)
1449#endif
1450 || ( ((htip & pData->netmask) == RT_N2H_U32(pData->special_addr.s_addr))
1451 && ( CTL_CHECK(htip, CTL_DNS)
1452 || CTL_CHECK(htip, CTL_ALIAS)
1453 || CTL_CHECK(htip, CTL_TFTP))
1454 )
1455 )
1456 {
1457 rah->ar_hrd = RT_H2N_U16_C(1);
1458 rah->ar_pro = RT_H2N_U16_C(ETH_P_IP);
1459 rah->ar_hln = ETH_ALEN;
1460 rah->ar_pln = 4;
1461 rah->ar_op = RT_H2N_U16_C(ARPOP_REPLY);
1462 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN);
1463
1464 switch (htip & ~pData->netmask)
1465 {
1466 case CTL_DNS:
1467 case CTL_ALIAS:
1468 case CTL_TFTP:
1469 if (!slirpMbufTagService(pData, mr, (uint8_t)(htip & ~pData->netmask)))
1470 {
1471 static bool fTagErrorReported;
1472 if (!fTagErrorReported)
1473 {
1474 LogRel(("NAT: couldn't add the tag(PACKET_SERVICE:%d) to mbuf:%p\n",
1475 (uint8_t)(htip & ~pData->netmask), m));
1476 fTagErrorReported = true;
1477 }
1478 }
1479 rah->ar_sha[5] = (uint8_t)(htip & ~pData->netmask);
1480 break;
1481 default:;
1482 }
1483
1484 memcpy(rah->ar_sip, ah->ar_tip, 4);
1485 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
1486 memcpy(rah->ar_tip, ah->ar_sip, 4);
1487 if_encap(pData, ETH_P_ARP, mr, ETH_ENCAP_URG);
1488 }
1489 else
1490 m_freem(pData, mr);
1491
1492 /* Gratuitous ARP */
1493 if ( *(uint32_t *)ah->ar_sip == *(uint32_t *)ah->ar_tip
1494 && memcmp(ah->ar_tha, broadcast_ethaddr, ETH_ALEN) == 0
1495 && memcmp(eh->h_dest, broadcast_ethaddr, ETH_ALEN) == 0)
1496 {
1497 /* We've received an announce about address assignment,
1498 * let's do an ARP cache update
1499 */
1500 static bool fGratuitousArpReported;
1501 if (!fGratuitousArpReported)
1502 {
1503 LogRel(("NAT: Gratuitous ARP [IP:%RTnaipv4, ether:%RTmac]\n",
1504 ah->ar_sip, ah->ar_sha));
1505 fGratuitousArpReported = true;
1506 }
1507 slirp_arp_cache_update_or_add(pData, *(uint32_t *)ah->ar_sip, &ah->ar_sha[0]);
1508 }
1509 break;
1510
1511 case ARPOP_REPLY:
1512 slirp_arp_cache_update_or_add(pData, *(uint32_t *)ah->ar_sip, &ah->ar_sha[0]);
1513 break;
1514
1515 default:
1516 break;
1517 }
1518
1519 m_freem(pData, m);
1520}
1521
1522/**
1523 * Feed a packet into the slirp engine.
1524 *
1525 * @param m Data buffer, m_len is not valid.
1526 * @param cbBuf The length of the data in m.
1527 */
1528void slirp_input(PNATState pData, struct mbuf *m, size_t cbBuf)
1529{
1530 int proto;
1531 static bool fWarnedIpv6;
1532 struct ethhdr *eh;
1533 uint8_t au8Ether[ETH_ALEN];
1534
1535 m->m_len = cbBuf;
1536 if (cbBuf < ETH_HLEN)
1537 {
1538 Log(("NAT: packet having size %d has been ignored\n", m->m_len));
1539 m_freem(pData, m);
1540 return;
1541 }
1542 eh = mtod(m, struct ethhdr *);
1543 proto = RT_N2H_U16(eh->h_proto);
1544
1545 memcpy(au8Ether, eh->h_source, ETH_ALEN);
1546
1547 switch(proto)
1548 {
1549 case ETH_P_ARP:
1550 arp_input(pData, m);
1551 break;
1552
1553 case ETH_P_IP:
1554 /* Update time. Important if the network is very quiet, as otherwise
1555 * the first outgoing connection gets an incorrect timestamp. */
1556 updtime(pData);
1557 m_adj(m, ETH_HLEN);
1558 M_ASSERTPKTHDR(m);
1559 m->m_pkthdr.header = mtod(m, void *);
1560 ip_input(pData, m);
1561 break;
1562
1563 case ETH_P_IPV6:
1564 m_freem(pData, m);
1565 if (!fWarnedIpv6)
1566 {
1567 LogRel(("NAT: IPv6 not supported\n"));
1568 fWarnedIpv6 = true;
1569 }
1570 break;
1571
1572 default:
1573 Log(("NAT: Unsupported protocol %x\n", proto));
1574 m_freem(pData, m);
1575 break;
1576 }
1577
1578 if (pData->cRedirectionsActive != pData->cRedirectionsStored)
1579 activate_port_forwarding(pData, au8Ether);
1580}
1581
1582/**
1583 * Output the IP packet to the ethernet device.
1584 *
1585 * @note This function will free m!
1586 */
1587void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m, int flags)
1588{
1589 struct ethhdr *eh;
1590 uint8_t *buf = NULL;
1591 uint8_t *mbuf = NULL;
1592 size_t mlen = 0;
1593 STAM_PROFILE_START(&pData->StatIF_encap, a);
1594
1595 M_ASSERTPKTHDR(m);
1596 m->m_data -= ETH_HLEN;
1597 m->m_len += ETH_HLEN;
1598 eh = mtod(m, struct ethhdr *);
1599 mlen = m->m_len;
1600
1601 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) != 0)
1602 {
1603 struct m_tag *t = m_tag_first(m);
1604 uint8_t u8ServiceId = CTL_ALIAS;
1605 memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
1606 memcpy(eh->h_source, special_ethaddr, ETH_ALEN);
1607 Assert(memcmp(eh->h_dest, special_ethaddr, ETH_ALEN) != 0);
1608 if (memcmp(eh->h_dest, zerro_ethaddr, ETH_ALEN) == 0)
1609 {
1610 /* don't do anything */
1611 m_freem(pData, m);
1612 goto done;
1613 }
1614 if ( t
1615 && (t = m_tag_find(m, PACKET_SERVICE, NULL)))
1616 {
1617 Assert(t);
1618 u8ServiceId = *(uint8_t *)&t[1];
1619 }
1620 eh->h_source[5] = u8ServiceId;
1621 }
1622 /*
1623 * we're processing the chain, that isn't not expected.
1624 */
1625 Assert((!m->m_next));
1626 if (m->m_next)
1627 {
1628 Log(("NAT: if_encap's recived the chain, dropping...\n"));
1629 m_freem(pData, m);
1630 goto done;
1631 }
1632 mbuf = mtod(m, uint8_t *);
1633 eh->h_proto = RT_H2N_U16(eth_proto);
1634 if (flags & ETH_ENCAP_URG)
1635 slirp_urg_output(pData->pvUser, m, mbuf, mlen);
1636 else
1637 slirp_output(pData->pvUser, m, mbuf, mlen);
1638done:
1639 STAM_PROFILE_STOP(&pData->StatIF_encap, a);
1640}
1641
1642/**
1643 * Still we're using dhcp server leasing to map ether to IP
1644 * @todo see rt_lookup_in_cache
1645 */
1646static uint32_t find_guest_ip(PNATState pData, const uint8_t *eth_addr)
1647{
1648 uint32_t ip = INADDR_ANY;
1649 int rc;
1650
1651 if (eth_addr == NULL)
1652 return INADDR_ANY;
1653
1654 if ( memcmp(eth_addr, zerro_ethaddr, ETH_ALEN) == 0
1655 || memcmp(eth_addr, broadcast_ethaddr, ETH_ALEN) == 0)
1656 return INADDR_ANY;
1657
1658 rc = slirp_arp_lookup_ip_by_ether(pData, eth_addr, &ip);
1659 if (RT_SUCCESS(rc))
1660 return ip;
1661
1662 bootp_cache_lookup_ip_by_ether(pData, eth_addr, &ip);
1663 /* ignore return code, ip will be set to INADDR_ANY on error */
1664 return ip;
1665}
1666
1667/**
1668 * We need check if we've activated port forwarding
1669 * for specific machine ... that of course relates to
1670 * service mode
1671 * @todo finish this for service case
1672 */
1673static void activate_port_forwarding(PNATState pData, const uint8_t *h_source)
1674{
1675 struct port_forward_rule *rule, *tmp;
1676
1677 /* check mac here */
1678 LIST_FOREACH_SAFE(rule, &pData->port_forward_rule_head, list, tmp)
1679 {
1680 struct socket *so;
1681 struct alias_link *alias_link;
1682 struct libalias *lib;
1683 int flags;
1684 struct sockaddr sa;
1685 struct sockaddr_in *psin;
1686 socklen_t socketlen;
1687 struct in_addr alias;
1688 int rc;
1689 uint32_t guest_addr; /* need to understand if we already give address to guest */
1690
1691 if (rule->activated)
1692 continue;
1693
1694#ifdef VBOX_WITH_NAT_SERVICE
1695 if (memcmp(rule->mac_address, h_source, ETH_ALEN) != 0)
1696 continue; /*not right mac, @todo: it'd be better do the list port forwarding per mac */
1697 guest_addr = find_guest_ip(pData, h_source);
1698#else
1699#if 0
1700 if (memcmp(client_ethaddr, h_source, ETH_ALEN) != 0)
1701 continue;
1702#endif
1703 guest_addr = find_guest_ip(pData, h_source);
1704#endif
1705 if (guest_addr == INADDR_ANY)
1706 {
1707 /* the address wasn't granted */
1708 return;
1709 }
1710
1711#if !defined(VBOX_WITH_NAT_SERVICE)
1712 if ( rule->guest_addr.s_addr != guest_addr
1713 && rule->guest_addr.s_addr != INADDR_ANY)
1714 continue;
1715 if (rule->guest_addr.s_addr == INADDR_ANY)
1716 rule->guest_addr.s_addr = guest_addr;
1717#endif
1718
1719 LogRel(("NAT: set redirect %s host port %d => guest port %d @ %RTnaipv4\n",
1720 rule->proto == IPPROTO_UDP ? "UDP" : "TCP", rule->host_port, rule->guest_port, guest_addr));
1721
1722 if (rule->proto == IPPROTO_UDP)
1723 so = udp_listen(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1724 RT_H2N_U16(rule->guest_port), 0);
1725 else
1726 so = solisten(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port), guest_addr,
1727 RT_H2N_U16(rule->guest_port), 0);
1728
1729 if (so == NULL)
1730 goto remove_port_forwarding;
1731
1732 psin = (struct sockaddr_in *)&sa;
1733 psin->sin_family = AF_INET;
1734 psin->sin_port = 0;
1735 psin->sin_addr.s_addr = INADDR_ANY;
1736 socketlen = sizeof(struct sockaddr);
1737
1738 rc = getsockname(so->s, &sa, &socketlen);
1739 if (rc < 0 || sa.sa_family != AF_INET)
1740 goto remove_port_forwarding;
1741
1742 psin = (struct sockaddr_in *)&sa;
1743
1744 lib = LibAliasInit(pData, NULL);
1745 flags = LibAliasSetMode(lib, 0, 0);
1746 flags |= pData->i32AliasMode;
1747 flags |= PKT_ALIAS_REVERSE; /* set reverse */
1748 flags = LibAliasSetMode(lib, flags, ~0);
1749
1750 alias.s_addr = RT_H2N_U32(RT_N2H_U32(guest_addr) | CTL_ALIAS);
1751 alias_link = LibAliasRedirectPort(lib, psin->sin_addr, RT_H2N_U16(rule->host_port),
1752 alias, RT_H2N_U16(rule->guest_port),
1753 pData->special_addr, -1, /* not very clear for now */
1754 rule->proto);
1755 if (!alias_link)
1756 goto remove_port_forwarding;
1757
1758 so->so_la = lib;
1759 rule->activated = 1;
1760 rule->so = so;
1761 pData->cRedirectionsActive++;
1762 continue;
1763
1764 remove_port_forwarding:
1765 LogRel(("NAT: failed to redirect %s %d => %d\n",
1766 (rule->proto == IPPROTO_UDP?"UDP":"TCP"), rule->host_port, rule->guest_port));
1767 LIST_REMOVE(rule, list);
1768 pData->cRedirectionsStored--;
1769 RTMemFree(rule);
1770 }
1771}
1772
1773/**
1774 * Changes in 3.1 instead of opening new socket do the following:
1775 * gain more information:
1776 * 1. bind IP
1777 * 2. host port
1778 * 3. guest port
1779 * 4. proto
1780 * 5. guest MAC address
1781 * the guest's MAC address is rather important for service, but we easily
1782 * could get it from VM configuration in DrvNAT or Service, the idea is activating
1783 * corresponding port-forwarding
1784 */
1785int slirp_add_redirect(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1786 struct in_addr guest_addr, int guest_port, const uint8_t *ethaddr)
1787{
1788 struct port_forward_rule *rule = NULL;
1789 Assert(ethaddr);
1790 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1791 {
1792 if ( rule->proto == (is_udp ? IPPROTO_UDP : IPPROTO_TCP)
1793 && rule->host_port == host_port
1794 && rule->bind_ip.s_addr == host_addr.s_addr
1795 && rule->guest_port == guest_port
1796 && rule->guest_addr.s_addr == guest_addr.s_addr
1797 )
1798 return 0; /* rule has been already registered */
1799 }
1800
1801 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1802 if (rule == NULL)
1803 return 1;
1804
1805 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1806 rule->host_port = host_port;
1807 rule->guest_port = guest_port;
1808 rule->guest_addr.s_addr = guest_addr.s_addr;
1809 rule->bind_ip.s_addr = host_addr.s_addr;
1810 memcpy(rule->mac_address, ethaddr, ETH_ALEN);
1811 /* @todo add mac address */
1812 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1813 pData->cRedirectionsStored++;
1814 /* activate port-forwarding if guest has already got assigned IP */
1815 if (memcmp(ethaddr, zerro_ethaddr, ETH_ALEN))
1816 activate_port_forwarding(pData, ethaddr);
1817 return 0;
1818}
1819
1820int slirp_remove_redirect(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1821 struct in_addr guest_addr, int guest_port)
1822{
1823 struct port_forward_rule *rule = NULL;
1824 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1825 {
1826 if ( rule->proto == (is_udp ? IPPROTO_UDP : IPPROTO_TCP)
1827 && rule->host_port == host_port
1828 && rule->guest_port == guest_port
1829 && rule->bind_ip.s_addr == host_addr.s_addr
1830 && rule->guest_addr.s_addr == guest_addr.s_addr
1831 && rule->activated)
1832 {
1833 LogRel(("NAT: remove redirect %s host port %d => guest port %d @ %RTnaipv4\n",
1834 rule->proto == IPPROTO_UDP ? "UDP" : "TCP", rule->host_port, rule->guest_port, guest_addr));
1835
1836 LibAliasUninit(rule->so->so_la);
1837 if (is_udp)
1838 udp_detach(pData, rule->so);
1839 else
1840 tcp_close(pData, sototcpcb(rule->so));
1841 LIST_REMOVE(rule, list);
1842 RTMemFree(rule);
1843 pData->cRedirectionsStored--;
1844 break;
1845 }
1846
1847 }
1848 return 0;
1849}
1850
1851void slirp_set_ethaddr_and_activate_port_forwarding(PNATState pData, const uint8_t *ethaddr, uint32_t GuestIP)
1852{
1853#ifndef VBOX_WITH_NAT_SERVICE
1854 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1855#endif
1856 if (GuestIP != INADDR_ANY)
1857 {
1858 slirp_arp_cache_update_or_add(pData, GuestIP, ethaddr);
1859 activate_port_forwarding(pData, ethaddr);
1860 }
1861}
1862
1863#if defined(RT_OS_WINDOWS)
1864HANDLE *slirp_get_events(PNATState pData)
1865{
1866 return pData->phEvents;
1867}
1868void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1869{
1870 pData->phEvents[index] = hEvent;
1871}
1872#endif
1873
1874unsigned int slirp_get_timeout_ms(PNATState pData)
1875{
1876 if (link_up)
1877 {
1878 if (time_fasttimo)
1879 return 2;
1880 if (do_slowtimo)
1881 return 500; /* see PR_SLOWHZ */
1882 }
1883 return 3600*1000; /* one hour */
1884}
1885
1886#ifndef RT_OS_WINDOWS
1887int slirp_get_nsock(PNATState pData)
1888{
1889 return pData->nsock;
1890}
1891#endif
1892
1893/*
1894 * this function called from NAT thread
1895 */
1896void slirp_post_sent(PNATState pData, void *pvArg)
1897{
1898 struct socket *so = 0;
1899 struct tcpcb *tp = 0;
1900 struct mbuf *m = (struct mbuf *)pvArg;
1901 m_freem(pData, m);
1902}
1903#ifdef VBOX_WITH_SLIRP_MT
1904void slirp_process_queue(PNATState pData)
1905{
1906 RTReqProcess(pData->pReqQueue, RT_INDEFINITE_WAIT);
1907}
1908void *slirp_get_queue(PNATState pData)
1909{
1910 return pData->pReqQueue;
1911}
1912#endif
1913
1914void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1915{
1916 Log2(("tftp_prefix: %s\n", tftpPrefix));
1917 tftp_prefix = tftpPrefix;
1918}
1919
1920void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1921{
1922 Log2(("bootFile: %s\n", bootFile));
1923 bootp_filename = bootFile;
1924}
1925
1926void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1927{
1928 Log2(("next_server: %s\n", next_server));
1929 if (next_server == NULL)
1930 pData->tftp_server.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_TFTP);
1931 else
1932 inet_aton(next_server, &pData->tftp_server);
1933}
1934
1935int slirp_set_binding_address(PNATState pData, char *addr)
1936{
1937 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1938 {
1939 pData->bindIP.s_addr = INADDR_ANY;
1940 return 1;
1941 }
1942 return 0;
1943}
1944
1945void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1946{
1947 if (!pData->fUseHostResolver)
1948 {
1949 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1950 pData->fUseDnsProxy = fDNSProxy;
1951 }
1952 else
1953 LogRel(("NAT: Host Resolver conflicts with DNS proxy, the last one was forcely ignored\n"));
1954}
1955
1956#define CHECK_ARG(name, val, lim_min, lim_max) \
1957 do { \
1958 if ((val) < (lim_min) || (val) > (lim_max)) \
1959 { \
1960 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1961 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1962 return; \
1963 } \
1964 else \
1965 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1966 } while (0)
1967
1968/* don't allow user set less 8kB and more than 1M values */
1969#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
1970void slirp_set_rcvbuf(PNATState pData, int kilobytes)
1971{
1972 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
1973 pData->socket_rcv = kilobytes;
1974}
1975void slirp_set_sndbuf(PNATState pData, int kilobytes)
1976{
1977 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
1978 pData->socket_snd = kilobytes * _1K;
1979}
1980void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
1981{
1982 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
1983 tcp_rcvspace = kilobytes * _1K;
1984}
1985void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
1986{
1987 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
1988 tcp_sndspace = kilobytes * _1K;
1989}
1990
1991/*
1992 * Looking for Ether by ip in ARP-cache
1993 * Note: it´s responsible of caller to allocate buffer for result
1994 * @returns iprt status code
1995 */
1996int slirp_arp_lookup_ether_by_ip(PNATState pData, uint32_t ip, uint8_t *ether)
1997{
1998 struct arp_cache_entry *ac;
1999
2000 if (ether == NULL)
2001 return VERR_INVALID_PARAMETER;
2002
2003 if (LIST_EMPTY(&pData->arp_cache))
2004 return VERR_NOT_FOUND;
2005
2006 LIST_FOREACH(ac, &pData->arp_cache, list)
2007 {
2008 if ( ac->ip == ip
2009 && memcmp(ac->ether, broadcast_ethaddr, ETH_ALEN) != 0)
2010 {
2011 memcpy(ether, ac->ether, ETH_ALEN);
2012 return VINF_SUCCESS;
2013 }
2014 }
2015 return VERR_NOT_FOUND;
2016}
2017
2018/*
2019 * Looking for IP by Ether in ARP-cache
2020 * Note: it´s responsible of caller to allocate buffer for result
2021 * @returns 0 - if found, 1 - otherwise
2022 */
2023int slirp_arp_lookup_ip_by_ether(PNATState pData, const uint8_t *ether, uint32_t *ip)
2024{
2025 struct arp_cache_entry *ac;
2026 *ip = INADDR_ANY;
2027
2028 if (LIST_EMPTY(&pData->arp_cache))
2029 return VERR_NOT_FOUND;
2030
2031 LIST_FOREACH(ac, &pData->arp_cache, list)
2032 {
2033 if (memcmp(ether, ac->ether, ETH_ALEN) == 0)
2034 {
2035 *ip = ac->ip;
2036 return VINF_SUCCESS;
2037 }
2038 }
2039 return VERR_NOT_FOUND;
2040}
2041
2042void slirp_arp_who_has(PNATState pData, uint32_t dst)
2043{
2044 struct mbuf *m;
2045 struct ethhdr *ehdr;
2046 struct arphdr *ahdr;
2047
2048 m = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
2049 if (m == NULL)
2050 {
2051 Log(("NAT: Can't alloc mbuf for ARP request\n"));
2052 return;
2053 }
2054 ehdr = mtod(m, struct ethhdr *);
2055 memset(ehdr->h_source, 0xff, ETH_ALEN);
2056 ahdr = (struct arphdr *)&ehdr[1];
2057 ahdr->ar_hrd = RT_H2N_U16_C(1);
2058 ahdr->ar_pro = RT_H2N_U16_C(ETH_P_IP);
2059 ahdr->ar_hln = ETH_ALEN;
2060 ahdr->ar_pln = 4;
2061 ahdr->ar_op = RT_H2N_U16_C(ARPOP_REQUEST);
2062 memcpy(ahdr->ar_sha, special_ethaddr, ETH_ALEN);
2063 /* we assume that this request come from gw, but not from DNS or TFTP */
2064 ahdr->ar_sha[5] = CTL_ALIAS;
2065 *(uint32_t *)ahdr->ar_sip = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
2066 memset(ahdr->ar_tha, 0xff, ETH_ALEN); /*broadcast*/
2067 *(uint32_t *)ahdr->ar_tip = dst;
2068 /* warn!!! should falls in mbuf minimal size */
2069 m->m_len = sizeof(struct arphdr) + ETH_HLEN;
2070 m->m_data += ETH_HLEN;
2071 m->m_len -= ETH_HLEN;
2072 if_encap(pData, ETH_P_ARP, m, ETH_ENCAP_URG);
2073}
2074
2075/* updates the arp cache
2076 * @note: this is helper function, slirp_arp_cache_update_or_add should be used.
2077 * @returns 0 - if has found and updated
2078 * 1 - if hasn't found.
2079 */
2080static inline int slirp_arp_cache_update(PNATState pData, uint32_t dst, const uint8_t *mac)
2081{
2082 struct arp_cache_entry *ac;
2083 Assert(( memcmp(mac, broadcast_ethaddr, ETH_ALEN)
2084 && memcmp(mac, zerro_ethaddr, ETH_ALEN)));
2085 LIST_FOREACH(ac, &pData->arp_cache, list)
2086 {
2087 if (!memcmp(ac->ether, mac, ETH_ALEN))
2088 {
2089 ac->ip = dst;
2090 return 0;
2091 }
2092 }
2093 return 1;
2094}
2095/**
2096 * add entry to the arp cache
2097 * @note: this is helper function, slirp_arp_cache_update_or_add should be used.
2098 */
2099
2100static inline void slirp_arp_cache_add(PNATState pData, uint32_t ip, const uint8_t *ether)
2101{
2102 struct arp_cache_entry *ac = NULL;
2103 Assert(( memcmp(ether, broadcast_ethaddr, ETH_ALEN)
2104 && memcmp(ether, zerro_ethaddr, ETH_ALEN)));
2105 ac = RTMemAllocZ(sizeof(struct arp_cache_entry));
2106 if (ac == NULL)
2107 {
2108 Log(("NAT: Can't allocate arp cache entry\n"));
2109 return;
2110 }
2111 ac->ip = ip;
2112 memcpy(ac->ether, ether, ETH_ALEN);
2113 LIST_INSERT_HEAD(&pData->arp_cache, ac, list);
2114}
2115
2116/* updates or adds entry to the arp cache
2117 * @returns 0 - if has found and updated
2118 * 1 - if hasn't found.
2119 */
2120int slirp_arp_cache_update_or_add(PNATState pData, uint32_t dst, const uint8_t *mac)
2121{
2122 if ( !memcmp(mac, broadcast_ethaddr, ETH_ALEN)
2123 || !memcmp(mac, zerro_ethaddr, ETH_ALEN))
2124 {
2125 static bool fBroadcastEtherAddReported;
2126 if (!fBroadcastEtherAddReported)
2127 {
2128 LogRel(("NAT: Attempt to add pair [%RTmac:%RTnaipv4] in ARP cache was ignored\n",
2129 mac, dst));
2130 fBroadcastEtherAddReported = true;
2131 }
2132 return 1;
2133 }
2134 if (slirp_arp_cache_update(pData, dst, mac))
2135 slirp_arp_cache_add(pData, dst, mac);
2136
2137 return 0;
2138}
2139
2140
2141void slirp_set_mtu(PNATState pData, int mtu)
2142{
2143 if (mtu < 20 || mtu >= 16000)
2144 {
2145 LogRel(("NAT: mtu(%d) is out of range (20;16000] mtu forcely assigned to 1500\n", mtu));
2146 mtu = 1500;
2147 }
2148 /* MTU is maximum transition unit on */
2149 if_mtu =
2150 if_mru = mtu;
2151}
2152
2153/**
2154 * Info handler.
2155 */
2156void slirp_info(PNATState pData, PCDBGFINFOHLP pHlp, const char *pszArgs)
2157{
2158 struct socket *so, *so_next;
2159 struct arp_cache_entry *ac;
2160 struct port_forward_rule *rule;
2161
2162 pHlp->pfnPrintf(pHlp, "NAT parameters: MTU=%d\n", if_mtu);
2163 pHlp->pfnPrintf(pHlp, "NAT TCP ports:\n");
2164 QSOCKET_FOREACH(so, so_next, tcp)
2165 /* { */
2166 pHlp->pfnPrintf(pHlp, " %R[natsock]\n", so);
2167 }
2168
2169 pHlp->pfnPrintf(pHlp, "NAT UDP ports:\n");
2170 QSOCKET_FOREACH(so, so_next, udp)
2171 /* { */
2172 pHlp->pfnPrintf(pHlp, " %R[natsock]\n", so);
2173 }
2174
2175 pHlp->pfnPrintf(pHlp, "NAT ARP cache:\n");
2176 LIST_FOREACH(ac, &pData->arp_cache, list)
2177 {
2178 pHlp->pfnPrintf(pHlp, " %RTnaipv4 %RTmac\n", ac->ip, &ac->ether);
2179 }
2180
2181 pHlp->pfnPrintf(pHlp, "NAT rules:\n");
2182 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
2183 {
2184 pHlp->pfnPrintf(pHlp, " %s %d => %RTnaipv4:%d %c\n",
2185 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
2186 rule->host_port, rule->guest_addr.s_addr, rule->guest_port,
2187 rule->activated ? ' ' : '*');
2188 }
2189}
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