VirtualBox

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

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

NAT: hide TFTP internals.

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