VirtualBox

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

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

NAT: Use RW critsect to protect the handler chain list against concurrent access

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