VirtualBox

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

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

Devices: Whitespace and svn:keyword cleanups by scm.

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