VirtualBox

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

Last change on this file since 59202 was 59063, checked in by vboxsync, 8 years ago

NAT: Move host resolver out of libalias. This is a minimal change
that only adapts existing code to its new call site, though I have
g/c'ed some of the bogus bits of doanswer().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 64.5 KB
Line 
1/* $Id: slirp.c 59063 2015-12-08 21:39:32Z vboxsync $ */
2/** @file
3 * NAT - slirp glue.
4 */
5
6/*
7 * Copyright (C) 2006-2015 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18/*
19 * This code is based on:
20 *
21 * libslirp glue
22 *
23 * Copyright (c) 2004-2008 Fabrice Bellard
24 *
25 * Permission is hereby granted, free of charge, to any person obtaining a copy
26 * of this software and associated documentation files (the "Software"), to deal
27 * in the Software without restriction, including without limitation the rights
28 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
29 * copies of the Software, and to permit persons to whom the Software is
30 * furnished to do so, subject to the following conditions:
31 *
32 * The above copyright notice and this permission notice shall be included in
33 * all copies or substantial portions of the Software.
34 *
35 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
36 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
37 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
38 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
39 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
40 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
41 * THE SOFTWARE.
42 */
43
44#include "slirp.h"
45#ifdef RT_OS_OS2
46# include <paths.h>
47#endif
48
49#include <VBox/err.h>
50#include <VBox/vmm/dbgf.h>
51#include <VBox/vmm/pdmdrv.h>
52#include <iprt/assert.h>
53#include <iprt/file.h>
54#ifndef RT_OS_WINDOWS
55# include <sys/ioctl.h>
56# include <poll.h>
57# include <netinet/in.h>
58#else
59# include <Winnls.h>
60# define _WINSOCK2API_
61# include <IPHlpApi.h>
62#endif
63#include <alias.h>
64
65#ifndef RT_OS_WINDOWS
66/**
67 * XXX: It shouldn't be non-Windows specific.
68 * resolv_conf_parser.h client's structure isn't OS specific, it's just need to be generalized a
69 * a bit to replace slirp_state.h DNS server (domain) lists with rcp_state like structure.
70 */
71# include "resolv_conf_parser.h"
72#endif
73
74#ifndef RT_OS_WINDOWS
75# define DO_ENGAGE_EVENT1(so, fdset, label) \
76 do { \
77 if ( so->so_poll_index != -1 \
78 && so->s == polls[so->so_poll_index].fd) \
79 { \
80 polls[so->so_poll_index].events |= N_(fdset ## _poll); \
81 break; \
82 } \
83 AssertRelease(poll_index < (nfds)); \
84 AssertRelease(poll_index >= 0 && poll_index < (nfds)); \
85 polls[poll_index].fd = (so)->s; \
86 (so)->so_poll_index = poll_index; \
87 polls[poll_index].events = N_(fdset ## _poll); \
88 polls[poll_index].revents = 0; \
89 poll_index++; \
90 } while (0)
91
92# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
93 do { \
94 if ( so->so_poll_index != -1 \
95 && so->s == polls[so->so_poll_index].fd) \
96 { \
97 polls[so->so_poll_index].events |= \
98 N_(fdset1 ## _poll) | N_(fdset2 ## _poll); \
99 break; \
100 } \
101 AssertRelease(poll_index < (nfds)); \
102 polls[poll_index].fd = (so)->s; \
103 (so)->so_poll_index = poll_index; \
104 polls[poll_index].events = \
105 N_(fdset1 ## _poll) | N_(fdset2 ## _poll); \
106 poll_index++; \
107 } while (0)
108
109# define DO_POLL_EVENTS(rc, error, so, events, label) do {} while (0)
110
111/*
112 * DO_CHECK_FD_SET is used in dumping events on socket, including POLLNVAL.
113 * gcc warns about attempts to log POLLNVAL so construction in a last to lines
114 * used to catch POLLNVAL while logging and return false in case of error while
115 * normal usage.
116 */
117# define DO_CHECK_FD_SET(so, events, fdset) \
118 ( ((so)->so_poll_index != -1) \
119 && ((so)->so_poll_index <= ndfs) \
120 && ((so)->s == polls[so->so_poll_index].fd) \
121 && (polls[(so)->so_poll_index].revents & N_(fdset ## _poll)) \
122 && ( N_(fdset ## _poll) == POLLNVAL \
123 || !(polls[(so)->so_poll_index].revents & POLLNVAL)))
124
125 /* specific for Windows Winsock API */
126# define DO_WIN_CHECK_FD_SET(so, events, fdset) 0
127
128# ifndef RT_OS_LINUX
129# define readfds_poll (POLLRDNORM)
130# define writefds_poll (POLLWRNORM)
131# else
132# define readfds_poll (POLLIN)
133# define writefds_poll (POLLOUT)
134# endif
135# define xfds_poll (POLLPRI)
136# define closefds_poll (POLLHUP)
137# define rderr_poll (POLLERR)
138# if 0 /* unused yet */
139# define rdhup_poll (POLLHUP)
140# define nval_poll (POLLNVAL)
141# endif
142
143# define ICMP_ENGAGE_EVENT(so, fdset) \
144 do { \
145 if (pData->icmp_socket.s != -1) \
146 DO_ENGAGE_EVENT1((so), fdset, ICMP); \
147 } while (0)
148
149#else /* RT_OS_WINDOWS */
150
151/*
152 * On Windows, we will be notified by IcmpSendEcho2() when the response arrives.
153 * So no call to WSAEventSelect necessary.
154 */
155# define ICMP_ENGAGE_EVENT(so, fdset) do {} while (0)
156
157/*
158 * On Windows we use FD_ALL_EVENTS to ensure that we don't miss any event.
159 */
160# define DO_ENGAGE_EVENT1(so, fdset1, label) \
161 do { \
162 rc = WSAEventSelect((so)->s, VBOX_SOCKET_EVENT, FD_ALL_EVENTS); \
163 if (rc == SOCKET_ERROR) \
164 { \
165 /* This should not happen */ \
166 error = WSAGetLastError(); \
167 LogRel(("WSAEventSelect (" #label ") error %d (so=%x, socket=%s, event=%x)\n", \
168 error, (so), (so)->s, VBOX_SOCKET_EVENT)); \
169 } \
170 } while (0); \
171 CONTINUE(label)
172
173# define DO_ENGAGE_EVENT2(so, fdset1, fdset2, label) \
174 DO_ENGAGE_EVENT1((so), (fdset1), label)
175
176# define DO_POLL_EVENTS(rc, error, so, events, label) \
177 (rc) = WSAEnumNetworkEvents((so)->s, VBOX_SOCKET_EVENT, (events)); \
178 if ((rc) == SOCKET_ERROR) \
179 { \
180 (error) = WSAGetLastError(); \
181 LogRel(("WSAEnumNetworkEvents %R[natsock] " #label " error %d\n", (so), (error))); \
182 LogFunc(("WSAEnumNetworkEvents %R[natsock] " #label " error %d\n", (so), (error))); \
183 CONTINUE(label); \
184 }
185
186# define acceptds_win FD_ACCEPT
187# define acceptds_win_bit FD_ACCEPT_BIT
188# define readfds_win FD_READ
189# define readfds_win_bit FD_READ_BIT
190# define writefds_win FD_WRITE
191# define writefds_win_bit FD_WRITE_BIT
192# define xfds_win FD_OOB
193# define xfds_win_bit FD_OOB_BIT
194# define closefds_win FD_CLOSE
195# define closefds_win_bit FD_CLOSE_BIT
196# define connectfds_win FD_CONNECT
197# define connectfds_win_bit FD_CONNECT_BIT
198
199# define closefds_win FD_CLOSE
200# define closefds_win_bit FD_CLOSE_BIT
201
202# define DO_CHECK_FD_SET(so, events, fdset) \
203 ((events).lNetworkEvents & fdset ## _win)
204
205# define DO_WIN_CHECK_FD_SET(so, events, fdset) DO_CHECK_FD_SET((so), (events), fdset)
206# define DO_UNIX_CHECK_FD_SET(so, events, fdset) 1 /*specific for Unix API */
207
208#endif /* RT_OS_WINDOWS */
209
210#define TCP_ENGAGE_EVENT1(so, fdset) \
211 DO_ENGAGE_EVENT1((so), fdset, tcp)
212
213#define TCP_ENGAGE_EVENT2(so, fdset1, fdset2) \
214 DO_ENGAGE_EVENT2((so), fdset1, fdset2, tcp)
215
216#ifdef RT_OS_WINDOWS
217# define WIN_TCP_ENGAGE_EVENT2(so, fdset, fdset2) TCP_ENGAGE_EVENT2(so, fdset1, fdset2)
218#endif
219
220#define UDP_ENGAGE_EVENT(so, fdset) \
221 DO_ENGAGE_EVENT1((so), fdset, udp)
222
223#define POLL_TCP_EVENTS(rc, error, so, events) \
224 DO_POLL_EVENTS((rc), (error), (so), (events), tcp)
225
226#define POLL_UDP_EVENTS(rc, error, so, events) \
227 DO_POLL_EVENTS((rc), (error), (so), (events), udp)
228
229#define CHECK_FD_SET(so, events, set) \
230 (DO_CHECK_FD_SET((so), (events), set))
231
232#define WIN_CHECK_FD_SET(so, events, set) \
233 (DO_WIN_CHECK_FD_SET((so), (events), set))
234
235/*
236 * Loging macros
237 */
238#if VBOX_WITH_DEBUG_NAT_SOCKETS
239# if defined(RT_OS_WINDOWS)
240# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
241 do { \
242 LogRel((" " #proto " %R[natsock] %R[natwinnetevents]\n", (so), (winevent))); \
243 } while (0)
244# else /* !RT_OS_WINDOWS */
245# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
246 do { \
247 LogRel((" " #proto " %R[natsock] %s %s %s er: %s, %s, %s\n", (so), \
248 CHECK_FD_SET(so, ign ,r_fdset) ? "READ":"", \
249 CHECK_FD_SET(so, ign, w_fdset) ? "WRITE":"", \
250 CHECK_FD_SET(so, ign, x_fdset) ? "OOB":"", \
251 CHECK_FD_SET(so, ign, rderr) ? "RDERR":"", \
252 CHECK_FD_SET(so, ign, rdhup) ? "RDHUP":"", \
253 CHECK_FD_SET(so, ign, nval) ? "RDNVAL":"")); \
254 } while (0)
255# endif /* !RT_OS_WINDOWS */
256#else /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
257# define DO_LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) do {} while (0)
258#endif /* !VBOX_WITH_DEBUG_NAT_SOCKETS */
259
260#define LOG_NAT_SOCK(so, proto, winevent, r_fdset, w_fdset, x_fdset) \
261 DO_LOG_NAT_SOCK((so), proto, (winevent), r_fdset, w_fdset, x_fdset)
262
263static const uint8_t special_ethaddr[6] =
264{
265 0x52, 0x54, 0x00, 0x12, 0x35, 0x00
266};
267
268static const uint8_t broadcast_ethaddr[6] =
269{
270 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
271};
272
273const uint8_t zerro_ethaddr[6] =
274{
275 0x0, 0x0, 0x0, 0x0, 0x0, 0x0
276};
277
278/**
279 * This helper routine do the checks in descriptions to
280 * ''fUnderPolling'' and ''fShouldBeRemoved'' flags
281 * @returns 1 if socket removed and 0 if no changes was made.
282 */
283static int slirpVerifyAndFreeSocket(PNATState pData, struct socket *pSocket)
284{
285 AssertPtrReturn(pData, 0);
286 AssertPtrReturn(pSocket, 0);
287 AssertReturn(pSocket->fUnderPolling, 0);
288 if (pSocket->fShouldBeRemoved)
289 {
290 pSocket->fUnderPolling = 0;
291 sofree(pData, pSocket);
292 /* pSocket is PHANTOM, now */
293 return 1;
294 }
295 return 0;
296}
297
298int slirp_init(PNATState *ppData, uint32_t u32NetAddr, uint32_t u32Netmask,
299 bool fPassDomain, bool fUseHostResolver, int i32AliasMode,
300 int iIcmpCacheLimit, void *pvUser)
301{
302 int rc;
303 PNATState pData;
304 if (u32Netmask & 0x1f)
305 {
306 /* CTL is x.x.x.15, bootp passes up to 16 IPs (15..31) */
307 LogRel(("NAT: The last 5 bits of the netmask (%RTnaipv4) need to be unset\n", RT_BE2H_U32(u32Netmask)));
308 return VERR_INVALID_PARAMETER;
309 }
310 pData = RTMemAllocZ(RT_ALIGN_Z(sizeof(NATState), sizeof(uint64_t)));
311 *ppData = pData;
312 if (!pData)
313 return VERR_NO_MEMORY;
314 pData->fPassDomain = !fUseHostResolver ? fPassDomain : false;
315 pData->fUseHostResolver = fUseHostResolver;
316 pData->fUseHostResolverPermanent = fUseHostResolver;
317 pData->pvUser = pvUser;
318 pData->netmask = u32Netmask;
319
320 rc = RTCritSectRwInit(&pData->CsRwHandlerChain);
321 if (RT_FAILURE(rc))
322 return rc;
323
324 /* sockets & TCP defaults */
325 pData->socket_rcv = 64 * _1K;
326 pData->socket_snd = 64 * _1K;
327 tcp_sndspace = 64 * _1K;
328 tcp_rcvspace = 64 * _1K;
329
330 /*
331 * Use the same default here as in DevNAT.cpp (SoMaxConnection CFGM value)
332 * to avoid release log noise.
333 */
334 pData->soMaxConn = 10;
335
336#ifdef RT_OS_WINDOWS
337 {
338 WSADATA Data;
339 RTLDRMOD hLdrMod;
340
341 WSAStartup(MAKEWORD(2, 0), &Data);
342
343 rc = RTLdrLoadSystem("Iphlpapi.dll", /* :fNoUnload */ true, &hLdrMod);
344 if (RT_SUCCESS(rc))
345 {
346 rc = RTLdrGetSymbol(hLdrMod, "GetAdaptersAddresses", (void **)&pData->pfGetAdaptersAddresses);
347 if (RT_FAILURE(rc))
348 LogRel(("NAT: Can't find GetAdapterAddresses in Iphlpapi.dll\n"));
349
350 RTLdrClose(hLdrMod);
351 }
352 }
353 pData->phEvents[VBOX_SOCKET_EVENT_INDEX] = CreateEvent(NULL, FALSE, FALSE, NULL);
354#endif
355
356 rc = bootp_dhcp_init(pData);
357 if (RT_FAILURE(rc))
358 {
359 Log(("NAT: DHCP server initialization failed\n"));
360 RTMemFree(pData);
361 *ppData = NULL;
362 return rc;
363 }
364 debug_init(pData);
365 if_init(pData);
366 ip_init(pData);
367 icmp_init(pData, iIcmpCacheLimit);
368
369 /* Initialise mbufs *after* setting the MTU */
370 mbuf_init(pData);
371
372 pData->special_addr.s_addr = u32NetAddr;
373 pData->slirp_ethaddr = &special_ethaddr[0];
374 alias_addr.s_addr = pData->special_addr.s_addr | RT_H2N_U32_C(CTL_ALIAS);
375 /* @todo: add ability to configure this staff */
376
377 /* set default addresses */
378 inet_aton("127.0.0.1", &loopback_addr);
379
380 rc = slirpTftpInit(pData);
381 AssertRCReturn(rc, VINF_NAT_DNS);
382
383 if (i32AliasMode & ~(PKT_ALIAS_LOG|PKT_ALIAS_SAME_PORTS|PKT_ALIAS_PROXY_ONLY))
384 {
385 Log(("NAT: alias mode %x is ignored\n", i32AliasMode));
386 i32AliasMode = 0;
387 }
388 pData->i32AliasMode = i32AliasMode;
389 getouraddr(pData);
390 {
391 int flags = 0;
392 struct in_addr proxy_addr;
393 pData->proxy_alias = LibAliasInit(pData, NULL);
394 if (pData->proxy_alias == NULL)
395 {
396 Log(("NAT: LibAlias default rule wasn't initialized\n"));
397 AssertMsgFailed(("NAT: LibAlias default rule wasn't initialized\n"));
398 }
399 flags = LibAliasSetMode(pData->proxy_alias, 0, 0);
400#ifndef NO_FW_PUNCH
401 flags |= PKT_ALIAS_PUNCH_FW;
402#endif
403 flags |= pData->i32AliasMode; /* do transparent proxying */
404 flags = LibAliasSetMode(pData->proxy_alias, flags, ~0);
405 proxy_addr.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
406 LibAliasSetAddress(pData->proxy_alias, proxy_addr);
407 ftp_alias_load(pData);
408 nbt_alias_load(pData);
409 }
410#ifdef VBOX_WITH_NAT_SEND2HOME
411 /* @todo: we should know all interfaces available on host. */
412 pData->pInSockAddrHomeAddress = RTMemAllocZ(sizeof(struct sockaddr));
413 pData->cInHomeAddressSize = 1;
414 inet_aton("192.168.1.25", &pData->pInSockAddrHomeAddress[0].sin_addr);
415 pData->pInSockAddrHomeAddress[0].sin_family = AF_INET;
416# ifdef RT_OS_DARWIN
417 pData->pInSockAddrHomeAddress[0].sin_len = sizeof(struct sockaddr_in);
418# endif
419#endif
420
421 slirp_link_up(pData);
422 return VINF_SUCCESS;
423}
424
425/**
426 * Register statistics.
427 */
428void slirp_register_statistics(PNATState pData, PPDMDRVINS pDrvIns)
429{
430#ifdef VBOX_WITH_STATISTICS
431# define PROFILE_COUNTER(name, dsc) REGISTER_COUNTER(name, pData, STAMTYPE_PROFILE, STAMUNIT_TICKS_PER_CALL, dsc)
432# define COUNTING_COUNTER(name, dsc) REGISTER_COUNTER(name, pData, STAMTYPE_COUNTER, STAMUNIT_COUNT, dsc)
433# include "counters.h"
434# undef COUNTER
435/** @todo register statistics for the variables dumped by:
436 * ipstats(pData); tcpstats(pData); udpstats(pData); icmpstats(pData);
437 * mbufstats(pData); sockstats(pData); */
438#else /* VBOX_WITH_STATISTICS */
439 NOREF(pData);
440 NOREF(pDrvIns);
441#endif /* !VBOX_WITH_STATISTICS */
442}
443
444/**
445 * Deregister statistics.
446 */
447void slirp_deregister_statistics(PNATState pData, PPDMDRVINS pDrvIns)
448{
449 if (pData == NULL)
450 return;
451#ifdef VBOX_WITH_STATISTICS
452# define PROFILE_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pData)
453# define COUNTING_COUNTER(name, dsc) DEREGISTER_COUNTER(name, pData)
454# include "counters.h"
455#else /* VBOX_WITH_STATISTICS */
456 NOREF(pData);
457 NOREF(pDrvIns);
458#endif /* !VBOX_WITH_STATISTICS */
459}
460
461/**
462 * Marks the link as up, making it possible to establish new connections.
463 */
464void slirp_link_up(PNATState pData)
465{
466 struct arp_cache_entry *ac;
467
468 if (link_up == 1)
469 return;
470
471 link_up = 1;
472
473 if (!pData->fUseHostResolverPermanent)
474 slirpInitializeDnsSettings(pData);
475}
476
477/**
478 * Marks the link as down and cleans up the current connections.
479 */
480void slirp_link_down(PNATState pData)
481{
482 struct port_forward_rule *rule;
483
484 if (link_up == 0)
485 return;
486
487 slirpReleaseDnsSettings(pData);
488
489 link_up = 0;
490}
491
492/**
493 * Terminates the slirp component.
494 */
495void slirp_term(PNATState pData)
496{
497 struct socket *so;
498
499 if (pData == NULL)
500 return;
501
502 icmp_finit(pData);
503
504 while ((so = tcb.so_next) != &tcb)
505 {
506 /* Don't miss TCB releasing */
507 if ( !sototcpcb(so)
508 && ( so->so_state & SS_NOFDREF
509 || so->s == -1))
510 sofree(pData, so);
511 else
512 tcp_close(pData, sototcpcb(so));
513 }
514
515 while ((so = udb.so_next) != &udb)
516 udp_detach(pData, so);
517
518 slirp_link_down(pData);
519 ftp_alias_unload(pData);
520 nbt_alias_unload(pData);
521 if (pData->fUseHostResolver)
522 {
523#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
524 while (!LIST_EMPTY(&pData->DNSMapHead))
525 {
526 PDNSMAPPINGENTRY pDnsEntry = LIST_FIRST(&pData->DNSMapHead);
527 LIST_REMOVE(pDnsEntry, MapList);
528 RTStrFree(pDnsEntry->pszCName);
529 RTMemFree(pDnsEntry);
530 }
531#endif
532 }
533 while (!LIST_EMPTY(&instancehead))
534 {
535 struct libalias *la = LIST_FIRST(&instancehead);
536 /* libalias do all clean up */
537 LibAliasUninit(la);
538 }
539 while (!LIST_EMPTY(&pData->arp_cache))
540 {
541 struct arp_cache_entry *ac = LIST_FIRST(&pData->arp_cache);
542 LIST_REMOVE(ac, list);
543 RTMemFree(ac);
544 }
545 slirpTftpTerm(pData);
546 bootp_dhcp_fini(pData);
547 m_fini(pData);
548#ifdef RT_OS_WINDOWS
549 WSACleanup();
550#endif
551#ifdef LOG_ENABLED
552 Log(("\n"
553 "NAT statistics\n"
554 "--------------\n"
555 "\n"));
556 ipstats(pData);
557 tcpstats(pData);
558 udpstats(pData);
559 icmpstats(pData);
560 mbufstats(pData);
561 sockstats(pData);
562 Log(("\n"
563 "\n"
564 "\n"));
565#endif
566 RTCritSectRwDelete(&pData->CsRwHandlerChain);
567 RTMemFree(pData);
568}
569
570
571#define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
572#define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
573
574/*
575 * curtime kept to an accuracy of 1ms
576 */
577static void updtime(PNATState pData)
578{
579#ifdef RT_OS_WINDOWS
580 struct _timeb tb;
581
582 _ftime(&tb);
583 curtime = (u_int)tb.time * (u_int)1000;
584 curtime += (u_int)tb.millitm;
585#else
586 gettimeofday(&tt, 0);
587
588 curtime = (u_int)tt.tv_sec * (u_int)1000;
589 curtime += (u_int)tt.tv_usec / (u_int)1000;
590
591 if ((tt.tv_usec % 1000) >= 500)
592 curtime++;
593#endif
594}
595
596#ifdef RT_OS_WINDOWS
597void slirp_select_fill(PNATState pData, int *pnfds)
598#else /* RT_OS_WINDOWS */
599void slirp_select_fill(PNATState pData, int *pnfds, struct pollfd *polls)
600#endif /* !RT_OS_WINDOWS */
601{
602 struct socket *so, *so_next;
603 int nfds;
604#if defined(RT_OS_WINDOWS)
605 int rc;
606 int error;
607#else
608 int poll_index = 0;
609#endif
610 int i;
611
612 STAM_PROFILE_START(&pData->StatFill, a);
613
614 nfds = *pnfds;
615
616 /*
617 * First, TCP sockets
618 */
619 do_slowtimo = 0;
620 if (!link_up)
621 goto done;
622
623 /*
624 * *_slowtimo needs calling if there are IP fragments
625 * in the fragment queue, or there are TCP connections active
626 */
627 /* XXX:
628 * triggering of fragment expiration should be the same but use new macroses
629 */
630 do_slowtimo = (tcb.so_next != &tcb);
631 if (!do_slowtimo)
632 {
633 for (i = 0; i < IPREASS_NHASH; i++)
634 {
635 if (!TAILQ_EMPTY(&ipq[i]))
636 {
637 do_slowtimo = 1;
638 break;
639 }
640 }
641 }
642 /* always add the ICMP socket */
643#ifndef RT_OS_WINDOWS
644 pData->icmp_socket.so_poll_index = -1;
645#endif
646 ICMP_ENGAGE_EVENT(&pData->icmp_socket, readfds);
647
648 STAM_COUNTER_RESET(&pData->StatTCP);
649 STAM_COUNTER_RESET(&pData->StatTCPHot);
650
651 QSOCKET_FOREACH(so, so_next, tcp)
652 /* { */
653 Assert(so->so_type == IPPROTO_TCP);
654#if !defined(RT_OS_WINDOWS)
655 so->so_poll_index = -1;
656#endif
657 STAM_COUNTER_INC(&pData->StatTCP);
658#ifdef VBOX_WITH_NAT_UDP_SOCKET_CLONE
659 /* TCP socket can't be cloned */
660 Assert((!so->so_cloneOf));
661#endif
662 /*
663 * See if we need a tcp_fasttimo
664 */
665 if ( time_fasttimo == 0
666 && so->so_tcpcb != NULL
667 && so->so_tcpcb->t_flags & TF_DELACK)
668 {
669 time_fasttimo = curtime; /* Flag when we want a fasttimo */
670 }
671
672 /*
673 * NOFDREF can include still connecting to local-host,
674 * newly socreated() sockets etc. Don't want to select these.
675 */
676 if (so->so_state & SS_NOFDREF || so->s == -1)
677 CONTINUE(tcp);
678
679 /*
680 * Set for reading sockets which are accepting
681 */
682 if (so->so_state & SS_FACCEPTCONN)
683 {
684 STAM_COUNTER_INC(&pData->StatTCPHot);
685 TCP_ENGAGE_EVENT1(so, readfds);
686 CONTINUE(tcp);
687 }
688
689 /*
690 * Set for writing sockets which are connecting
691 */
692 if (so->so_state & SS_ISFCONNECTING)
693 {
694 Log2(("connecting %R[natsock] engaged\n",so));
695 STAM_COUNTER_INC(&pData->StatTCPHot);
696#ifdef RT_OS_WINDOWS
697 WIN_TCP_ENGAGE_EVENT2(so, writefds, connectfds);
698#else
699 TCP_ENGAGE_EVENT1(so, writefds);
700#endif
701 }
702
703 /*
704 * Set for writing if we are connected, can send more, and
705 * we have something to send
706 */
707 if (CONN_CANFSEND(so) && SBUF_LEN(&so->so_rcv))
708 {
709 STAM_COUNTER_INC(&pData->StatTCPHot);
710 TCP_ENGAGE_EVENT1(so, writefds);
711 }
712
713 /*
714 * Set for reading (and urgent data) if we are connected, can
715 * receive more, and we have room for it XXX /2 ?
716 */
717 /* @todo: vvl - check which predicat here will be more useful here in rerm of new sbufs. */
718 if ( CONN_CANFRCV(so)
719 && (SBUF_LEN(&so->so_snd) < (SBUF_SIZE(&so->so_snd)/2))
720#ifdef RT_OS_WINDOWS
721 && !(so->so_state & SS_ISFCONNECTING)
722#endif
723 )
724 {
725 STAM_COUNTER_INC(&pData->StatTCPHot);
726 TCP_ENGAGE_EVENT2(so, readfds, xfds);
727 }
728 LOOP_LABEL(tcp, so, so_next);
729 }
730
731 /*
732 * UDP sockets
733 */
734 STAM_COUNTER_RESET(&pData->StatUDP);
735 STAM_COUNTER_RESET(&pData->StatUDPHot);
736
737 QSOCKET_FOREACH(so, so_next, udp)
738 /* { */
739
740 Assert(so->so_type == IPPROTO_UDP);
741 STAM_COUNTER_INC(&pData->StatUDP);
742#if !defined(RT_OS_WINDOWS)
743 so->so_poll_index = -1;
744#endif
745
746 /*
747 * See if it's timed out
748 */
749 if (so->so_expire)
750 {
751 if (so->so_expire <= curtime)
752 {
753 Log2(("NAT: %R[natsock] expired\n", so));
754 if (so->so_timeout != NULL)
755 {
756 /* so_timeout - might change the so_expire value or
757 * drop so_timeout* from so.
758 */
759 so->so_timeout(pData, so, so->so_timeout_arg);
760 /* on 4.2 so->
761 */
762 if ( so_next->so_prev != so /* so_timeout freed the socket */
763 || so->so_timeout) /* so_timeout just freed so_timeout */
764 CONTINUE_NO_UNLOCK(udp);
765 }
766 UDP_DETACH(pData, so, so_next);
767 CONTINUE_NO_UNLOCK(udp);
768 }
769 }
770#ifdef VBOX_WITH_NAT_UDP_SOCKET_CLONE
771 if (so->so_cloneOf)
772 CONTINUE_NO_UNLOCK(udp);
773#endif
774
775 /*
776 * When UDP packets are received from over the link, they're
777 * sendto()'d straight away, so no need for setting for writing
778 * Limit the number of packets queued by this session to 4.
779 * Note that even though we try and limit this to 4 packets,
780 * the session could have more queued if the packets needed
781 * to be fragmented.
782 *
783 * (XXX <= 4 ?)
784 */
785 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4)
786 {
787 STAM_COUNTER_INC(&pData->StatUDPHot);
788 UDP_ENGAGE_EVENT(so, readfds);
789 }
790 LOOP_LABEL(udp, so, so_next);
791 }
792done:
793
794#if defined(RT_OS_WINDOWS)
795 *pnfds = VBOX_EVENT_COUNT;
796#else /* RT_OS_WINDOWS */
797 AssertRelease(poll_index <= *pnfds);
798 *pnfds = poll_index;
799#endif /* !RT_OS_WINDOWS */
800
801 STAM_PROFILE_STOP(&pData->StatFill, a);
802}
803
804
805/**
806 * This function do Connection or sending tcp sequence to.
807 * @returns if true operation completed
808 * @note: functions call tcp_input that potentially could lead to tcp_drop
809 */
810static bool slirpConnectOrWrite(PNATState pData, struct socket *so, bool fConnectOnly)
811{
812 int ret;
813 LogFlowFunc(("ENTER: so:%R[natsock], fConnectOnly:%RTbool\n", so, fConnectOnly));
814 /*
815 * Check for non-blocking, still-connecting sockets
816 */
817 if (so->so_state & SS_ISFCONNECTING)
818 {
819 Log2(("connecting %R[natsock] catched\n", so));
820 /* Connected */
821 so->so_state &= ~SS_ISFCONNECTING;
822
823 /*
824 * This should be probably guarded by PROBE_CONN too. Anyway,
825 * we disable it on OS/2 because the below send call returns
826 * EFAULT which causes the opened TCP socket to close right
827 * after it has been opened and connected.
828 */
829#ifndef RT_OS_OS2
830 ret = send(so->s, (const char *)&ret, 0, 0);
831 if (ret < 0)
832 {
833 /* XXXXX Must fix, zero bytes is a NOP */
834 if ( soIgnorableErrorCode(errno)
835 || errno == ENOTCONN)
836 {
837 LogFlowFunc(("LEAVE: false\n"));
838 return false;
839 }
840
841 /* else failed */
842 so->so_state = SS_NOFDREF;
843 }
844 /* else so->so_state &= ~SS_ISFCONNECTING; */
845#endif
846
847 /*
848 * Continue tcp_input
849 */
850 TCP_INPUT(pData, (struct mbuf *)NULL, sizeof(struct ip), so);
851 /* continue; */
852 }
853 else if (!fConnectOnly)
854 {
855 SOWRITE(ret, pData, so);
856 if (RT_LIKELY(ret > 0))
857 {
858 /*
859 * Make sure we will send window update to peer. This is
860 * a moral equivalent of calling tcp_output() for PRU_RCVD
861 * in tcp_usrreq() of the real stack.
862 */
863 struct tcpcb *tp = sototcpcb(so);
864 if (RT_LIKELY(tp != NULL))
865 tp->t_flags |= TF_DELACK;
866 }
867 }
868
869 LogFlowFunc(("LEAVE: true\n"));
870 return true;
871}
872
873#if defined(RT_OS_WINDOWS)
874void slirp_select_poll(PNATState pData, int fTimeout)
875#else /* RT_OS_WINDOWS */
876void slirp_select_poll(PNATState pData, struct pollfd *polls, int ndfs)
877#endif /* !RT_OS_WINDOWS */
878{
879 struct socket *so, *so_next;
880 int ret;
881#if defined(RT_OS_WINDOWS)
882 WSANETWORKEVENTS NetworkEvents;
883 int rc;
884 int error;
885#endif
886
887 STAM_PROFILE_START(&pData->StatPoll, a);
888
889 /* Update time */
890 updtime(pData);
891
892 /*
893 * See if anything has timed out
894 */
895 if (link_up)
896 {
897 if (time_fasttimo && ((curtime - time_fasttimo) >= 2))
898 {
899 STAM_PROFILE_START(&pData->StatFastTimer, b);
900 tcp_fasttimo(pData);
901 time_fasttimo = 0;
902 STAM_PROFILE_STOP(&pData->StatFastTimer, b);
903 }
904 if (do_slowtimo && ((curtime - last_slowtimo) >= 499))
905 {
906 STAM_PROFILE_START(&pData->StatSlowTimer, c);
907 ip_slowtimo(pData);
908 tcp_slowtimo(pData);
909 last_slowtimo = curtime;
910 STAM_PROFILE_STOP(&pData->StatSlowTimer, c);
911 }
912 }
913#if defined(RT_OS_WINDOWS)
914 if (fTimeout)
915 return; /* only timer update */
916#endif
917
918 /*
919 * Check sockets
920 */
921 if (!link_up)
922 goto done;
923#if defined(RT_OS_WINDOWS)
924 icmpwin_process(pData);
925#else
926 if ( (pData->icmp_socket.s != -1)
927 && CHECK_FD_SET(&pData->icmp_socket, ignored, readfds))
928 sorecvfrom(pData, &pData->icmp_socket);
929#endif
930 /*
931 * Check TCP sockets
932 */
933 QSOCKET_FOREACH(so, so_next, tcp)
934 /* { */
935 /* TCP socket can't be cloned */
936#ifdef VBOX_WITH_NAT_UDP_SOCKET_CLONE
937 Assert((!so->so_cloneOf));
938#endif
939 Assert(!so->fUnderPolling);
940 so->fUnderPolling = 1;
941 if (slirpVerifyAndFreeSocket(pData, so))
942 CONTINUE(tcp);
943 /*
944 * FD_ISSET is meaningless on these sockets
945 * (and they can crash the program)
946 */
947 if (so->so_state & SS_NOFDREF || so->s == -1)
948 {
949 so->fUnderPolling = 0;
950 CONTINUE(tcp);
951 }
952
953 POLL_TCP_EVENTS(rc, error, so, &NetworkEvents);
954
955 LOG_NAT_SOCK(so, TCP, &NetworkEvents, readfds, writefds, xfds);
956
957 if (so->so_state & SS_ISFCONNECTING)
958 {
959 int sockerr = 0;
960#if !defined(RT_OS_WINDOWS)
961 {
962 int revents = 0;
963
964 /*
965 * Failed connect(2) is reported by poll(2) on
966 * different OSes with different combinations of
967 * POLLERR, POLLHUP, and POLLOUT.
968 */
969 if ( CHECK_FD_SET(so, NetworkEvents, closefds) /* POLLHUP */
970 || CHECK_FD_SET(so, NetworkEvents, rderr)) /* POLLERR */
971 {
972 revents = POLLHUP; /* squash to single "failed" flag */
973 }
974#if defined(RT_OS_SOLARIS) || defined(RT_OS_NETBSD)
975 /* Solaris and NetBSD report plain POLLOUT even on error */
976 else if (CHECK_FD_SET(so, NetworkEvents, writefds)) /* POLLOUT */
977 {
978 revents = POLLOUT;
979 }
980#endif
981
982 if (revents != 0)
983 {
984 socklen_t optlen = (socklen_t)sizeof(sockerr);
985 ret = getsockopt(so->s, SOL_SOCKET, SO_ERROR, &sockerr, &optlen);
986
987 if ( RT_UNLIKELY(ret < 0)
988 || ( (revents & POLLHUP)
989 && RT_UNLIKELY(sockerr == 0)))
990 sockerr = ETIMEDOUT;
991 }
992 }
993#else /* RT_OS_WINDOWS */
994 {
995 if (NetworkEvents.lNetworkEvents & FD_CONNECT)
996 sockerr = NetworkEvents.iErrorCode[FD_CONNECT_BIT];
997 }
998#endif
999 if (sockerr != 0)
1000 {
1001 tcp_fconnect_failed(pData, so, sockerr);
1002 ret = slirpVerifyAndFreeSocket(pData, so);
1003 Assert(ret == 1); /* freed */
1004 CONTINUE(tcp);
1005 }
1006
1007 /*
1008 * XXX: For now just fall through to the old code to
1009 * handle successful connect(2).
1010 */
1011 }
1012
1013 /*
1014 * Check for URG data
1015 * This will soread as well, so no need to
1016 * test for readfds below if this succeeds
1017 */
1018
1019 /* out-of-band data */
1020 if ( CHECK_FD_SET(so, NetworkEvents, xfds)
1021#ifdef RT_OS_DARWIN
1022 /* Darwin and probably BSD hosts generates POLLPRI|POLLHUP event on receiving TCP.flags.{ACK|URG|FIN} this
1023 * combination on other Unixs hosts doesn't enter to this branch
1024 */
1025 && !CHECK_FD_SET(so, NetworkEvents, closefds)
1026#endif
1027#ifdef RT_OS_WINDOWS
1028 /**
1029 * In some cases FD_CLOSE comes with FD_OOB, that confuse tcp processing.
1030 */
1031 && !WIN_CHECK_FD_SET(so, NetworkEvents, closefds)
1032#endif
1033 )
1034 {
1035 sorecvoob(pData, so);
1036 if (slirpVerifyAndFreeSocket(pData, so))
1037 CONTINUE(tcp);
1038 }
1039
1040 /*
1041 * Check sockets for reading
1042 */
1043 else if ( CHECK_FD_SET(so, NetworkEvents, readfds)
1044 || WIN_CHECK_FD_SET(so, NetworkEvents, acceptds))
1045 {
1046
1047#ifdef RT_OS_WINDOWS
1048 if (WIN_CHECK_FD_SET(so, NetworkEvents, connectfds))
1049 {
1050 /* Finish connection first */
1051 /* should we ignore return value? */
1052 bool fRet = slirpConnectOrWrite(pData, so, true);
1053 LogFunc(("fRet:%RTbool\n", fRet));
1054 if (slirpVerifyAndFreeSocket(pData, so))
1055 CONTINUE(tcp);
1056 }
1057#endif
1058 /*
1059 * Check for incoming connections
1060 */
1061 if (so->so_state & SS_FACCEPTCONN)
1062 {
1063 TCP_CONNECT(pData, so);
1064 if (slirpVerifyAndFreeSocket(pData, so))
1065 CONTINUE(tcp);
1066 if (!CHECK_FD_SET(so, NetworkEvents, closefds))
1067 {
1068 so->fUnderPolling = 0;
1069 CONTINUE(tcp);
1070 }
1071 }
1072
1073 ret = soread(pData, so);
1074 if (slirpVerifyAndFreeSocket(pData, so))
1075 CONTINUE(tcp);
1076 /* Output it if we read something */
1077 if (RT_LIKELY(ret > 0))
1078 TCP_OUTPUT(pData, sototcpcb(so));
1079
1080 if (slirpVerifyAndFreeSocket(pData, so))
1081 CONTINUE(tcp);
1082 }
1083
1084 /*
1085 * Check for FD_CLOSE events.
1086 * in some cases once FD_CLOSE engaged on socket it could be flashed latter (for some reasons)
1087 */
1088 if ( CHECK_FD_SET(so, NetworkEvents, closefds)
1089 || (so->so_close == 1))
1090 {
1091 /*
1092 * drain the socket
1093 */
1094 for (; so_next->so_prev == so
1095 && !slirpVerifyAndFreeSocket(pData, so);)
1096 {
1097 ret = soread(pData, so);
1098 if (slirpVerifyAndFreeSocket(pData, so))
1099 break;
1100
1101 if (ret > 0)
1102 TCP_OUTPUT(pData, sototcpcb(so));
1103 else if (so_next->so_prev == so)
1104 {
1105 Log2(("%R[natsock] errno %d (%s)\n", so, errno, strerror(errno)));
1106 break;
1107 }
1108 }
1109
1110 /* if socket freed ''so'' is PHANTOM and next socket isn't points on it */
1111 if (so_next->so_prev == so)
1112 {
1113 /* mark the socket for termination _after_ it was drained */
1114 so->so_close = 1;
1115 /* No idea about Windows but on Posix, POLLHUP means that we can't send more.
1116 * Actually in the specific error scenario, POLLERR is set as well. */
1117#ifndef RT_OS_WINDOWS
1118 if (CHECK_FD_SET(so, NetworkEvents, rderr))
1119 sofcantsendmore(so);
1120#endif
1121 }
1122 if (so_next->so_prev == so)
1123 so->fUnderPolling = 0;
1124 CONTINUE(tcp);
1125 }
1126
1127 /*
1128 * Check sockets for writing
1129 */
1130 if ( CHECK_FD_SET(so, NetworkEvents, writefds)
1131#ifdef RT_OS_WINDOWS
1132 || WIN_CHECK_FD_SET(so, NetworkEvents, connectfds)
1133#endif
1134 )
1135 {
1136 int fConnectOrWriteSuccess = slirpConnectOrWrite(pData, so, false);
1137 /* slirpConnectOrWrite could return true even if tcp_input called tcp_drop,
1138 * so we should be ready to such situations.
1139 */
1140 if (slirpVerifyAndFreeSocket(pData, so))
1141 CONTINUE(tcp);
1142 else if (!fConnectOrWriteSuccess)
1143 {
1144 so->fUnderPolling = 0;
1145 CONTINUE(tcp);
1146 }
1147 /* slirpConnectionOrWrite succeeded and socket wasn't dropped */
1148 }
1149
1150 /*
1151 * Probe a still-connecting, non-blocking socket
1152 * to check if it's still alive
1153 */
1154#ifdef PROBE_CONN
1155 if (so->so_state & SS_ISFCONNECTING)
1156 {
1157 ret = recv(so->s, (char *)&ret, 0, 0);
1158
1159 if (ret < 0)
1160 {
1161 /* XXX */
1162 if ( soIgnorableErrorCode(errno)
1163 || errno == ENOTCONN)
1164 {
1165 CONTINUE(tcp); /* Still connecting, continue */
1166 }
1167
1168 /* else failed */
1169 so->so_state = SS_NOFDREF;
1170
1171 /* tcp_input will take care of it */
1172 }
1173 else
1174 {
1175 ret = send(so->s, &ret, 0, 0);
1176 if (ret < 0)
1177 {
1178 /* XXX */
1179 if ( soIgnorableErrorCode(errno)
1180 || errno == ENOTCONN)
1181 {
1182 CONTINUE(tcp);
1183 }
1184 /* else failed */
1185 so->so_state = SS_NOFDREF;
1186 }
1187 else
1188 so->so_state &= ~SS_ISFCONNECTING;
1189
1190 }
1191 TCP_INPUT((struct mbuf *)NULL, sizeof(struct ip),so);
1192 } /* SS_ISFCONNECTING */
1193#endif
1194 if (!slirpVerifyAndFreeSocket(pData, so))
1195 so->fUnderPolling = 0;
1196 LOOP_LABEL(tcp, so, so_next);
1197 }
1198
1199 /*
1200 * Now UDP sockets.
1201 * Incoming packets are sent straight away, they're not buffered.
1202 * Incoming UDP data isn't buffered either.
1203 */
1204 QSOCKET_FOREACH(so, so_next, udp)
1205 /* { */
1206#ifdef VBOX_WITH_NAT_UDP_SOCKET_CLONE
1207 if (so->so_cloneOf)
1208 CONTINUE_NO_UNLOCK(udp);
1209#endif
1210#if 0
1211 so->fUnderPolling = 1;
1212 if(slirpVerifyAndFreeSocket(pData, so));
1213 CONTINUE(udp);
1214 so->fUnderPolling = 0;
1215#endif
1216
1217 POLL_UDP_EVENTS(rc, error, so, &NetworkEvents);
1218
1219 LOG_NAT_SOCK(so, UDP, &NetworkEvents, readfds, writefds, xfds);
1220
1221 if (so->s != -1 && CHECK_FD_SET(so, NetworkEvents, readfds))
1222 {
1223 SORECVFROM(pData, so);
1224 }
1225 LOOP_LABEL(udp, so, so_next);
1226 }
1227
1228done:
1229
1230 STAM_PROFILE_STOP(&pData->StatPoll, a);
1231}
1232
1233
1234struct arphdr
1235{
1236 unsigned short ar_hrd; /* format of hardware address */
1237 unsigned short ar_pro; /* format of protocol address */
1238 unsigned char ar_hln; /* length of hardware address */
1239 unsigned char ar_pln; /* length of protocol address */
1240 unsigned short ar_op; /* ARP opcode (command) */
1241
1242 /*
1243 * Ethernet looks like this : This bit is variable sized however...
1244 */
1245 unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */
1246 unsigned char ar_sip[4]; /* sender IP address */
1247 unsigned char ar_tha[ETH_ALEN]; /* target hardware address */
1248 unsigned char ar_tip[4]; /* target IP address */
1249};
1250AssertCompileSize(struct arphdr, 28);
1251
1252static void arp_output(PNATState pData, const uint8_t *pcu8EtherSource, const struct arphdr *pcARPHeaderSource, uint32_t ip4TargetAddress)
1253{
1254 struct ethhdr *pEtherHeaderResponse;
1255 struct arphdr *pARPHeaderResponse;
1256 uint32_t ip4TargetAddressInHostFormat;
1257 struct mbuf *pMbufResponse;
1258
1259 Assert((pcu8EtherSource));
1260 if (!pcu8EtherSource)
1261 return;
1262 ip4TargetAddressInHostFormat = RT_N2H_U32(ip4TargetAddress);
1263
1264 pMbufResponse = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
1265 if (!pMbufResponse)
1266 return;
1267 pEtherHeaderResponse = mtod(pMbufResponse, struct ethhdr *);
1268 /* @note: if_encap will swap src and dst*/
1269 memcpy(pEtherHeaderResponse->h_source, pcu8EtherSource, ETH_ALEN);
1270 pMbufResponse->m_data += ETH_HLEN;
1271 pARPHeaderResponse = mtod(pMbufResponse, struct arphdr *);
1272 pMbufResponse->m_len = sizeof(struct arphdr);
1273
1274 pARPHeaderResponse->ar_hrd = RT_H2N_U16_C(1);
1275 pARPHeaderResponse->ar_pro = RT_H2N_U16_C(ETH_P_IP);
1276 pARPHeaderResponse->ar_hln = ETH_ALEN;
1277 pARPHeaderResponse->ar_pln = 4;
1278 pARPHeaderResponse->ar_op = RT_H2N_U16_C(ARPOP_REPLY);
1279 memcpy(pARPHeaderResponse->ar_sha, special_ethaddr, ETH_ALEN);
1280
1281 if (!slirpMbufTagService(pData, pMbufResponse, (uint8_t)(ip4TargetAddressInHostFormat & ~pData->netmask)))
1282 {
1283 static bool fTagErrorReported;
1284 if (!fTagErrorReported)
1285 {
1286 LogRel(("NAT: Couldn't add the tag(PACKET_SERVICE:%d)\n",
1287 (uint8_t)(ip4TargetAddressInHostFormat & ~pData->netmask)));
1288 fTagErrorReported = true;
1289 }
1290 }
1291 pARPHeaderResponse->ar_sha[5] = (uint8_t)(ip4TargetAddressInHostFormat & ~pData->netmask);
1292
1293 memcpy(pARPHeaderResponse->ar_sip, pcARPHeaderSource->ar_tip, 4);
1294 memcpy(pARPHeaderResponse->ar_tha, pcARPHeaderSource->ar_sha, ETH_ALEN);
1295 memcpy(pARPHeaderResponse->ar_tip, pcARPHeaderSource->ar_sip, 4);
1296 if_encap(pData, ETH_P_ARP, pMbufResponse, ETH_ENCAP_URG);
1297}
1298
1299/**
1300 * @note This function will free m!
1301 */
1302static void arp_input(PNATState pData, struct mbuf *m)
1303{
1304 struct ethhdr *pEtherHeader;
1305 struct arphdr *pARPHeader;
1306 uint32_t ip4TargetAddress;
1307
1308 int ar_op;
1309 pEtherHeader = mtod(m, struct ethhdr *);
1310 pARPHeader = (struct arphdr *)&pEtherHeader[1];
1311
1312 ar_op = RT_N2H_U16(pARPHeader->ar_op);
1313 ip4TargetAddress = *(uint32_t*)pARPHeader->ar_tip;
1314
1315 switch (ar_op)
1316 {
1317 case ARPOP_REQUEST:
1318 if ( CTL_CHECK(ip4TargetAddress, CTL_DNS)
1319 || CTL_CHECK(ip4TargetAddress, CTL_ALIAS)
1320 || CTL_CHECK(ip4TargetAddress, CTL_TFTP))
1321 {
1322 slirp_update_guest_addr_guess(pData, *(uint32_t *)pARPHeader->ar_sip, "arp request");
1323 arp_output(pData, pEtherHeader->h_source, pARPHeader, ip4TargetAddress);
1324 break;
1325 }
1326
1327 /* Gratuitous ARP */
1328 if ( *(uint32_t *)pARPHeader->ar_sip == *(uint32_t *)pARPHeader->ar_tip
1329 && ( memcmp(pARPHeader->ar_tha, zerro_ethaddr, ETH_ALEN) == 0
1330 || memcmp(pARPHeader->ar_tha, broadcast_ethaddr, ETH_ALEN) == 0)
1331 && memcmp(pEtherHeader->h_dest, broadcast_ethaddr, ETH_ALEN) == 0)
1332 {
1333 LogRel2(("NAT: Gratuitous ARP from %RTnaipv4 at %RTmac\n",
1334 *(uint32_t *)pARPHeader->ar_sip, pARPHeader->ar_sha));
1335 slirp_update_guest_addr_guess(pData, *(uint32_t *)pARPHeader->ar_sip, "gratuitous arp");
1336 slirp_arp_cache_update_or_add(pData, *(uint32_t *)pARPHeader->ar_sip, &pARPHeader->ar_sha[0]);
1337 }
1338 break;
1339
1340 case ARPOP_REPLY:
1341 slirp_arp_cache_update_or_add(pData, *(uint32_t *)pARPHeader->ar_sip, &pARPHeader->ar_sha[0]);
1342 break;
1343
1344 default:
1345 break;
1346 }
1347
1348 m_freem(pData, m);
1349}
1350
1351/**
1352 * Feed a packet into the slirp engine.
1353 *
1354 * @param m Data buffer, m_len is not valid.
1355 * @param cbBuf The length of the data in m.
1356 */
1357void slirp_input(PNATState pData, struct mbuf *m, size_t cbBuf)
1358{
1359 int proto;
1360 static bool fWarnedIpv6;
1361 struct ethhdr *eh;
1362 uint8_t au8Ether[ETH_ALEN];
1363
1364 m->m_len = cbBuf;
1365 if (cbBuf < ETH_HLEN)
1366 {
1367 Log(("NAT: packet having size %d has been ignored\n", m->m_len));
1368 m_freem(pData, m);
1369 return;
1370 }
1371 eh = mtod(m, struct ethhdr *);
1372 proto = RT_N2H_U16(eh->h_proto);
1373
1374 memcpy(au8Ether, eh->h_source, ETH_ALEN);
1375
1376 switch(proto)
1377 {
1378 case ETH_P_ARP:
1379 arp_input(pData, m);
1380 break;
1381
1382 case ETH_P_IP:
1383 /* Update time. Important if the network is very quiet, as otherwise
1384 * the first outgoing connection gets an incorrect timestamp. */
1385 updtime(pData);
1386 m_adj(m, ETH_HLEN);
1387 M_ASSERTPKTHDR(m);
1388 m->m_pkthdr.header = mtod(m, void *);
1389 ip_input(pData, m);
1390 break;
1391
1392 case ETH_P_IPV6:
1393 m_freem(pData, m);
1394 if (!fWarnedIpv6)
1395 {
1396 LogRel(("NAT: IPv6 not supported\n"));
1397 fWarnedIpv6 = true;
1398 }
1399 break;
1400
1401 default:
1402 Log(("NAT: Unsupported protocol %x\n", proto));
1403 m_freem(pData, m);
1404 break;
1405 }
1406}
1407
1408/**
1409 * Output the IP packet to the ethernet device.
1410 *
1411 * @note This function will free m!
1412 */
1413void if_encap(PNATState pData, uint16_t eth_proto, struct mbuf *m, int flags)
1414{
1415 struct ethhdr *eh;
1416 uint8_t *mbuf = NULL;
1417 size_t mlen = 0;
1418 STAM_PROFILE_START(&pData->StatIF_encap, a);
1419 LogFlowFunc(("ENTER: pData:%p, eth_proto:%RX16, m:%p, flags:%d\n",
1420 pData, eth_proto, m, flags));
1421
1422 M_ASSERTPKTHDR(m);
1423
1424 Assert(M_LEADINGSPACE(m) >= ETH_HLEN);
1425 m->m_data -= ETH_HLEN;
1426 m->m_len += ETH_HLEN;
1427 eh = mtod(m, struct ethhdr *);
1428 mlen = m->m_len;
1429
1430 if (memcmp(eh->h_source, special_ethaddr, ETH_ALEN) != 0)
1431 {
1432 struct m_tag *t = m_tag_first(m);
1433 uint8_t u8ServiceId = CTL_ALIAS;
1434 memcpy(eh->h_dest, eh->h_source, ETH_ALEN);
1435 memcpy(eh->h_source, special_ethaddr, ETH_ALEN);
1436 Assert(memcmp(eh->h_dest, special_ethaddr, ETH_ALEN) != 0);
1437 if (memcmp(eh->h_dest, zerro_ethaddr, ETH_ALEN) == 0)
1438 {
1439 /* don't do anything */
1440 m_freem(pData, m);
1441 goto done;
1442 }
1443 if ( t
1444 && (t = m_tag_find(m, PACKET_SERVICE, NULL)))
1445 {
1446 Assert(t);
1447 u8ServiceId = *(uint8_t *)&t[1];
1448 }
1449 eh->h_source[5] = u8ServiceId;
1450 }
1451 /*
1452 * we're processing the chain, that isn't not expected.
1453 */
1454 Assert((!m->m_next));
1455 if (m->m_next)
1456 {
1457 Log(("NAT: if_encap's recived the chain, dropping...\n"));
1458 m_freem(pData, m);
1459 goto done;
1460 }
1461 mbuf = mtod(m, uint8_t *);
1462 eh->h_proto = RT_H2N_U16(eth_proto);
1463 LogFunc(("eh(dst:%RTmac, src:%RTmac)\n", eh->h_dest, eh->h_source));
1464 if (flags & ETH_ENCAP_URG)
1465 slirp_urg_output(pData->pvUser, m, mbuf, mlen);
1466 else
1467 slirp_output(pData->pvUser, m, mbuf, mlen);
1468done:
1469 STAM_PROFILE_STOP(&pData->StatIF_encap, a);
1470 LogFlowFuncLeave();
1471}
1472
1473
1474void
1475slirp_update_guest_addr_guess(PNATState pData, uint32_t guess, const char *msg)
1476{
1477 Assert(msg != NULL);
1478
1479 if (pData->guest_addr_guess.s_addr == guess)
1480 {
1481 LogRel2(("NAT: Guest address guess %RTnaipv4 re-confirmed by %s\n",
1482 pData->guest_addr_guess.s_addr, msg));
1483 return;
1484 }
1485
1486 if (pData->guest_addr_guess.s_addr == INADDR_ANY)
1487 {
1488 pData->guest_addr_guess.s_addr = guess;
1489 LogRel(("NAT: Guest address guess set to %RTnaipv4 by %s\n",
1490 pData->guest_addr_guess.s_addr, msg));
1491 return;
1492 }
1493 else
1494 {
1495 LogRel(("NAT: Guest address guess changed from %RTnaipv4 to %RTnaipv4 by %s\n",
1496 pData->guest_addr_guess.s_addr, guess, msg));
1497 pData->guest_addr_guess.s_addr = guess;
1498 return;
1499 }
1500}
1501
1502
1503static struct port_forward_rule *
1504slirp_find_redirect(PNATState pData,
1505 int is_udp,
1506 struct in_addr host_addr, int host_port,
1507 struct in_addr guest_addr, int guest_port)
1508{
1509 struct port_forward_rule *rule;
1510 uint16_t proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1511
1512 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
1513 {
1514 if ( rule->proto == proto
1515 && rule->host_port == host_port
1516 && rule->bind_ip.s_addr == host_addr.s_addr
1517 && rule->guest_port == guest_port
1518 && rule->guest_addr.s_addr == guest_addr.s_addr)
1519 {
1520 return rule;
1521 }
1522 }
1523
1524 return NULL;
1525}
1526
1527
1528int slirp_add_redirect(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1529 struct in_addr guest_addr, int guest_port)
1530{
1531 struct port_forward_rule *rule;
1532
1533 rule = slirp_find_redirect(pData, is_udp, host_addr, host_port, guest_addr, guest_port);
1534 if (rule != NULL) /* rule has been already registered */
1535 {
1536 /* XXX: this shouldn't happen */
1537 return 0;
1538 }
1539
1540 rule = RTMemAllocZ(sizeof(struct port_forward_rule));
1541 if (rule == NULL)
1542 return 1;
1543
1544 rule->proto = (is_udp ? IPPROTO_UDP : IPPROTO_TCP);
1545 rule->bind_ip.s_addr = host_addr.s_addr;
1546 rule->host_port = host_port;
1547 rule->guest_addr.s_addr = guest_addr.s_addr;
1548 rule->guest_port = guest_port;
1549
1550 if (rule->proto == IPPROTO_UDP)
1551 rule->so = udp_listen(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port),
1552 rule->guest_addr.s_addr, RT_H2N_U16(rule->guest_port), 0);
1553 else
1554 rule->so = solisten(pData, rule->bind_ip.s_addr, RT_H2N_U16(rule->host_port),
1555 rule->guest_addr.s_addr, RT_H2N_U16(rule->guest_port), 0);
1556
1557 if (rule->so == NULL)
1558 {
1559 LogRel(("NAT: Failed to redirect %s %RTnaipv4:%d -> %RTnaipv4:%d\n",
1560 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
1561 rule->bind_ip.s_addr, rule->host_port,
1562 guest_addr, rule->guest_port));
1563 RTMemFree(rule);
1564 return 1;
1565 }
1566
1567 LogRel(("NAT: Set redirect %s %RTnaipv4:%d -> %RTnaipv4:%d\n",
1568 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
1569 rule->bind_ip.s_addr, rule->host_port,
1570 guest_addr, rule->guest_port));
1571
1572 LIST_INSERT_HEAD(&pData->port_forward_rule_head, rule, list);
1573 return 0;
1574}
1575
1576
1577int slirp_remove_redirect(PNATState pData, int is_udp, struct in_addr host_addr, int host_port,
1578 struct in_addr guest_addr, int guest_port)
1579{
1580 struct port_forward_rule *rule;
1581
1582 rule = slirp_find_redirect(pData, is_udp, host_addr, host_port, guest_addr, guest_port);
1583 if (rule == NULL)
1584 {
1585 LogRel(("NAT: Unable to find redirect %s %RTnaipv4:%d -> %RTnaipv4:%d\n",
1586 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
1587 rule->bind_ip.s_addr, rule->host_port,
1588 guest_addr.s_addr, rule->guest_port));
1589 return 0;
1590 }
1591
1592 LogRel(("NAT: Remove redirect %s %RTnaipv4:%d -> %RTnaipv4:%d\n",
1593 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
1594 rule->bind_ip.s_addr, rule->host_port,
1595 guest_addr.s_addr, rule->guest_port));
1596
1597 if (rule->so != NULL)
1598 {
1599 if (is_udp)
1600 udp_detach(pData, rule->so);
1601 else
1602 tcp_close(pData, sototcpcb(rule->so));
1603 }
1604
1605 LIST_REMOVE(rule, list);
1606 RTMemFree(rule);
1607 return 0;
1608}
1609
1610
1611#if defined(RT_OS_WINDOWS)
1612HANDLE *slirp_get_events(PNATState pData)
1613{
1614 return pData->phEvents;
1615}
1616void slirp_register_external_event(PNATState pData, HANDLE hEvent, int index)
1617{
1618 pData->phEvents[index] = hEvent;
1619}
1620#endif
1621
1622unsigned int slirp_get_timeout_ms(PNATState pData)
1623{
1624 if (link_up)
1625 {
1626 if (time_fasttimo)
1627 return 2;
1628 if (do_slowtimo)
1629 return 500; /* see PR_SLOWHZ */
1630 }
1631 return 3600*1000; /* one hour */
1632}
1633
1634#ifndef RT_OS_WINDOWS
1635int slirp_get_nsock(PNATState pData)
1636{
1637 return pData->nsock;
1638}
1639#endif
1640
1641/*
1642 * this function called from NAT thread
1643 */
1644void slirp_post_sent(PNATState pData, void *pvArg)
1645{
1646 struct mbuf *m = (struct mbuf *)pvArg;
1647 m_freem(pData, m);
1648}
1649
1650void slirp_set_dhcp_TFTP_prefix(PNATState pData, const char *tftpPrefix)
1651{
1652 Log2(("tftp_prefix: %s\n", tftpPrefix));
1653 tftp_prefix = tftpPrefix;
1654}
1655
1656void slirp_set_dhcp_TFTP_bootfile(PNATState pData, const char *bootFile)
1657{
1658 Log2(("bootFile: %s\n", bootFile));
1659 bootp_filename = bootFile;
1660}
1661
1662void slirp_set_dhcp_next_server(PNATState pData, const char *next_server)
1663{
1664 Log2(("next_server: %s\n", next_server));
1665 if (next_server == NULL)
1666 pData->tftp_server.s_addr = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_TFTP);
1667 else
1668 inet_aton(next_server, &pData->tftp_server);
1669}
1670
1671int slirp_set_binding_address(PNATState pData, char *addr)
1672{
1673 if (addr == NULL || (inet_aton(addr, &pData->bindIP) == 0))
1674 {
1675 pData->bindIP.s_addr = INADDR_ANY;
1676 return 1;
1677 }
1678 return 0;
1679}
1680
1681void slirp_set_dhcp_dns_proxy(PNATState pData, bool fDNSProxy)
1682{
1683 if (!pData->fUseHostResolver)
1684 {
1685 Log2(("NAT: DNS proxy switched %s\n", (fDNSProxy ? "on" : "off")));
1686 pData->fUseDnsProxy = fDNSProxy;
1687 }
1688 else if (fDNSProxy)
1689 LogRel(("NAT: Host Resolver conflicts with DNS proxy, the last one was forcely ignored\n"));
1690}
1691
1692#define CHECK_ARG(name, val, lim_min, lim_max) \
1693 do { \
1694 if ((val) < (lim_min) || (val) > (lim_max)) \
1695 { \
1696 LogRel(("NAT: (" #name ":%d) has been ignored, " \
1697 "because out of range (%d, %d)\n", (val), (lim_min), (lim_max))); \
1698 return; \
1699 } \
1700 else \
1701 LogRel(("NAT: (" #name ":%d)\n", (val))); \
1702 } while (0)
1703
1704void slirp_set_somaxconn(PNATState pData, int iSoMaxConn)
1705{
1706 LogFlowFunc(("iSoMaxConn:%d\n", iSoMaxConn));
1707 /* Conditions */
1708 if (iSoMaxConn > SOMAXCONN)
1709 {
1710 LogRel(("NAT: value of somaxconn(%d) bigger than SOMAXCONN(%d)\n", iSoMaxConn, SOMAXCONN));
1711 iSoMaxConn = SOMAXCONN;
1712 }
1713
1714 if (iSoMaxConn < 1)
1715 {
1716 LogRel(("NAT: proposed value(%d) of somaxconn is invalid, default value is used (%d)\n", iSoMaxConn, pData->soMaxConn));
1717 LogFlowFuncLeave();
1718 return;
1719 }
1720
1721 /* Asignment */
1722 if (pData->soMaxConn != iSoMaxConn)
1723 {
1724 LogRel(("NAT: value of somaxconn has been changed from %d to %d\n",
1725 pData->soMaxConn, iSoMaxConn));
1726 pData->soMaxConn = iSoMaxConn;
1727 }
1728 LogFlowFuncLeave();
1729}
1730/* don't allow user set less 8kB and more than 1M values */
1731#define _8K_1M_CHECK_ARG(name, val) CHECK_ARG(name, (val), 8, 1024)
1732void slirp_set_rcvbuf(PNATState pData, int kilobytes)
1733{
1734 _8K_1M_CHECK_ARG("SOCKET_RCVBUF", kilobytes);
1735 pData->socket_rcv = kilobytes;
1736}
1737void slirp_set_sndbuf(PNATState pData, int kilobytes)
1738{
1739 _8K_1M_CHECK_ARG("SOCKET_SNDBUF", kilobytes);
1740 pData->socket_snd = kilobytes * _1K;
1741}
1742void slirp_set_tcp_rcvspace(PNATState pData, int kilobytes)
1743{
1744 _8K_1M_CHECK_ARG("TCP_RCVSPACE", kilobytes);
1745 tcp_rcvspace = kilobytes * _1K;
1746}
1747void slirp_set_tcp_sndspace(PNATState pData, int kilobytes)
1748{
1749 _8K_1M_CHECK_ARG("TCP_SNDSPACE", kilobytes);
1750 tcp_sndspace = kilobytes * _1K;
1751}
1752
1753/*
1754 * Looking for Ether by ip in ARP-cache
1755 * Note: it´s responsible of caller to allocate buffer for result
1756 * @returns iprt status code
1757 */
1758int slirp_arp_lookup_ether_by_ip(PNATState pData, uint32_t ip, uint8_t *ether)
1759{
1760 struct arp_cache_entry *ac;
1761
1762 if (ether == NULL)
1763 return VERR_INVALID_PARAMETER;
1764
1765 if (LIST_EMPTY(&pData->arp_cache))
1766 return VERR_NOT_FOUND;
1767
1768 LIST_FOREACH(ac, &pData->arp_cache, list)
1769 {
1770 if ( ac->ip == ip
1771 && memcmp(ac->ether, broadcast_ethaddr, ETH_ALEN) != 0)
1772 {
1773 memcpy(ether, ac->ether, ETH_ALEN);
1774 return VINF_SUCCESS;
1775 }
1776 }
1777 return VERR_NOT_FOUND;
1778}
1779
1780/*
1781 * Looking for IP by Ether in ARP-cache
1782 * Note: it´s responsible of caller to allocate buffer for result
1783 * @returns 0 - if found, 1 - otherwise
1784 */
1785int slirp_arp_lookup_ip_by_ether(PNATState pData, const uint8_t *ether, uint32_t *ip)
1786{
1787 struct arp_cache_entry *ac;
1788 *ip = INADDR_ANY;
1789
1790 if (LIST_EMPTY(&pData->arp_cache))
1791 return VERR_NOT_FOUND;
1792
1793 LIST_FOREACH(ac, &pData->arp_cache, list)
1794 {
1795 if (memcmp(ether, ac->ether, ETH_ALEN) == 0)
1796 {
1797 *ip = ac->ip;
1798 return VINF_SUCCESS;
1799 }
1800 }
1801 return VERR_NOT_FOUND;
1802}
1803
1804void slirp_arp_who_has(PNATState pData, uint32_t dst)
1805{
1806 struct mbuf *m;
1807 struct ethhdr *ehdr;
1808 struct arphdr *ahdr;
1809 static bool fWarned = false;
1810 LogFlowFunc(("ENTER: %RTnaipv4\n", dst));
1811
1812 /* ARP request WHO HAS 0.0.0.0 is one of the signals
1813 * that something has been broken at Slirp. Investigating
1814 * pcap dumps it's easy to miss warning ARP requests being
1815 * focused on investigation of other protocols flow.
1816 */
1817#ifdef DEBUG_vvl
1818 Assert((dst != INADDR_ANY));
1819 NOREF(fWarned);
1820#else
1821 if ( dst == INADDR_ANY
1822 && !fWarned)
1823 {
1824 LogRel(("NAT: ARP: \"WHO HAS INADDR_ANY\" request has been detected\n"));
1825 fWarned = true;
1826 }
1827#endif /* !DEBUG_vvl */
1828
1829 m = m_getcl(pData, M_NOWAIT, MT_HEADER, M_PKTHDR);
1830 if (m == NULL)
1831 {
1832 Log(("NAT: Can't alloc mbuf for ARP request\n"));
1833 LogFlowFuncLeave();
1834 return;
1835 }
1836 ehdr = mtod(m, struct ethhdr *);
1837 memset(ehdr->h_source, 0xff, ETH_ALEN);
1838 ahdr = (struct arphdr *)&ehdr[1];
1839 ahdr->ar_hrd = RT_H2N_U16_C(1);
1840 ahdr->ar_pro = RT_H2N_U16_C(ETH_P_IP);
1841 ahdr->ar_hln = ETH_ALEN;
1842 ahdr->ar_pln = 4;
1843 ahdr->ar_op = RT_H2N_U16_C(ARPOP_REQUEST);
1844 memcpy(ahdr->ar_sha, special_ethaddr, ETH_ALEN);
1845 /* we assume that this request come from gw, but not from DNS or TFTP */
1846 ahdr->ar_sha[5] = CTL_ALIAS;
1847 *(uint32_t *)ahdr->ar_sip = RT_H2N_U32(RT_N2H_U32(pData->special_addr.s_addr) | CTL_ALIAS);
1848 memset(ahdr->ar_tha, 0xff, ETH_ALEN); /*broadcast*/
1849 *(uint32_t *)ahdr->ar_tip = dst;
1850 /* warn!!! should falls in mbuf minimal size */
1851 m->m_len = sizeof(struct arphdr) + ETH_HLEN;
1852 m->m_data += ETH_HLEN;
1853 m->m_len -= ETH_HLEN;
1854 if_encap(pData, ETH_P_ARP, m, ETH_ENCAP_URG);
1855 LogFlowFuncLeave();
1856}
1857#ifdef VBOX_WITH_DNSMAPPING_IN_HOSTRESOLVER
1858void slirp_add_host_resolver_mapping(PNATState pData, const char *pszHostName, const char *pszHostNamePattern, uint32_t u32HostIP)
1859{
1860 LogFlowFunc(("ENTER: pszHostName:%s, pszHostNamePattern:%s u32HostIP:%RTnaipv4\n",
1861 pszHostName ? pszHostName : "(null)",
1862 pszHostNamePattern ? pszHostNamePattern : "(null)",
1863 u32HostIP));
1864 if ( ( pszHostName
1865 || pszHostNamePattern)
1866 && u32HostIP != INADDR_ANY
1867 && u32HostIP != INADDR_BROADCAST)
1868 {
1869 PDNSMAPPINGENTRY pDnsMapping = RTMemAllocZ(sizeof(DNSMAPPINGENTRY));
1870 if (!pDnsMapping)
1871 {
1872 LogFunc(("Can't allocate DNSMAPPINGENTRY\n"));
1873 LogFlowFuncLeave();
1874 return;
1875 }
1876 pDnsMapping->u32IpAddress = u32HostIP;
1877 if (pszHostName)
1878 pDnsMapping->pszCName = RTStrDup(pszHostName);
1879 else if (pszHostNamePattern)
1880 pDnsMapping->pszPattern = RTStrDup(pszHostNamePattern);
1881 if ( !pDnsMapping->pszCName
1882 && !pDnsMapping->pszPattern)
1883 {
1884 LogFunc(("Can't allocate enough room for %s\n", pszHostName ? pszHostName : pszHostNamePattern));
1885 RTMemFree(pDnsMapping);
1886 LogFlowFuncLeave();
1887 return;
1888 }
1889 LIST_INSERT_HEAD(&pData->DNSMapHead, pDnsMapping, MapList);
1890 LogRel(("NAT: User-defined mapping %s: %RTnaipv4 is registered\n",
1891 pDnsMapping->pszCName ? pDnsMapping->pszCName : pDnsMapping->pszPattern,
1892 pDnsMapping->u32IpAddress));
1893 }
1894 LogFlowFuncLeave();
1895}
1896#endif
1897
1898/* updates the arp cache
1899 * @note: this is helper function, slirp_arp_cache_update_or_add should be used.
1900 * @returns 0 - if has found and updated
1901 * 1 - if hasn't found.
1902 */
1903static inline int slirp_arp_cache_update(PNATState pData, uint32_t dst, const uint8_t *mac)
1904{
1905 struct arp_cache_entry *ac;
1906 Assert(( memcmp(mac, broadcast_ethaddr, ETH_ALEN)
1907 && memcmp(mac, zerro_ethaddr, ETH_ALEN)));
1908 LIST_FOREACH(ac, &pData->arp_cache, list)
1909 {
1910 if (ac->ip == dst)
1911 {
1912 memcpy(ac->ether, mac, ETH_ALEN);
1913 return 0;
1914 }
1915 }
1916 return 1;
1917}
1918
1919/**
1920 * add entry to the arp cache
1921 * @note: this is helper function, slirp_arp_cache_update_or_add should be used.
1922 */
1923static inline void slirp_arp_cache_add(PNATState pData, uint32_t ip, const uint8_t *ether)
1924{
1925 struct arp_cache_entry *ac = NULL;
1926 Assert(( memcmp(ether, broadcast_ethaddr, ETH_ALEN)
1927 && memcmp(ether, zerro_ethaddr, ETH_ALEN)));
1928 ac = RTMemAllocZ(sizeof(struct arp_cache_entry));
1929 if (ac == NULL)
1930 {
1931 Log(("NAT: Can't allocate arp cache entry\n"));
1932 return;
1933 }
1934 ac->ip = ip;
1935 memcpy(ac->ether, ether, ETH_ALEN);
1936 LIST_INSERT_HEAD(&pData->arp_cache, ac, list);
1937}
1938
1939/* updates or adds entry to the arp cache
1940 * @returns 0 - if has found and updated
1941 * 1 - if hasn't found.
1942 */
1943int slirp_arp_cache_update_or_add(PNATState pData, uint32_t dst, const uint8_t *mac)
1944{
1945 if ( !memcmp(mac, broadcast_ethaddr, ETH_ALEN)
1946 || !memcmp(mac, zerro_ethaddr, ETH_ALEN))
1947 {
1948 static bool fBroadcastEtherAddReported;
1949 if (!fBroadcastEtherAddReported)
1950 {
1951 LogRel(("NAT: Attempt to add pair [%RTmac:%RTnaipv4] in ARP cache was ignored\n",
1952 mac, dst));
1953 fBroadcastEtherAddReported = true;
1954 }
1955 return 1;
1956 }
1957 if (slirp_arp_cache_update(pData, dst, mac))
1958 slirp_arp_cache_add(pData, dst, mac);
1959
1960 return 0;
1961}
1962
1963
1964void slirp_set_mtu(PNATState pData, int mtu)
1965{
1966 if (mtu < 20 || mtu >= 16000)
1967 {
1968 LogRel(("NAT: MTU(%d) is out of range (20;16000] mtu forcely assigned to 1500\n", mtu));
1969 mtu = 1500;
1970 }
1971 /* MTU is maximum transition unit on */
1972 if_mtu =
1973 if_mru = mtu;
1974}
1975
1976/**
1977 * Info handler.
1978 */
1979void slirp_info(PNATState pData, const void *pvArg, const char *pszArgs)
1980{
1981 struct socket *so, *so_next;
1982 struct arp_cache_entry *ac;
1983 struct port_forward_rule *rule;
1984 PCDBGFINFOHLP pHlp = (PCDBGFINFOHLP)pvArg;
1985 NOREF(pszArgs);
1986
1987 pHlp->pfnPrintf(pHlp, "NAT parameters: MTU=%d\n", if_mtu);
1988 pHlp->pfnPrintf(pHlp, "NAT TCP ports:\n");
1989 QSOCKET_FOREACH(so, so_next, tcp)
1990 /* { */
1991 pHlp->pfnPrintf(pHlp, " %R[natsock]\n", so);
1992 }
1993
1994 pHlp->pfnPrintf(pHlp, "NAT UDP ports:\n");
1995 QSOCKET_FOREACH(so, so_next, udp)
1996 /* { */
1997 pHlp->pfnPrintf(pHlp, " %R[natsock]\n", so);
1998 }
1999
2000 pHlp->pfnPrintf(pHlp, "NAT ARP cache:\n");
2001 LIST_FOREACH(ac, &pData->arp_cache, list)
2002 {
2003 pHlp->pfnPrintf(pHlp, " %RTnaipv4 %RTmac\n", ac->ip, &ac->ether);
2004 }
2005
2006 pHlp->pfnPrintf(pHlp, "NAT rules:\n");
2007 LIST_FOREACH(rule, &pData->port_forward_rule_head, list)
2008 {
2009 pHlp->pfnPrintf(pHlp, " %s %d => %RTnaipv4:%d %c\n",
2010 rule->proto == IPPROTO_UDP ? "UDP" : "TCP",
2011 rule->host_port, rule->guest_addr.s_addr, rule->guest_port,
2012 rule->activated ? ' ' : '*');
2013 }
2014}
2015
2016/**
2017 * @note: NATState::fUseHostResolver could be changed in bootp.c::dhcp_decode
2018 * @note: this function is executed on GUI/VirtualBox or main/VBoxHeadless thread.
2019 * @note: this function can potentially race with bootp.c::dhcp_decode (except Darwin)
2020 */
2021int slirp_host_network_configuration_change_strategy_selector(const PNATState pData)
2022{
2023 if (pData->fUseHostResolverPermanent)
2024 return VBOX_NAT_DNS_HOSTRESOLVER;
2025
2026 if (pData->fUseDnsProxy) {
2027#if HAVE_NOTIFICATION_FOR_DNS_UPDATE /* XXX */ && !defined(RT_OS_WINDOWS)
2028 /* We dont conflict with bootp.c::dhcp_decode */
2029 struct rcp_state rcp_state;
2030 int rc;
2031
2032 rcp_state.rcps_flags |= RCPSF_IGNORE_IPV6;
2033 rc = rcp_parse(&rcp_state, RESOLV_CONF_FILE);
2034 LogRelFunc(("NAT: rcp_parse:%Rrc old domain:%s new domain:%s\n",
2035 rc, LIST_EMPTY(&pData->pDomainList)
2036 ? "(null)"
2037 : LIST_FIRST(&pData->pDomainList)->dd_pszDomain,
2038 rcp_state.rcps_domain));
2039 if ( RT_FAILURE(rc)
2040 || LIST_EMPTY(&pData->pDomainList))
2041 return VBOX_NAT_DNS_DNSPROXY;
2042
2043 if ( rcp_state.rcps_domain
2044 && strcmp(rcp_state.rcps_domain, LIST_FIRST(&pData->pDomainList)->dd_pszDomain) == 0)
2045 return VBOX_NAT_DNS_DNSPROXY;
2046 else
2047 return VBOX_NAT_DNS_EXTERNAL;
2048#else
2049 /* copy domain name */
2050 /* domain only compare with coy version */
2051 return VBOX_NAT_DNS_DNSPROXY;
2052#endif
2053 }
2054 return VBOX_NAT_DNS_EXTERNAL;
2055}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use