VirtualBox

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

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

NAT: correct handling end of zone's resources.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 64.8 KB
Line 
1/* $Id: slirp.c 28502 2010-04-20 07:16:46Z vboxsync $ */
2/** @file
3 * NAT - slirp glue.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/*
23 * This code is based on:
24 *
25 * libslirp glue
26 *
27 * Copyright (c) 2004-2008 Fabrice Bellard
28 *
29 * Permission is hereby granted, free of charge, to any person obtaining a copy
30 * of this software and associated documentation files (the "Software"), to deal
31 * in the Software without restriction, including without limitation the rights
32 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
33 * copies of the Software, and to permit persons to whom the Software is
34 * furnished to do so, subject to the following conditions:
35 *
36 * The above copyright notice and this permission notice shall be included in
37 * all copies or substantial portions of the Software.
38 *
39 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
40 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
41 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
42 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
43 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
44 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
45 * THE SOFTWARE.
46 */
47
48#include "slirp.h"
49#ifdef RT_OS_OS2
50# include <paths.h>
51#endif
52
53#include <VBox/err.h>
54#include <VBox/pdmdrv.h>
55#include <iprt/assert.h>
56#include <iprt/file.h>
57#ifndef RT_OS_WINDOWS
58# include <sys/ioctl.h>
59# include <poll.h>
60#else
61# include <Winnls.h>
62# define _WINSOCK2API_
63# include <IPHlpApi.h>
64#endif
65#include <alias.h>
66
67#ifndef RT_OS_WINDOWS
68
69# define DO_ENGAGE_EVENT1(so, fdset, label) \
70 do { \
71 if ( so->so_poll_index != -1 \
72 && so->s == polls[so->so_poll_index].fd) \
73 { \
74 polls[so->so_poll_index].events |= N_(fdset ## _poll); \
75 break; \
76 } \
77 AssertRelease(poll_index < (nfds)); \
78 AssertRelease(poll_index >= 0 && poll_index < (nfds)); \
79 polls[poll_index].fd = (so)->s; \
80 (so)->so_poll_index = poll_index; \
81 polls[poll_index].events = N_(fdset ## _poll); \
82 polls[poll_index].revents = 0; \
83 poll_index++; \
84 } while (0)
85
86# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
87 do { \
88 if ( so->so_poll_index != -1 \
89 && so->s == polls[so->so_poll_index].fd) \
90 { \
91 polls[so->so_poll_index].events |= \
92 N_(fdset1 ## _poll) | N_(fdset2 ## _poll); \
93 break; \
94 } \
95 AssertRelease(poll_index < (nfds)); \
96 polls[poll_index].fd = (so)->s; \
97 (so)->so_poll_index = poll_index; \
98 polls[poll_index].events = \
99 N_(fdset1 ## _poll) | N_(fdset2 ## _poll); \
100 poll_index++; \
101 } while (0)
102
103# define DO_POLL_EVENTS(rc, error, so, events, label) do {} while (0)
104
105/*
106 * DO_CHECK_FD_SET is used in dumping events on socket, including POLLNVAL.
107 * gcc warns about attempts to log POLLNVAL so construction in a last to lines
108 * used to catch POLLNVAL while logging and return false in case of error while
109 * normal usage.
110 */
111# define DO_CHECK_FD_SET(so, events, fdset) \
112 ( ((so)->so_poll_index != -1) \
113 && ((so)->so_poll_index <= ndfs) \
114 && ((so)->s == polls[so->so_poll_index].fd) \
115 && (polls[(so)->so_poll_index].revents & N_(fdset ## _poll)) \
116 && ( N_(fdset ## _poll) == POLLNVAL \
117 || !(polls[(so)->so_poll_index].revents & POLLNVAL)))
118
119 /* specific for Unix API */
120# define DO_UNIX_CHECK_FD_SET(so, events, fdset) DO_CHECK_FD_SET((so), (events), fdset)
121 /* specific for Windows Winsock API */
122# define DO_WIN_CHECK_FD_SET(so, events, fdset) 0
123
124# ifndef RT_OS_LINUX
125# define readfds_poll (POLLRDNORM)
126# define writefds_poll (POLLWRNORM)
127# else
128# define readfds_poll (POLLIN)
129# define writefds_poll (POLLOUT)
130# endif
131# define xfds_poll (POLLPRI)
132# define closefds_poll (POLLHUP)
133# define rderr_poll (POLLERR)
134# define rdhup_poll (POLLHUP)
135# define nval_poll (POLLNVAL)
136
137# define ICMP_ENGAGE_EVENT(so, fdset) \
138 do { \
139 if (pData->icmp_socket.s != -1) \
140 DO_ENGAGE_EVENT1((so), fdset, ICMP); \
141 } while (0)
142
143#else /* RT_OS_WINDOWS */
144
145/*
146 * On Windows, we will be notified by IcmpSendEcho2() when the response arrives.
147 * So no call to WSAEventSelect necessary.
148 */
149# define ICMP_ENGAGE_EVENT(so, fdset) do {} while (0)
150
151/*
152 * On Windows we use FD_ALL_EVENTS to ensure that we don't miss any event.
153 */
154# define DO_ENGAGE_EVENT1(so, fdset1, label) \
155 do { \
156 rc = WSAEventSelect((so)->s, VBOX_SOCKET_EVENT, FD_ALL_EVENTS); \
157 if (rc == SOCKET_ERROR) \
158 { \
159 /* This should not happen */ \
160 error = WSAGetLastError(); \
161 LogRel(("WSAEventSelect (" #label ") error %d (so=%x, socket=%s, event=%x)\n", \
162 error, (so), (so)->s, VBOX_SOCKET_EVENT)); \
163 } \
164 } while (0); \
165 CONTINUE(label)
166
167# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
168 DO_ENGAGE_EVENT1((so), (fdset1), label)
169
170# define DO_POLL_EVENTS(rc, error, so, events, label) \
171 (rc) = WSAEnumNetworkEvents((so)->s, VBOX_SOCKET_EVENT, (events)); \
172 if ((rc) == SOCKET_ERROR) \
173 { \
174 (error) = WSAGetLastError(); \
175 LogRel(("WSAEnumNetworkEvents " #label " error %d\n", (error))); \
176 CONTINUE(label); \
177 }
178
179# define acceptds_win FD_ACCEPT
180# define acceptds_win_bit FD_ACCEPT_BIT
181# define readfds_win FD_READ
182# define readfds_win_bit FD_READ_BIT
183# define writefds_win FD_WRITE
184# define writefds_win_bit FD_WRITE_BIT
185# define xfds_win FD_OOB
186# define xfds_win_bit FD_OOB_BIT
187# define closefds_win FD_CLOSE
188# define closefds_win_bit FD_CLOSE_BIT
189
190# define closefds_win FD_CLOSE
191# define closefds_win_bit FD_CLOSE_BIT
192
193# define DO_CHECK_FD_SET(so, events, fdset) \
194 (((events).lNetworkEvents & fdset ## _win) && ((events).iErrorCode[fdset ## _win_bit] == 0))
195
196# define DO_WIN_CHECK_FD_SET(so, events, fdset) DO_CHECK_FD_SET((so), (events), fdset)
197# define DO_UNIX_CHECK_FD_SET(so, events, fdset) 1 /*specific for Unix API */
198
199#endif /* RT_OS_WINDOWS */
200
201#define TCP_ENGAGE_EVENT1(so, fdset) \
202 DO_ENGAGE_EVENT1((so), fdset, tcp)
203
204#define TCP_ENGAGE_EVENT2(so, fdset1, fdset2) \
205 DO_ENGAGE_EVENT2((so), fdset1, fdset2, tcp)
206
207#define UDP_ENGAGE_EVENT(so, fdset) \
208 DO_ENGAGE_EVENT1((so), fdset, udp)
209
210#define POLL_TCP_EVENTS(rc, error, so, events) \
211 DO_POLL_EVENTS((rc), (error), (so), (events), tcp)
212
213#define POLL_UDP_EVENTS(rc, error, so, events) \
214 DO_POLL_EVENTS((rc), (error), (so), (events), udp)
215
216#define CHECK_FD_SET(so, events, set) \
217 (DO_CHECK_FD_SET((so), (events), set))
218
219#define WIN_CHECK_FD_SET(so, events, set) \
220 (DO_WIN_CHECK_FD_SET((so), (events), set))
221
222#define UNIX_CHECK_FD_SET(so, events, set) \
223 (DO_UNIX_CHECK_FD_SET(so, events, set))
224
225/*
226 * Loging macros
227 */
228#if VBOX_WITH_DEBUG_NAT_SOCKETS
229# if defined(RT_OS_WINDOWS)
230# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
231 do { \
232 LogRel((" " #proto " %R[natsock] %R[natwinnetevents]\n", (so), (winevent))); \
233 } while (0)
234# else /* !RT_OS_WINDOWS */
235# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
236 do { \
237 LogRel((" " #proto " %R[natsock] %s %s %s er: %s, %s, %s\n", (so), \
238 CHECK_FD_SET(so, ign ,r_fdset) ? "READ":"", \
239 CHECK_FD_SET(so, ign, w_fdset) ? "WRITE":"", \
240 CHECK_FD_SET(so, ign, x_fdset) ? "OOB":"", \
241 CHECK_FD_SET(so, ign, rderr) ? "RDERR":"", \
242 CHECK_FD_SET(so, ign, rdhup) ? "RDHUP":"", \
243 CHECK_FD_SET(so, ign, nval) ? "RDNVAL":"")); \
244 } while (0)
245# endif /* !RT_OS_WINDOWS */
246#else /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
247# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) do {} while (0)
248#endif /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
249
250#define LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
251 DO_LOG_NAT_SOCK((so), proto, (winevent), r_fdset, w_fdset, x_fdset)
252
253static void activate_port_forwarding(PNATState, const uint8_t *pEther);
254
255static const uint8_t special_ethaddr[6] =
256{
257 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
258};
259
260static const uint8_t broadcast_ethaddr[6] =
261{
262 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
263};
264
265const uint8_t zerro_ethaddr[6] =
266{
267 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
268};
269
270#ifdef RT_OS_WINDOWS
271static int get_dns_addr_domain(PNATState pData, bool fVerbose,
272 struct in_addr *pdns_addr,
273 const char **ppszDomain)
274{
275 ULONG flags = GAA_FLAG_INCLUDE_PREFIX; /*GAA_FLAG_INCLUDE_ALL_INTERFACES;*/ /* all interfaces registered in NDIS */
276 PIP_ADAPTER_ADDRESSES pAdapterAddr = NULL;
277 PIP_ADAPTER_ADDRESSES pAddr = NULL;
278 PIP_ADAPTER_DNS_SERVER_ADDRESS pDnsAddr = NULL;
279 ULONG size;
280 int wlen = 0;
281 char *pszSuffix;
282 struct dns_domain_entry *pDomain = NULL;
283 ULONG ret = ERROR_SUCCESS;
284
285 /* @todo add SKIPing flags to get only required information */
286
287 /* determine size of buffer */
288 size = 0;
289 ret = pData->pfGetAdaptersAddresses(AF_INET, 0, NULL /* reserved */, pAdapterAddr, &size);
290 if (ret != ERROR_BUFFER_OVERFLOW)
291 {
292 LogRel(("NAT: error %lu occurred on capacity detection operation\n", ret));
293 return -1;
294 }
295 if (size == 0)
296 {
297 LogRel(("NAT: Win socket API returns non capacity\n"));
298 return -1;
299 }
300
301 pAdapterAddr = RTMemAllocZ(size);
302 if (!pAdapterAddr)
303 {
304 LogRel(("NAT: No memory available \n"));
305 return -1;
306 }
307 ret = pData->pfGetAdaptersAddresses(AF_INET, 0, NULL /* reserved */, pAdapterAddr, &size);
308 if (ret != ERROR_SUCCESS)
309 {
310 LogRel(("NAT: error %lu occurred on fetching adapters info\n", ret));
311 RTMemFree(pAdapterAddr);
312 return -1;
313 }
314
315 for (pAddr = pAdapterAddr; pAddr != NULL; pAddr = pAddr->Next)
316 {
317 int found;
318 if (pAddr->OperStatus != IfOperStatusUp)
319 continue;
320
321 for (pDnsAddr = pAddr->FirstDnsServerAddress; pDnsAddr != NULL; pDnsAddr = pDnsAddr->Next)
322 {
323 struct sockaddr *SockAddr = pDnsAddr->Address.lpSockaddr;
324 struct in_addr InAddr;
325 struct dns_entry *pDns;
326
327 if (SockAddr->sa_family != AF_INET)
328 continue;
329
330 InAddr = ((struct sockaddr_in *)SockAddr)->sin_addr;
331
332 /* add dns server to list */
333 pDns = RTMemAllocZ(sizeof(struct dns_entry));
334 if (!pDns)
335 {
336 LogRel(("NAT: Can't allocate buffer for DNS entry\n"));
337 RTMemFree(pAdapterAddr);
338 return VERR_NO_MEMORY;
339 }
340
341 LogRel(("NAT: adding %R[IP4] to DNS server list\n", &InAddr));
342 if ((InAddr.s_addr & RT_H2N_U32_C(IN_CLASSA_NET)) == RT_N2H_U32_C(INADDR_LOOPBACK & IN_CLASSA_NET))
343 pDns->de_addr.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
344 else
345 pDns->de_addr.s_addr = InAddr.s_addr;
346
347 TAILQ_INSERT_HEAD(&pData->pDnsList, pDns, de_list);
348
349 if (pAddr->DnsSuffix == NULL)
350 continue;
351
352 /* uniq */
353 RTUtf16ToUtf8(pAddr->DnsSuffix, &pszSuffix);
354 if (!pszSuffix || strlen(pszSuffix) == 0)
355 {
356 RTStrFree(pszSuffix);
357 continue;
358 }
359
360 found = 0;
361 LIST_FOREACH(pDomain, &pData->pDomainList, dd_list)
362 {
363 if ( pDomain->dd_pszDomain != NULL
364 && strcmp(pDomain->dd_pszDomain, pszSuffix) == 0)
365 {
366 found = 1;
367 RTStrFree(pszSuffix);
368 break;
369 }
370 }
371 if (!found)
372 {
373 pDomain = RTMemAllocZ(sizeof(struct dns_domain_entry));
374 if (!pDomain)
375 {
376 LogRel(("NAT: not enough memory\n"));
377 RTStrFree(pszSuffix);
378 RTMemFree(pAdapterAddr);
379 return VERR_NO_MEMORY;
380 }
381 pDomain->dd_pszDomain = pszSuffix;
382 LogRel(("NAT: adding domain name %s to search list\n", pDomain->dd_pszDomain));
383 LIST_INSERT_HEAD(&pData->pDomainList, pDomain, dd_list);
384 }
385 }
386 }
387 RTMemFree(pAdapterAddr);
388 return 0;
389}
390
391#else /* !RT_OS_WINDOWS */
392
393static int RTFileGets(RTFILE File, void *pvBuf, size_t cbBufSize, size_t *pcbRead)
394{
395 size_t cbRead;
396 char bTest;
397 int rc = VERR_NO_MEMORY;
398 char *pu8Buf = (char *)pvBuf;
399 *pcbRead = 0;
400
401 while ( RT_SUCCESS(rc = RTFileRead(File, &bTest, 1, &cbRead))
402 && (pu8Buf - (char *)pvBuf) < cbBufSize)
403 {
404 if (cbRead == 0)
405 return VERR_EOF;
406
407 if (bTest == '\r' || bTest == '\n')
408 {
409 *pu8Buf = 0;
410 return VINF_SUCCESS;
411 }
412 *pu8Buf = bTest;
413 pu8Buf++;
414 (*pcbRead)++;
415 }
416 return rc;
417}
418
419static int get_dns_addr_domain(PNATState pData, bool fVerbose,
420 struct in_addr *pdns_addr,
421 const char **ppszDomain)
422{
423 char buff[512];
424 char buff2[256];
425 RTFILE f;
426 int fFoundNameserver = 0;
427 struct in_addr tmp_addr;
428 int rc;
429 size_t bytes;
430
431# ifdef RT_OS_OS2
432 /* Try various locations. */
433 char *etc = getenv("ETC");
434 if (etc)
435 {
436 RTStrmPrintf(buff, sizeof(buff), "%s/RESOLV2", etc);
437 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
438 }
439 if (RT_FAILURE(rc))
440 {
441 RTStrmPrintf(buff, sizeof(buff), "%s/RESOLV2", _PATH_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/resolv.conf", _PATH_ETC);
447 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
448 }
449# else /* !RT_OS_OS2 */
450# ifndef DEBUG_vvl
451 rc = RTFileOpen(&f, "/etc/resolv.conf", RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
452# else
453 char *home = getenv("HOME");
454 RTStrPrintf(buff, sizeof(buff), "%s/resolv.conf", home);
455 rc = RTFileOpen(&f, buff, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
456 if (RT_SUCCESS(rc))
457 {
458 Log(("NAT: DNS we're using %s\n", buff));
459 }
460 else
461 {
462 rc = RTFileOpen(&f, "/etc/resolv.conf", RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
463 Log(("NAT: DNS we're using %s\n", buff));
464 }
465# endif
466# endif /* !RT_OS_OS2 */
467 if (RT_FAILURE(rc))
468 return -1;
469
470 if (ppszDomain)
471 *ppszDomain = NULL;
472
473 Log(("NAT: DNS Servers:\n"));
474 while ( RT_SUCCESS(rc = RTFileGets(f, buff, 512, &bytes))
475 && rc != VERR_EOF)
476 {
477 struct dns_entry *pDns = NULL;
478 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1)
479 {
480 if (!inet_aton(buff2, &tmp_addr))
481 continue;
482
483 /* localhost mask */
484 pDns = RTMemAllocZ(sizeof (struct dns_entry));
485 if (!pDns)
486 {
487 LogRel(("can't alloc memory for DNS entry\n"));
488 return -1;
489 }
490
491 /* check */
492 pDns->de_addr.s_addr = tmp_addr.s_addr;
493 if ((pDns->de_addr.s_addr & RT_H2N_U32_C(IN_CLASSA_NET)) == RT_N2H_U32_C(INADDR_LOOPBACK & IN_CLASSA_NET))
494 {
495 pDns->de_addr.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
496 }
497 TAILQ_INSERT_HEAD(&pData->pDnsList, pDns, de_list);
498 fFoundNameserver++;
499 }
500 if ((!strncmp(buff, "domain", 6) || !strncmp(buff, "search", 6)))
501 {
502 char *tok;
503 char *saveptr;
504 struct dns_domain_entry *pDomain = NULL;
505 int fFoundDomain = 0;
506 tok = strtok_r(&buff[6], " \t\n", &saveptr);
507 LIST_FOREACH(pDomain, &pData->pDomainList, dd_list)
508 {
509 if ( tok != NULL
510 && strcmp(tok, pDomain->dd_pszDomain) == 0)
511 {
512 fFoundDomain = 1;
513 break;
514 }
515 }
516 if (tok != NULL && !fFoundDomain)
517 {
518 pDomain = RTMemAllocZ(sizeof(struct dns_domain_entry));
519 if (!pDomain)
520 {
521 LogRel(("NAT: not enought memory to add domain list\n"));
522 return VERR_NO_MEMORY;
523 }
524 pDomain->dd_pszDomain = RTStrDup(tok);
525 LogRel(("NAT: adding domain name %s to search list\n", pDomain->dd_pszDomain));
526 LIST_INSERT_HEAD(&pData->pDomainList, pDomain, dd_list);
527 }
528 }
529 }
530 RTFileClose(f);
531 if (!fFoundNameserver)
532 return -1;
533 return 0;
534}
535
536#endif /* !RT_OS_WINDOWS */
537
538static int slirp_init_dns_list(PNATState pData)
539{
540 TAILQ_INIT(&pData->pDnsList);
541 LIST_INIT(&pData->pDomainList);
542 return get_dns_addr_domain(pData, true, NULL, NULL);
543}
544
545static void slirp_release_dns_list(PNATState pData)
546{
547 struct dns_entry *pDns = NULL;
548 struct dns_domain_entry *pDomain = NULL;
549
550 while (!TAILQ_EMPTY(&pData->pDnsList))
551 {
552 pDns = TAILQ_FIRST(&pData->pDnsList);
553 TAILQ_REMOVE(&pData->pDnsList, pDns, de_list);
554 RTMemFree(pDns);
555 }
556
557 while (!LIST_EMPTY(&pData->pDomainList))
558 {
559 pDomain = LIST_FIRST(&pData->pDomainList);
560 LIST_REMOVE(pDomain, dd_list);
561 if (pDomain->dd_pszDomain != NULL)
562 RTStrFree(pDomain->dd_pszDomain);
563 RTMemFree(pDomain);
564 }
565}
566
567int get_dns_addr(PNATState pData, struct in_addr *pdns_addr)
568{
569 return get_dns_addr_domain(pData, false, pdns_addr, NULL);
570}
571
572int slirp_init(PNATState *ppData, uint32_t u32NetAddr, uint32_t u32Netmask,
573 bool fPassDomain, bool fUseHostResolver, void *pvUser)
574{
575 int fNATfailed = 0;
576 int rc;
577 PNATState pData = RTMemAllocZ(sizeof(NATState));
578 *ppData = pData;
579 if (!pData)
580 return VERR_NO_MEMORY;
581 if (u32Netmask & 0x1f)
582 /* CTL is x.x.x.15, bootp passes up to 16 IPs (15..31) */
583 return VERR_INVALID_PARAMETER;
584 pData->fPassDomain = !fUseHostResolver ? fPassDomain : false;
585 pData->fUseHostResolver = fUseHostResolver;
586 pData->pvUser = pvUser;
587 pData->netmask = u32Netmask;
588
589 /* sockets & TCP defaults */
590 pData->socket_rcv = 64 * _1K;
591 pData->socket_snd = 64 * _1K;
592 tcp_sndspace = 64 * _1K;
593 tcp_rcvspace = 64 * _1K;
594
595#ifdef RT_OS_WINDOWS
596 {
597 WSADATA Data;
598 WSAStartup(MAKEWORD(2, 0), &Data);
599 }
600 pData->phEvents[VBOX_SOCKET_EVENT_INDEX] = CreateEvent(NULL, FALSE, FALSE, NULL);
601#endif
602#ifdef VBOX_WITH_SLIRP_MT
603 QSOCKET_LOCK_CREATE(tcb);
604 QSOCKET_LOCK_CREATE(udb);
605 rc = RTReqCreateQueue(&pData->pReqQueue);
606 AssertReleaseRC(rc);
607#endif
608
609 link_up = 1;
610
611 rc = bootp_dhcp_init(pData);
612 if (rc != 0)
613 {
614 LogRel(("NAT: DHCP server initialization was failed\n"));
615 return VINF_NAT_DNS;
616 }
617 debug_init();
618 if_init(pData);
619 ip_init(pData);
620 icmp_init(pData);
621
622 /* Initialise mbufs *after* setting the MTU */
623#ifndef VBOX_WITH_SLIRP_BSD_MBUF
624 m_init(pData);
625#else
626 mbuf_init(pData);
627#endif
628
629 pData->special_addr.s_addr = u32NetAddr;
630 pData->slirp_ethaddr = &special_ethaddr[0];
631 alias_addr.s_addr = pData->special_addr.s_addr | RT_H2N_U32_C(CTL_ALIAS);
632 /* @todo: add ability to configure this staff */
633
634 /* set default addresses */
635 inet_aton("127.0.0.1", &loopback_addr);
636 if (!pData->fUseHostResolver)
637 {
638 if (slirp_init_dns_list(pData) < 0)
639 fNATfailed = 1;
640
641 dnsproxy_init(pData);
642 }
643
644 getouraddr(pData);
645 {
646 int flags = 0;
647 struct in_addr proxy_addr;
648 pData->proxy_alias = LibAliasInit(pData, NULL);
649 if (pData->proxy_alias == NULL)
650 {
651 LogRel(("NAT: LibAlias default rule wasn't initialized\n"));
652 AssertMsgFailed(("NAT: LibAlias default rule wasn't initialized\n"));
653 }
654 flags = LibAliasSetMode(pData->proxy_alias, 0, 0);
655#ifndef NO_FW_PUNCH
656 flags |= PKT_ALIAS_PUNCH_FW;
657#endif
658 flags |= PKT_ALIAS_PROXY_ONLY; /* do transparent proxying */
659 flags |= PKT_ALIAS_LOG; /* set logging */
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 |= PKT_ALIAS_LOG; /* set logging */
1784 flags |= PKT_ALIAS_PROXY_ONLY; /* do transparent proxying */
1785 flags |= PKT_ALIAS_REVERSE; /* set logging */
1786 flags = LibAliasSetMode(lib, flags, ~0);
1787
1788 alias.s_addr = RT_H2N_U32(RT_N2H_U32(guest_addr) | CTL_ALIAS);
1789 alias_link = LibAliasRedirectPort(lib, psin->sin_addr, RT_H2N_U16(rule->host_port),
1790 alias, RT_H2N_U16(rule->guest_port),
1791 pData->special_addr, -1, /* not very clear for now */
1792 rule->proto);
1793 if (!alias_link)
1794 goto remove_port_forwarding;
1795
1796 so->so_la = lib;
1797 rule->activated = 1;
1798 pData->cRedirectionsActive++;
1799 continue;
1800
1801 remove_port_forwarding:
1802 LogRel(("NAT: failed to redirect %s %d => %d\n",
1803 (rule->proto == IPPROTO_UDP?"UDP":"TCP"), rule->host_port, rule->guest_port));
1804 LIST_REMOVE(rule, list);
1805 pData->cRedirectionsStored--;
1806 RTMemFree(rule);
1807 }
1808}
1809
1810/**
1811 * Changes in 3.1 instead of opening new socket do the following:
1812 * gain more information:
1813 * 1. bind IP
1814 * 2. host port
1815 * 3. guest port
1816 * 4. proto
1817 * 5. guest MAC address
1818 * the guest's MAC address is rather important for service, but we easily
1819 * could get it from VM configuration in DrvNAT or Service, the idea is activating
1820 * corresponding port-forwarding
1821 */
1822int slirp_redir(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1823 struct in_addr guest_addr, int guest_port, const uint8_t *ethaddr)
1824{
1825 struct port_forward_rule *rule = NULL;
1826 Assert(memcmp(ethaddr, zerro_ethaddr, ETH_ALEN) == 0);
1827
1828 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1829 if (rule == NULL)
1830 return 1;
1831
1832 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1833 rule->host_port = host_port;
1834 rule->guest_port = guest_port;
1835#ifndef VBOX_WITH_NAT_SERVICE
1836 rule->guest_addr.s_addr = guest_addr.s_addr;
1837#endif
1838 rule->bind_ip.s_addr = host_addr.s_addr;
1839 memcpy(rule->mac_address, ethaddr, ETH_ALEN);
1840 /* @todo add mac address */
1841 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1842 pData->cRedirectionsStored++;
1843 return 0;
1844}
1845
1846void slirp_set_ethaddr_and_activate_port_forwarding(PNATState pData, const uint8_t *ethaddr, uint32_t GuestIP)
1847{
1848#ifndef VBOX_WITH_NAT_SERVICE
1849 memcpy(client_ethaddr, ethaddr, ETH_ALEN);
1850#endif
1851 if (GuestIP != INADDR_ANY)
1852 {
1853 slirp_arp_cache_update_or_add(pData, GuestIP, ethaddr);
1854 activate_port_forwarding(pData, ethaddr);
1855 }
1856}
1857
1858#if defined(RT_OS_WINDOWS)
1859HANDLE *slirp_get_events(PNATState pData)
1860{
1861 return pData->phEvents;
1862}
1863void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1864{
1865 pData->phEvents[index] = hEvent;
1866}
1867#endif
1868
1869unsigned int slirp_get_timeout_ms(PNATState pData)
1870{
1871 if (link_up)
1872 {
1873 if (time_fasttimo)
1874 return 2;
1875 if (do_slowtimo)
1876 return 500; /* see PR_SLOWHZ */
1877 }
1878 return 3600*1000; /* one hour */
1879}
1880
1881#ifndef RT_OS_WINDOWS
1882int slirp_get_nsock(PNATState pData)
1883{
1884 return pData->nsock;
1885}
1886#endif
1887
1888/*
1889 * this function called from NAT thread
1890 */
1891void slirp_post_sent(PNATState pData, void *pvArg)
1892{
1893 struct socket *so = 0;
1894 struct tcpcb *tp = 0;
1895 struct mbuf *m = (struct mbuf *)pvArg;
1896 m_freem(pData, m);
1897}
1898#ifdef VBOX_WITH_SLIRP_MT
1899void slirp_process_queue(PNATState pData)
1900{
1901 RTReqProcess(pData->pReqQueue, RT_INDEFINITE_WAIT);
1902}
1903void *slirp_get_queue(PNATState pData)
1904{
1905 return pData->pReqQueue;
1906}
1907#endif
1908
1909void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1910{
1911 Log2(("tftp_prefix:%s\n", tftpPrefix));
1912 tftp_prefix = tftpPrefix;
1913}
1914
1915void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1916{
1917 Log2(("bootFile:%s\n", bootFile));
1918 bootp_filename = bootFile;
1919}
1920
1921void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1922{
1923 Log2(("next_server:%s\n", next_server));
1924 if (next_server == NULL)
1925 pData->tftp_server.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_TFTP);
1926 else
1927 inet_aton(next_server, &pData->tftp_server);
1928}
1929
1930int slirp_set_binding_address(PNATState pData, char *addr)
1931{
1932 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1933 {
1934 pData->bindIP.s_addr = INADDR_ANY;
1935 return 1;
1936 }
1937 return 0;
1938}
1939
1940void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1941{
1942 if (!pData->fUseHostResolver)
1943 {
1944 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1945 pData->fUseDnsProxy = fDNSProxy;
1946 }
1947 else
1948 LogRel(("NAT: Host Resolver conflicts with DNS proxy, the last one was forcely ignored\n"));
1949}
1950
1951#define CHECK_ARG(name, val, lim_min, lim_max) \
1952 do { \
1953 if ((val) < (lim_min) || (val) > (lim_max)) \
1954 { \
1955 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1956 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1957 return; \
1958 } \
1959 else \
1960 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1961 } while (0)
1962
1963/* don't allow user set less 8kB and more than 1M values */
1964#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
1965void slirp_set_rcvbuf(PNATState pData, int kilobytes)
1966{
1967 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
1968 pData->socket_rcv = kilobytes;
1969}
1970void slirp_set_sndbuf(PNATState pData, int kilobytes)
1971{
1972 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
1973 pData->socket_snd = kilobytes * _1K;
1974}
1975void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
1976{
1977 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
1978 tcp_rcvspace = kilobytes * _1K;
1979}
1980void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
1981{
1982 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
1983 tcp_sndspace = kilobytes * _1K;
1984}
1985
1986/*
1987 * Looking for Ether by ip in ARP-cache
1988 * Note: it´s responsible of caller to allocate buffer for result
1989 * @returns iprt status code
1990 */
1991int slirp_arp_lookup_ether_by_ip(PNATState pData, uint32_t ip, uint8_t *ether)
1992{
1993 struct arp_cache_entry *ac;
1994
1995 if (ether == NULL)
1996 return VERR_INVALID_PARAMETER;
1997
1998 if (LIST_EMPTY(&pData->arp_cache))
1999 return VERR_NOT_FOUND;
2000
2001 LIST_FOREACH(ac, &pData->arp_cache, list)
2002 {
2003 if (ac->ip == ip)
2004 {
2005 memcpy(ether, ac->ether, ETH_ALEN);
2006 return VINF_SUCCESS;
2007 }
2008 }
2009 return VERR_NOT_FOUND;
2010}
2011
2012/*
2013 * Looking for IP by Ether in ARP-cache
2014 * Note: it´s responsible of caller to allocate buffer for result
2015 * @returns 0 - if found, 1 - otherwise
2016 */
2017int slirp_arp_lookup_ip_by_ether(PNATState pData, const uint8_t *ether, uint32_t *ip)
2018{
2019 struct arp_cache_entry *ac;
2020 *ip = INADDR_ANY;
2021
2022 if (LIST_EMPTY(&pData->arp_cache))
2023 return VERR_NOT_FOUND;
2024
2025 LIST_FOREACH(ac, &pData->arp_cache, list)
2026 {
2027 if (memcmp(ether, ac->ether, ETH_ALEN) == 0)
2028 {
2029 *ip = ac->ip;
2030 return VINF_SUCCESS;
2031 }
2032 }
2033 return VERR_NOT_FOUND;
2034}
2035
2036void slirp_arp_who_has(PNATState pData, uint32_t dst)
2037{
2038 struct mbuf *m;
2039 struct ethhdr *ehdr;
2040 struct arphdr *ahdr;
2041
2042#ifndef VBOX_WITH_SLIRP_BSD_MBUF
2043 m = m_get(pData);
2044#else
2045 m = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
2046#endif
2047 if (m == NULL)
2048 {
2049 LogRel(("NAT: Can't alloc mbuf for ARP request\n"));
2050 return;
2051 }
2052 ehdr = mtod(m, struct ethhdr *);
2053 memset(ehdr->h_source, 0xff, ETH_ALEN);
2054 ahdr = (struct arphdr *)&ehdr[1];
2055 ahdr->ar_hrd = RT_H2N_U16_C(1);
2056 ahdr->ar_pro = RT_H2N_U16_C(ETH_P_IP);
2057 ahdr->ar_hln = ETH_ALEN;
2058 ahdr->ar_pln = 4;
2059 ahdr->ar_op = RT_H2N_U16_C(ARPOP_REQUEST);
2060 memcpy(ahdr->ar_sha, special_ethaddr, ETH_ALEN);
2061 *(uint32_t *)ahdr->ar_sip = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
2062 memset(ahdr->ar_tha, 0xff, ETH_ALEN); /*broadcast*/
2063 *(uint32_t *)ahdr->ar_tip = dst;
2064#ifndef VBOX_WITH_SLIRP_BSD_MBUF
2065 m->m_data += if_maxlinkhdr;
2066 m->m_len = sizeof(struct arphdr);
2067#else
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#endif
2073 if_encap(pData, ETH_P_ARP, m, ETH_ENCAP_URG);
2074}
2075
2076int slirp_arp_cache_update_or_add(PNATState pData, uint32_t dst, const uint8_t *mac)
2077{
2078 if (slirp_arp_cache_update(pData, dst, mac))
2079 slirp_arp_cache_add(pData, dst, mac);
2080
2081 return 0;
2082}
2083
2084/* updates the arp cache
2085 * @returns 0 - if has found and updated
2086 * 1 - if hasn't found.
2087 */
2088int slirp_arp_cache_update(PNATState pData, uint32_t dst, const uint8_t *mac)
2089{
2090 struct arp_cache_entry *ac;
2091 LIST_FOREACH(ac, &pData->arp_cache, list)
2092 {
2093 if (memcmp(ac->ether, mac, ETH_ALEN) == 0)
2094 {
2095 ac->ip = dst;
2096 return 0;
2097 }
2098 }
2099 return 1;
2100}
2101
2102void slirp_arp_cache_add(PNATState pData, uint32_t ip, const uint8_t *ether)
2103{
2104 struct arp_cache_entry *ac = NULL;
2105 ac = RTMemAllocZ(sizeof(struct arp_cache_entry));
2106 if (ac == NULL)
2107 {
2108 LogRel(("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#ifdef VBOX_WITH_SLIRP_BSD_MBUF
2117void slirp_set_mtu(PNATState pData, int mtu)
2118{
2119 if (mtu < 20 || mtu >= 16000)
2120 {
2121 LogRel(("NAT: mtu(%d) is out of range (20;16000] mtu forcely assigned to 1500\n", mtu));
2122 mtu = 1500;
2123 }
2124 if_mtu =
2125 if_mru = mtu;
2126}
2127#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