VirtualBox

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

Last change on this file since 46260 was 45323, checked in by vboxsync, 12 years ago

NAT:dnsproxy: handling return from so_timeout callback.
1st condition handle the case when dnsproxy already detached expired socket (not in this version).

2nd condition checks so_timeout if dnsproxy's dropped so_timeout from current socket it could be detached (previously dnsproxy queried next nameserver using new socket).

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