VirtualBox

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

Last change on this file since 50690 was 50690, checked in by vboxsync, 11 years ago

NAT:slirp.c::slirp_init instead rising link_up flag do call slirp_link_up on ending state of initialization.

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