VirtualBox

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

Last change on this file since 29506 was 29506, checked in by vboxsync, 15 years ago

NAT: backed r61642, pospone till 3.2.2.

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