VirtualBox

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

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

NAT: extract DNS functions to slirp_dns.c.

Handle resolv.conf-less Linux distributions.

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