VirtualBox

source: vbox/trunk/src/VBox/NetworkServices/NAT/VBoxNetLwipNAT.cpp@ 48373

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

lwip-nat: fetching local bindings. (disabled).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.7 KB
Line 
1/* $Id: VBoxNetLwipNAT.cpp 48373 2013-09-08 06:24:00Z vboxsync $ */
2/** @file
3 * VBoxNetNAT - NAT Service for connecting to IntNet.
4 */
5
6/*
7 * Copyright (C) 2009 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#include "winutils.h"
19
20#include <VBox/com/com.h>
21#include <VBox/com/listeners.h>
22#include <VBox/com/string.h>
23#include <VBox/com/Guid.h>
24#include <VBox/com/array.h>
25#include <VBox/com/ErrorInfo.h>
26#include <VBox/com/errorprint.h>
27#include <VBox/com/VirtualBox.h>
28
29#include <iprt/net.h>
30#include <iprt/initterm.h>
31#include <iprt/alloca.h>
32#ifndef RT_OS_WINDOWS
33# include <arpa/inet.h>
34#endif
35#include <iprt/err.h>
36#include <iprt/time.h>
37#include <iprt/timer.h>
38#include <iprt/thread.h>
39#include <iprt/stream.h>
40#include <iprt/path.h>
41#include <iprt/param.h>
42#include <iprt/pipe.h>
43#include <iprt/getopt.h>
44#include <iprt/string.h>
45#include <iprt/mem.h>
46#include <iprt/message.h>
47#include <iprt/req.h>
48#include <iprt/file.h>
49#include <iprt/semaphore.h>
50#include <iprt/cpp/utils.h>
51#define LOG_GROUP LOG_GROUP_NAT_SERVICE
52#include <VBox/log.h>
53
54#include <VBox/sup.h>
55#include <VBox/intnet.h>
56#include <VBox/intnetinline.h>
57#include <VBox/vmm/pdmnetinline.h>
58#include <VBox/vmm/vmm.h>
59#include <VBox/version.h>
60
61#ifndef RT_OS_WINDOWS
62# include <sys/poll.h>
63# include <sys/socket.h>
64# include <netinet/in.h>
65#endif
66
67#include <vector>
68#include <string>
69
70#include "../NetLib/VBoxNetLib.h"
71#include "../NetLib/VBoxNetBaseService.h"
72#include "VBoxLwipCore.h"
73
74extern "C"
75{
76/* bunch of LWIP headers */
77#include "lwip/opt.h"
78#ifdef LWIP_SOCKET
79# undef LWIP_SOCKET
80# define LWIP_SOCKET 0
81#endif
82#include "lwip/sys.h"
83#include "lwip/stats.h"
84#include "lwip/mem.h"
85#include "lwip/memp.h"
86#include "lwip/pbuf.h"
87#include "lwip/netif.h"
88#include "lwip/api.h"
89#include "lwip/tcp_impl.h"
90#include "ipv6/lwip/ethip6.h"
91#include "lwip/nd6.h" // for proxy_na_hook
92#include "lwip/mld6.h"
93#include "lwip/udp.h"
94#include "lwip/tcp.h"
95#include "lwip/tcpip.h"
96#include "lwip/sockets.h"
97#include "netif/etharp.h"
98
99#include "proxytest.h"
100#include "pxremap.h"
101#include "portfwd.h"
102}
103
104#include "../NetLib/VBoxPortForwardString.h"
105
106static RTGETOPTDEF g_aGetOptDef[] =
107{
108 { "--port-forward4", 'p', RTGETOPT_REQ_STRING },
109 { "--port-forward6", 'P', RTGETOPT_REQ_STRING }
110};
111
112typedef struct NATSEVICEPORTFORWARDRULE
113{
114 PORTFORWARDRULE Pfr;
115 fwspec FWSpec;
116} NATSEVICEPORTFORWARDRULE, *PNATSEVICEPORTFORWARDRULE;
117
118typedef std::vector<NATSEVICEPORTFORWARDRULE> VECNATSERVICEPF;
119typedef VECNATSERVICEPF::iterator ITERATORNATSERVICEPF;
120typedef VECNATSERVICEPF::const_iterator CITERATORNATSERVICEPF;
121
122struct ip4address2off
123{
124 struct sockaddr_in addr;
125 uint32_t off;
126};
127
128class PortForwardListener;
129
130class VBoxNetLwipNAT: public VBoxNetBaseService
131{
132 friend class PortForwardListener;
133 public:
134 VBoxNetLwipNAT();
135 virtual ~VBoxNetLwipNAT();
136 void usage(){ /* @todo: should be implemented */ };
137 int run();
138 virtual int init(void);
139 /* @todo: when configuration would be really needed */
140 virtual int parseOpt(int rc, const RTGETOPTUNION& getOptVal);
141
142 private:
143 struct proxy_options m_ProxyOptions;
144 struct sockaddr_in m_src4;
145 struct sockaddr_in6 m_src6;
146 /**
147 * place for registered local interfaces.
148 */
149 ip4address2off m_lo2off[10];
150
151 uint16_t m_u16Mtu;
152 netif m_LwipNetIf;
153 /* Queues */
154 RTREQQUEUE hReqIntNet;
155 /* thread where we're waiting for a frames, no semaphores needed */
156 RTTHREAD hThrIntNetRecv;
157
158 /* Our NAT network descriptor in Main */
159 ComPtr<INATNetwork> net;
160 STDMETHOD(HandleEvent)(VBoxEventType_T aEventType, IEvent *pEvent);
161
162 RTSEMEVENT hSemSVC;
163 /* Only for debug needs, by default NAT service should load rules from SVC
164 * on startup, and then on sync them on events.
165 */
166 bool fDontLoadRulesOnStartup;
167 static void onLwipTcpIpInit(void *arg);
168 static void onLwipTcpIpFini(void *arg);
169 static err_t netifInit(netif *pNetif);
170 static err_t netifLinkoutput(netif *pNetif, pbuf *pBuf);
171 static int intNetThreadRecv(RTTHREAD, void *);
172 static void vboxNetLwipNATProcessXmit(void);
173
174 VECNATSERVICEPF m_vecPortForwardRule4;
175 VECNATSERVICEPF m_vecPortForwardRule6;
176
177 static int natServicePfRegister(NATSEVICEPORTFORWARDRULE& natServicePf);
178 static int natServiceProcessRegisteredPf(VECNATSERVICEPF& vecPf);
179};
180
181
182class PortForwardListener
183{
184public:
185 PortForwardListener(){}
186 virtual ~PortForwardListener(){}
187 HRESULT init(VBoxNetLwipNAT *pNAT) { m_pNAT = pNAT; return S_OK; }
188 HRESULT init() { return S_OK; }
189 void uninit(){}
190 STDMETHOD(HandleEvent)(VBoxEventType_T aEventType, IEvent *pEvent)
191 {return m_pNAT->HandleEvent(aEventType, pEvent);};
192private:
193 VBoxNetLwipNAT *m_pNAT;
194};
195
196
197typedef ListenerImpl<PortForwardListener, VBoxNetLwipNAT *> PortForwardListenerImpl;
198
199
200VBOX_LISTENER_DECLARE(PortForwardListenerImpl)
201
202
203
204static VBoxNetLwipNAT *g_pLwipNat;
205
206
207STDMETHODIMP VBoxNetLwipNAT::HandleEvent(VBoxEventType_T aEventType,
208 IEvent *pEvent)
209{
210 HRESULT hrc = S_OK;
211 switch (aEventType)
212 {
213 case VBoxEventType_OnNATNetworkPortForward:
214 {
215 com::Bstr name, strHostAddr, strGuestAddr;
216 LONG lHostPort, lGuestPort;
217 BOOL fCreateFW, fIPv6FW;
218 NATProtocol_T proto = NATProtocol_TCP;
219
220
221 ComPtr<INATNetworkPortForwardEvent> pfEvt = pEvent;
222
223 hrc = pfEvt->COMGETTER(Name)(name.asOutParam());
224 AssertReturn(SUCCEEDED(hrc), hrc);
225
226 hrc = pfEvt->COMGETTER(Proto)(&proto);
227 AssertReturn(SUCCEEDED(hrc), hrc);
228
229 hrc = pfEvt->COMGETTER(HostIp)(strHostAddr.asOutParam());
230 AssertReturn(SUCCEEDED(hrc), hrc);
231
232 hrc = pfEvt->COMGETTER(HostPort)(&lHostPort);
233 AssertReturn(SUCCEEDED(hrc), hrc);
234
235 hrc = pfEvt->COMGETTER(GuestIp)(strGuestAddr.asOutParam());
236 AssertReturn(SUCCEEDED(hrc), hrc);
237
238 hrc = pfEvt->COMGETTER(HostPort)(&lGuestPort);
239 AssertReturn(SUCCEEDED(hrc), hrc);
240
241 hrc = pfEvt->COMGETTER(Create)(&fCreateFW);
242 AssertReturn(SUCCEEDED(hrc), hrc);
243
244 hrc = pfEvt->COMGETTER(Ipv6)(&fIPv6FW);
245 AssertReturn(SUCCEEDED(hrc), hrc);
246
247 VECNATSERVICEPF& rules = (fIPv6FW ?
248 m_vecPortForwardRule6 :
249 m_vecPortForwardRule4);
250
251 NATSEVICEPORTFORWARDRULE r;
252
253 RT_ZERO(r);
254
255 if (name.length() > RT_ELEMENTS(r.Pfr.aszPfrName))
256 {
257 hrc = E_INVALIDARG;
258 goto port_forward_done;
259 }
260
261 switch (proto)
262 {
263 case NATProtocol_TCP:
264 r.Pfr.iPfrProto = IPPROTO_TCP;
265 break;
266 case NATProtocol_UDP:
267 r.Pfr.iPfrProto = IPPROTO_UDP;
268 break;
269 default:
270 goto port_forward_done;
271 }
272
273
274 RTStrPrintf(r.Pfr.aszPfrName, RT_ELEMENTS(r.Pfr.aszPfrName),
275 "%s",
276 com::Utf8Str(name).c_str());
277
278 RTStrPrintf(r.Pfr.aszPfrHostAddr, RT_ELEMENTS(r.Pfr.aszPfrHostAddr),
279 "%s",
280 com::Utf8Str(strHostAddr).c_str());
281
282 /* XXX: limits should be checked */
283 r.Pfr.u16PfrHostPort = (uint16_t)lHostPort;
284
285 RTStrPrintf(r.Pfr.aszPfrHostAddr, RT_ELEMENTS(r.Pfr.aszPfrGuestAddr),
286 "%s",
287 com::Utf8Str(strHostAddr).c_str());
288
289 /* XXX: limits should be checked */
290 r.Pfr.u16PfrGuestPort = (uint16_t)lGuestPort;
291
292 if (fCreateFW) /* Addition */
293 {
294 rules.push_back(r);
295
296 natServicePfRegister(rules.back());
297 }
298 else /* Deletion */
299 {
300 ITERATORNATSERVICEPF it;
301 for (it = rules.begin(); it != rules.end(); ++it)
302 {
303 /* compare */
304 NATSEVICEPORTFORWARDRULE& natFw = *it;
305 if ( natFw.Pfr.iPfrProto == r.Pfr.iPfrProto
306 && natFw.Pfr.u16PfrHostPort == r.Pfr.u16PfrHostPort
307 && (strncmp(natFw.Pfr.aszPfrHostAddr, r.Pfr.aszPfrHostAddr, INET6_ADDRSTRLEN) == 0)
308 && natFw.Pfr.u16PfrGuestPort == r.Pfr.u16PfrGuestPort
309 && (strncmp(natFw.Pfr.aszPfrGuestAddr, r.Pfr.aszPfrGuestAddr, INET6_ADDRSTRLEN) == 0))
310 {
311 fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
312 if (!pFwCopy)
313 {
314 break;
315 }
316 memcpy(pFwCopy, &natFw.FWSpec, sizeof(fwspec));
317
318 /* We shouldn't care about pFwCopy this memory will be freed when
319 * will message will arrive to the destination.
320 */
321 portfwd_rule_del(pFwCopy);
322
323 rules.erase(it);
324 break;
325 }
326 } /* loop over vector elements */
327 } /* condition add or delete */
328 port_forward_done:
329 /* clean up strings */
330 name.setNull();
331 strHostAddr.setNull();
332 strGuestAddr.setNull();
333 break;
334 }
335 }
336 return hrc;
337}
338
339
340void VBoxNetLwipNAT::onLwipTcpIpInit(void* arg)
341{
342 AssertPtrReturnVoid(arg);
343 VBoxNetLwipNAT *pThis = (VBoxNetLwipNAT *)arg;
344
345 HRESULT hrc = com::Initialize();
346 Assert(!FAILED(hrc));
347
348 proxy_arp_hook = pxremap_proxy_arp;
349 proxy_ip4_divert_hook = pxremap_ip4_divert;
350
351 proxy_na_hook = pxremap_proxy_na;
352 proxy_ip6_divert_hook = pxremap_ip6_divert;
353
354 /* lwip thread */
355 RTNETADDRIPV4 IpNetwork;
356 IpNetwork.u = g_pLwipNat->m_Ipv4Address.u & g_pLwipNat->m_Ipv4Netmask.u;
357
358 ip_addr LwipIpAddr, LwipIpNetMask, LwipIpNetwork;
359
360 memcpy(&LwipIpAddr, &g_pLwipNat->m_Ipv4Address, sizeof(ip_addr));
361 memcpy(&LwipIpNetMask, &g_pLwipNat->m_Ipv4Netmask, sizeof(ip_addr));
362 memcpy(&LwipIpNetwork, &IpNetwork, sizeof(ip_addr));
363
364 netif *pNetif = netif_add(&g_pLwipNat->m_LwipNetIf /* Lwip Interface */,
365 &LwipIpAddr /* IP address*/,
366 &LwipIpNetMask /* Network mask */,
367 &LwipIpAddr /* gateway address, @todo: is self IP acceptable? */,
368 g_pLwipNat /* state */,
369 VBoxNetLwipNAT::netifInit /* netif_init_fn */,
370 lwip_tcpip_input /* netif_input_fn */);
371
372 AssertPtrReturnVoid(pNetif);
373
374 netif_set_up(pNetif);
375 netif_set_link_up(pNetif);
376
377 /*
378 * XXX: lwIP currently only ever calls mld6_joingroup() in
379 * nd6_tmr() for fresh tentative addresses, which is a wrong place
380 * to do it - but I'm not keen on fixing this properly for now
381 * (with correct handling of interface up and down transitions,
382 * etc). So stick it here as a kludge.
383 */
384 for (int i = 0; i <= 1; ++i) {
385 ip6_addr_t *paddr = netif_ip6_addr(pNetif, i);
386
387 ip6_addr_t solicited_node_multicast_address;
388 ip6_addr_set_solicitednode(&solicited_node_multicast_address,
389 paddr->addr[3]);
390 mld6_joingroup(paddr, &solicited_node_multicast_address);
391 }
392
393 /*
394 * XXX: We must join the solicited-node multicast for the
395 * addresses we do IPv6 NA-proxy for. We map IPv6 loopback to
396 * proxy address + 1. We only need the low 24 bits, and those are
397 * fixed.
398 */
399 {
400 ip6_addr_t solicited_node_multicast_address;
401
402 ip6_addr_set_solicitednode(&solicited_node_multicast_address,
403 /* last 24 bits of the address */
404 PP_HTONL(0x00000002));
405 mld6_netif_joingroup(pNetif, &solicited_node_multicast_address);
406 }
407
408 proxy_init(&g_pLwipNat->m_LwipNetIf, &g_pLwipNat->m_ProxyOptions);
409
410 natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule4);
411 natServiceProcessRegisteredPf(g_pLwipNat->m_vecPortForwardRule6);
412
413}
414
415
416void VBoxNetLwipNAT::onLwipTcpIpFini(void* arg)
417{
418 AssertPtrReturnVoid(arg);
419 VBoxNetLwipNAT *pThis = (VBoxNetLwipNAT *)arg;
420
421 /* XXX: proxy finalization */
422 netif_set_link_down(&g_pLwipNat->m_LwipNetIf);
423 netif_set_down(&g_pLwipNat->m_LwipNetIf);
424 netif_remove(&g_pLwipNat->m_LwipNetIf);
425
426}
427
428/*
429 * Callback for netif_add() to initialize the interface.
430 */
431err_t VBoxNetLwipNAT::netifInit(netif *pNetif)
432{
433 err_t rcLwip = ERR_OK;
434
435 AssertPtrReturn(pNetif, ERR_ARG);
436
437 VBoxNetLwipNAT *pNat = static_cast<VBoxNetLwipNAT *>(pNetif->state);
438 AssertPtrReturn(pNat, ERR_ARG);
439
440 LogFlowFunc(("ENTER: pNetif[%c%c%d]\n", pNetif->name[0], pNetif->name[1], pNetif->num));
441 /* validity */
442 AssertReturn( pNetif->name[0] == 'N'
443 && pNetif->name[1] == 'T', ERR_ARG);
444
445
446 pNetif->hwaddr_len = sizeof(RTMAC);
447 memcpy(pNetif->hwaddr, &pNat->m_MacAddress, sizeof(RTMAC));
448
449 pNat->m_u16Mtu = 1500; // XXX: FIXME
450 pNetif->mtu = pNat->m_u16Mtu;
451
452 pNetif->flags = NETIF_FLAG_BROADCAST
453 | NETIF_FLAG_ETHARP /* Don't bother driver with ARP and let Lwip resolve ARP handling */
454 | NETIF_FLAG_ETHERNET; /* Lwip works with ethernet too */
455
456 pNetif->linkoutput = netifLinkoutput; /* ether-level-pipe */
457 pNetif->output = lwip_etharp_output; /* ip-pipe */
458 pNetif->output_ip6 = ethip6_output;
459
460 /* IPv6 link-local address in slot 0 */
461 netif_create_ip6_linklocal_address(pNetif, /* :from_mac_48bit */ 1);
462 netif_ip6_addr_set_state(pNetif, 0, IP6_ADDR_PREFERRED); // skip DAD
463
464 /*
465 * RFC 4193 Locally Assigned Global ID (ULA) in slot 1
466 * [fd17:625c:f037:XXXX::1] where XXXX, 16 bit Subnet ID, are two
467 * bytes from the middle of the IPv4 address, e.g. :dead: for
468 * 10.222.173.1
469 */
470 u8_t nethi = ip4_addr2(&pNetif->ip_addr);
471 u8_t netlo = ip4_addr3(&pNetif->ip_addr);
472
473 ip6_addr_t *paddr = netif_ip6_addr(pNetif, 1);
474 IP6_ADDR(paddr, 0, 0xFD, 0x17, 0x62, 0x5C);
475 IP6_ADDR(paddr, 1, 0xF0, 0x37, nethi, netlo);
476 IP6_ADDR(paddr, 2, 0x00, 0x00, 0x00, 0x00);
477 IP6_ADDR(paddr, 3, 0x00, 0x00, 0x00, 0x01);
478 netif_ip6_addr_set_state(pNetif, 1, IP6_ADDR_PREFERRED);
479
480#if LWIP_IPV6_SEND_ROUTER_SOLICIT
481 pNetif->rs_count = 0;
482#endif
483
484 LogFlowFunc(("LEAVE: %d\n", rcLwip));
485 return rcLwip;
486}
487
488
489/**
490 * Intnet-recv thread
491 */
492int VBoxNetLwipNAT::intNetThreadRecv(RTTHREAD, void *)
493{
494 int rc = VINF_SUCCESS;
495
496 /* 1. initialization and connection */
497 HRESULT hrc = com::Initialize();
498 if (FAILED(hrc))
499 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
500
501 /* Well we're ready */
502 PINTNETRINGBUF pRingBuf = &g_pLwipNat->m_pIfBuf->Recv;
503
504 for (;;)
505 {
506 /*
507 * Wait for a packet to become available.
508 */
509 /* 2. waiting for request for */
510 rc = g_pLwipNat->waitForIntNetEvent(2000);
511 if (RT_FAILURE(rc))
512 {
513 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED)
514 {
515 /* do we want interrupt anyone ??? */
516 continue;
517 }
518 LogRel(("VBoxNetNAT: waitForIntNetEvent returned %Rrc\n", rc));
519 AssertRCReturn(rc,ERR_IF);
520 }
521
522 /*
523 * Process the receive buffer.
524 */
525 PCINTNETHDR pHdr;
526
527 while ((pHdr = IntNetRingGetNextFrameToRead(pRingBuf)) != NULL)
528 {
529 uint8_t const u8Type = pHdr->u8Type;
530 size_t cbFrame = pHdr->cbFrame;
531 uint8_t *pu8Frame = NULL;
532 pbuf *pPbufHdr = NULL;
533 pbuf *pPbuf = NULL;
534 switch (u8Type)
535 {
536
537 case INTNETHDR_TYPE_FRAME:
538 /* @todo:should it be really here?
539 * Well well well, we're accessing lwip code here
540 */
541 pPbufHdr = pPbuf = pbuf_alloc(PBUF_RAW, pHdr->cbFrame, PBUF_POOL);
542 if (!pPbuf)
543 {
544 LogRel(("NAT: Can't allocate send buffer cbFrame=%u\n", cbFrame));
545 break;
546 }
547 Assert(pPbufHdr->tot_len == cbFrame);
548 pu8Frame = (uint8_t *)IntNetHdrGetFramePtr(pHdr, g_pLwipNat->m_pIfBuf);
549 while(pPbuf)
550 {
551 memcpy(pPbuf->payload, pu8Frame, pPbuf->len);
552 pu8Frame += pPbuf->len;
553 pPbuf = pPbuf->next;
554 }
555
556 g_pLwipNat->m_LwipNetIf.input(pPbufHdr, &g_pLwipNat->m_LwipNetIf);
557
558 AssertReleaseRC(rc);
559 break;
560 case INTNETHDR_TYPE_GSO:
561 {
562 PCPDMNETWORKGSO pGso = IntNetHdrGetGsoContext(pHdr,
563 g_pLwipNat->m_pIfBuf);
564 if (!PDMNetGsoIsValid(pGso, cbFrame,
565 cbFrame - sizeof(PDMNETWORKGSO)))
566 break;
567 cbFrame -= sizeof(PDMNETWORKGSO);
568 uint8_t abHdrScratch[256];
569 uint32_t const cSegs = PDMNetGsoCalcSegmentCount(pGso,
570 cbFrame);
571 for (size_t iSeg = 0; iSeg < cSegs; iSeg++)
572 {
573 uint32_t cbSegFrame;
574 void *pvSegFrame =
575 PDMNetGsoCarveSegmentQD(pGso,
576 (uint8_t *)(pGso + 1),
577 cbFrame,
578 abHdrScratch,
579 iSeg,
580 cSegs,
581 &cbSegFrame);
582
583 pPbuf = pbuf_alloc(PBUF_RAW, cbSegFrame, PBUF_POOL);
584 if (!pPbuf)
585 {
586 LogRel(("NAT: Can't allocate send buffer cbFrame=%u\n", cbSegFrame));
587 break;
588 }
589 Assert( !pPbuf->next
590 && pPbuf->len == cbSegFrame);
591 memcpy(pPbuf->payload, pvSegFrame, cbSegFrame);
592 g_pLwipNat->m_LwipNetIf.input(pPbuf, &g_pLwipNat->m_LwipNetIf);
593
594 }
595
596 }
597 break;
598 case INTNETHDR_TYPE_PADDING:
599 break;
600 default:
601 STAM_REL_COUNTER_INC(&g_pLwipNat->m_pIfBuf->cStatBadFrames);
602 break;
603 }
604 IntNetRingSkipFrame(&g_pLwipNat->m_pIfBuf->Recv);
605
606 } /* loop */
607 }
608 /* 3. deinitilization and termination */
609 LogFlowFuncLeaveRC(rc);
610 return rc;
611}
612
613
614/**
615 *
616 */
617void VBoxNetLwipNAT::vboxNetLwipNATProcessXmit()
618{
619 int rc = VINF_SUCCESS;
620 INTNETIFSENDREQ SendReq;
621 SendReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
622 SendReq.Hdr.cbReq = sizeof(SendReq);
623 SendReq.pSession = g_pLwipNat->m_pSession;
624 SendReq.hIf = g_pLwipNat->m_hIf;
625 rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_SEND, 0, &SendReq.Hdr);
626 AssertRC(rc);
627}
628
629
630err_t VBoxNetLwipNAT::netifLinkoutput(netif *pNetif, pbuf *pPBuf)
631{
632 int rc = VINF_SUCCESS;
633 err_t rcLwip = ERR_OK;
634 AssertPtrReturn(pNetif, ERR_ARG);
635 AssertPtrReturn(pPBuf, ERR_ARG);
636 AssertReturn((void *)g_pLwipNat == pNetif->state, ERR_ARG);
637 LogFlowFunc(("ENTER: pNetif[%c%c%d], pPbuf:%p\n",
638 pNetif->name[0],
639 pNetif->name[1],
640 pNetif->num,
641 pPBuf));
642
643 /*
644 * We're on the lwip thread ...
645 * try accure Xmit lock (actually we DO accure the lock ... )
646 * 1. we've entered csXmit so we should create frame
647 * 1.a. Frame creation success see 2.
648 * 1.b. (hm ... what about queue processing in place)
649 * 1.c. 2nd attempt create frame
650 * 1.d. Unlock the Xmit
651 * 1.e. goto BUSY.1
652 * 2. Copy pbuf to the frame
653 * 3. Send
654 * 4. leave csXmit & return.
655 *
656 * @todo: perhaps we can use it for optimization,
657 * e.g. drop UDP and reoccure lock on TCP NOTE: now BUSY is unachievable!
658 * Otherwise (BUSY)
659 * 1. Unbuffered (drop)
660 * (buffered)
661 * 1. Copy pbuf to entermediate buffer.
662 * 2. Add call buffer to the queue
663 * 3. return.
664 */
665 /* see p.1 */
666 rc = VINF_SUCCESS;
667 PINTNETHDR pHdr = NULL;
668 uint8_t *pu8Frame = NULL;
669 int offFrame = 0;
670 int idxSg = 0;
671 struct pbuf *pPBufPtr = pPBuf;
672 /* Allocate frame, and pad it if required. */
673 rc = IntNetRingAllocateFrame(&g_pLwipNat->m_pIfBuf->Send, pPBuf->tot_len, &pHdr, (void **)&pu8Frame);
674 if (RT_SUCCESS(rc))
675 {
676 /* see p. 2 */
677 while (pPBufPtr)
678 {
679 memcpy(&pu8Frame[offFrame], pPBufPtr->payload, pPBufPtr->len);
680 offFrame += pPBufPtr->len;
681 pPBufPtr = pPBufPtr->next;
682 }
683 }
684 if (RT_FAILURE(rc))
685 {
686 /* Could it be that some frames are still in the ring buffer */
687 /* 1.c */
688 AssertMsgFailed(("Debug Me!"));
689 }
690
691 /* Commit - what really this function do */
692 IntNetRingCommitFrameEx(&g_pLwipNat->m_pIfBuf->Send, pHdr, pPBuf->tot_len);
693
694 g_pLwipNat->vboxNetLwipNATProcessXmit();
695
696 AssertRCReturn(rc, ERR_IF);
697 LogFlowFunc(("LEAVE: %d\n", rcLwip));
698 return rcLwip;
699}
700
701
702VBoxNetLwipNAT::VBoxNetLwipNAT()
703{
704 LogFlowFuncEnter();
705
706 m_ProxyOptions.tftp_root = NULL;
707 m_ProxyOptions.src4 = NULL;
708 m_ProxyOptions.src6 = NULL;
709 memset(&m_src4, 0, sizeof(m_src4));
710 memset(&m_src6, 0, sizeof(m_src6));
711 m_src4.sin_family = AF_INET;
712 m_src6.sin6_family = AF_INET6;
713#if HAVE_SA_LEN
714 m_src4.sin_len = sizeof(m_src4);
715 m_src6.sin6_len = sizeof(m_src6);
716#endif
717
718 m_LwipNetIf.name[0] = 'N';
719 m_LwipNetIf.name[1] = 'T';
720 m_MacAddress.au8[0] = 0x52;
721 m_MacAddress.au8[1] = 0x54;
722 m_MacAddress.au8[2] = 0;
723 m_MacAddress.au8[3] = 0x12;
724 m_MacAddress.au8[4] = 0x35;
725 m_MacAddress.au8[5] = 0;
726 m_Ipv4Address.u = RT_MAKE_U32_FROM_U8( 10, 0, 2, 2); // NB: big-endian
727 m_Ipv4Netmask.u = RT_H2N_U32_C(0xffffff00);
728
729 for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i)
730 m_vecOptionDefs.push_back(&g_aGetOptDef[i]);
731
732 m_enmTrunkType = kIntNetTrunkType_SrvNat;
733
734 LogFlowFuncLeave();
735}
736
737
738VBoxNetLwipNAT::~VBoxNetLwipNAT()
739{
740 if (m_ProxyOptions.tftp_root != NULL)
741 {
742 RTStrFree((char *)m_ProxyOptions.tftp_root);
743 }
744}
745
746
747int VBoxNetLwipNAT::natServicePfRegister(NATSEVICEPORTFORWARDRULE& natPf)
748{
749 int lrc = 0;
750 int rc = VINF_SUCCESS;
751 int socketSpec = SOCK_STREAM;
752 char *pszHostAddr;
753 int sockFamily = (natPf.Pfr.fPfrIPv6 ? PF_INET6 : PF_INET);
754
755 switch(natPf.Pfr.iPfrProto)
756 {
757 case IPPROTO_TCP:
758 socketSpec = SOCK_STREAM;
759 break;
760 case IPPROTO_UDP:
761 socketSpec = SOCK_DGRAM;
762 break;
763 default:
764 return VERR_IGNORED; /* Ah, just ignore the garbage */
765 }
766
767 pszHostAddr = natPf.Pfr.aszPfrHostAddr;
768
769 /* XXX: workaround for inet_pton and an empty ipv4 address
770 * in rule declaration.
771 */
772 if ( sockFamily == PF_INET
773 && pszHostAddr[0] == 0)
774 pszHostAddr = (char *)"0.0.0.0"; /* XXX: fix it! without type cast */
775
776
777 lrc = fwspec_set(&natPf.FWSpec,
778 sockFamily,
779 socketSpec,
780 pszHostAddr,
781 natPf.Pfr.u16PfrHostPort,
782 natPf.Pfr.aszPfrGuestAddr,
783 natPf.Pfr.u16PfrGuestPort);
784
785 AssertReturn(!lrc, VERR_IGNORED);
786
787 fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
788 AssertPtrReturn(pFwCopy, VERR_IGNORED);
789
790 /*
791 * We need pass the copy, because we can't be sure
792 * how much this pointer will be valid in LWIP environment.
793 */
794 memcpy(pFwCopy, &natPf.FWSpec, sizeof(fwspec));
795
796 lrc = portfwd_rule_add(pFwCopy);
797
798 AssertReturn(!lrc, VERR_IGNORED);
799
800 return VINF_SUCCESS;
801}
802
803
804int VBoxNetLwipNAT::natServiceProcessRegisteredPf(VECNATSERVICEPF& vecRules){
805 ITERATORNATSERVICEPF it;
806 for (it = vecRules.begin();
807 it != vecRules.end(); ++it)
808 {
809 int rc = natServicePfRegister((*it));
810 if (RT_FAILURE(rc))
811 {
812 LogRel(("PF: %s is ignored\n", (*it).Pfr.aszPfrName));
813 continue;
814 }
815 }
816 return VINF_SUCCESS;
817}
818
819
820int VBoxNetLwipNAT::init()
821{
822 com::Bstr bstr;
823 int rc = VINF_SUCCESS;
824 LogFlowFuncEnter();
825
826
827 /* virtualbox initialized in super class */
828
829 HRESULT hrc;
830 hrc = virtualbox->FindNATNetworkByName(com::Bstr(m_Network.c_str()).raw(),
831 net.asOutParam());
832 AssertComRCReturn(hrc, VERR_NOT_FOUND);
833#if !defined(RT_OS_WINDOWS)
834 /* XXX: Temporaly disabled this code on Windows for further debugging */
835 ComPtr<IEventSource> pES;
836
837 hrc = net->COMGETTER(EventSource)(pES.asOutParam());
838 AssertComRC(hrc);
839
840 ComObjPtr<PortForwardListenerImpl> listener;
841 hrc = listener.createObject();
842 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
843
844 hrc = listener->init(new PortForwardListener(), this);
845 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
846
847 com::SafeArray<VBoxEventType_T> events;
848
849 events.push_back(VBoxEventType_OnNATNetworkPortForward);
850
851 hrc = pES->RegisterListener(listener, ComSafeArrayAsInParam(events), true);
852 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
853#endif
854
855 com::Bstr bstrSourceIp4Key = com::BstrFmt("NAT/%s/SourceIp4",m_Network.c_str());
856 com::Bstr bstrSourceIpX;
857 RTNETADDRIPV4 addr;
858 hrc = virtualbox->GetExtraData(bstrSourceIp4Key.raw(), bstrSourceIpX.asOutParam());
859 if (SUCCEEDED(hrc))
860 {
861 int rc = RTNetStrToIPv4Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr);
862 if (RT_SUCCESS(rc))
863 {
864 RT_ZERO(m_src4);
865
866 m_src4.sin_addr.s_addr = addr.u;
867 m_ProxyOptions.src4 = &m_src4;
868
869 bstrSourceIpX.setNull();
870 }
871 }
872
873 if (!fDontLoadRulesOnStartup)
874 {
875 /* XXX: extract function and do not duplicate */
876 com::SafeArray<BSTR> rules;
877 hrc = net->COMGETTER(PortForwardRules4)(ComSafeArrayAsOutParam(rules));
878 Assert(SUCCEEDED(hrc));
879
880 size_t idxRules = 0;
881 for (idxRules = 0; idxRules < rules.size(); ++idxRules)
882 {
883 Log(("%d-rule: %ls\n", idxRules, rules[idxRules]));
884 NATSEVICEPORTFORWARDRULE Rule;
885 RT_ZERO(Rule);
886 rc = netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 0, &Rule.Pfr);
887 AssertRC(rc);
888 m_vecPortForwardRule4.push_back(Rule);
889 }
890
891 rules.setNull();
892 hrc = net->COMGETTER(PortForwardRules6)(ComSafeArrayAsOutParam(rules));
893 Assert(SUCCEEDED(hrc));
894
895 for (idxRules = 0; idxRules < rules.size(); ++idxRules)
896 {
897 Log(("%d-rule: %ls\n", idxRules, rules[idxRules]));
898 NATSEVICEPORTFORWARDRULE Rule;
899 netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 1, &Rule.Pfr);
900 m_vecPortForwardRule6.push_back(Rule);
901 }
902
903#if 0 /* fetching local mappings */
904 com::SafeArray<BSTR> strs;
905 int count_strs;
906 hrc = net->COMGETTER(LocalMappings)(ComSafeArrayAsOutParam(strs));
907 if ( SUCCEEDED(hrc)
908 && (count_strs = strs.size()))
909 {
910 unsigned int j = 0;
911 int i;
912
913 for (i = 0; i < count_strs && j < RT_ELEMENTS(m_lo2off); ++i)
914 {
915 char aszAddr[17];
916 RTNETADDRIPV4 ip4addr;
917 char *pszTerm;
918 uint32_t u32Off;
919 const char *pszLo2Off = com::Utf8Str(strs[i]).c_str();
920
921 RT_ZERO(aszAddr);
922
923 pszTerm = RTStrStr(pszLo2Off, ";");
924
925 if ( !pszTerm
926 && (pszTerm - pszLo2Off) >= 17)
927 continue;
928
929 memcpy(aszAddr, pszLo2Off, (pszTerm - pszLo2Off));
930 rc = RTNetStrToIPv4Addr(aszAddr, &ip4addr);
931 if (RT_FAILURE(rc))
932 continue;
933
934 u32Off = RTStrToUInt32(pszTerm + 1);
935 if (u32Off == 0)
936 continue;
937
938 m_lo2off[j].addr.sin_addr.s_addr = ip4addr.u;
939 m_lo2off[j].off = u32Off;
940 ++j;
941 }
942 }
943#endif
944 } /* if (!fDontLoadRulesOnStartup) */
945
946 hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
947 AssertComRCReturn(hrc, VERR_NOT_FOUND);
948 if (!bstr.isEmpty())
949 {
950 com::Utf8Str strTftpRoot(com::Utf8StrFmt("%ls%c%s",
951 bstr.raw(), RTPATH_DELIMITER, "TFTP"));
952 char *pszStrTemp; // avoid const char ** vs char **
953 rc = RTStrUtf8ToCurrentCP(&pszStrTemp, strTftpRoot.c_str());
954 AssertRC(rc);
955 m_ProxyOptions.tftp_root = pszStrTemp;
956 }
957
958 /* end of COM initialization */
959
960 rc = RTSemEventCreate(&hSemSVC);
961 AssertRCReturn(rc, rc);
962
963 rc = RTReqQueueCreate(&hReqIntNet);
964 AssertRCReturn(rc, rc);
965
966 g_pLwipNat->tryGoOnline();
967 vboxLwipCoreInitialize(VBoxNetLwipNAT::onLwipTcpIpInit, this);
968
969 rc = RTThreadCreate(&g_pLwipNat->hThrIntNetRecv, /* thread handle*/
970 VBoxNetLwipNAT::intNetThreadRecv, /* routine */
971 NULL, /* user data */
972 128 * _1K, /* stack size */
973 RTTHREADTYPE_IO, /* type */
974 0, /* flags, @todo: waitable ?*/
975 "INTNET-RECV");
976 AssertRCReturn(rc,rc);
977
978
979
980 LogFlowFuncLeaveRC(rc);
981 return rc;
982}
983
984
985int VBoxNetLwipNAT::parseOpt(int rc, const RTGETOPTUNION& Val)
986{
987 switch (rc)
988 {
989 case 'p':
990 case 'P':
991 {
992 NATSEVICEPORTFORWARDRULE Rule;
993 VECNATSERVICEPF& rules = (rc == 'P'?
994 m_vecPortForwardRule6
995 : m_vecPortForwardRule4);
996
997 fDontLoadRulesOnStartup = true;
998
999 RT_ZERO(Rule);
1000
1001 int irc = netPfStrToPf(Val.psz, (rc == 'P'), &Rule.Pfr);
1002 rules.push_back(Rule);
1003 return VINF_SUCCESS;
1004 }
1005 default:;
1006 }
1007 return VERR_NOT_FOUND;
1008}
1009
1010
1011int VBoxNetLwipNAT::run()
1012{
1013
1014 while(true)
1015 {
1016 RTSemEventWait(g_pLwipNat->hSemSVC, RT_INDEFINITE_WAIT);
1017 }
1018
1019 vboxLwipCoreFinalize(VBoxNetLwipNAT::onLwipTcpIpFini, this);
1020
1021 /* @todo: clean up of port-forward rules */
1022 m_vecPortForwardRule4.clear();
1023 m_vecPortForwardRule6.clear();
1024
1025 return VINF_SUCCESS;
1026}
1027
1028
1029/**
1030 * Entry point.
1031 */
1032extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1033{
1034 LogFlowFuncEnter();
1035#ifdef RT_OS_WINDOWS
1036 WSADATA wsaData;
1037 int err;
1038
1039 err = WSAStartup(MAKEWORD(2,2), &wsaData);
1040 if (err)
1041 {
1042 fprintf(stderr, "wsastartup: failed (%d)\n", err);
1043 return 1;
1044 }
1045#endif
1046
1047 HRESULT hrc = com::Initialize();
1048#ifdef VBOX_WITH_XPCOM
1049 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1050 {
1051 char szHome[RTPATH_MAX] = "";
1052 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1053 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1054 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1055 }
1056#endif
1057 if (FAILED(hrc))
1058 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
1059
1060 g_pLwipNat = new VBoxNetLwipNAT();
1061
1062 Log2(("NAT: initialization\n"));
1063 int rc = g_pLwipNat->parseArgs(argc - 1, argv + 1);
1064 AssertRC(rc);
1065
1066
1067 if (!rc)
1068 {
1069
1070 g_pLwipNat->init();
1071 g_pLwipNat->run();
1072
1073 }
1074 delete g_pLwipNat;
1075 return 0;
1076}
1077
1078
1079#ifndef VBOX_WITH_HARDENING
1080
1081int main(int argc, char **argv, char **envp)
1082{
1083 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1084 if (RT_FAILURE(rc))
1085 return RTMsgInitFailure(rc);
1086
1087 return TrustedMain(argc, argv, envp);
1088}
1089
1090# if defined(RT_OS_WINDOWS)
1091
1092static LRESULT CALLBACK WindowProc(HWND hwnd,
1093 UINT uMsg,
1094 WPARAM wParam,
1095 LPARAM lParam
1096)
1097{
1098 if(uMsg == WM_DESTROY)
1099 {
1100 PostQuitMessage(0);
1101 return 0;
1102 }
1103 return DefWindowProc (hwnd, uMsg, wParam, lParam);
1104}
1105
1106static LPCWSTR g_WndClassName = L"VBoxNetNatLwipClass";
1107
1108static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
1109{
1110 HWND hwnd = 0;
1111 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
1112 bool bExit = false;
1113
1114 /* Register the Window Class. */
1115 WNDCLASS wc;
1116 wc.style = 0;
1117 wc.lpfnWndProc = WindowProc;
1118 wc.cbClsExtra = 0;
1119 wc.cbWndExtra = sizeof(void *);
1120 wc.hInstance = hInstance;
1121 wc.hIcon = NULL;
1122 wc.hCursor = NULL;
1123 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1124 wc.lpszMenuName = NULL;
1125 wc.lpszClassName = g_WndClassName;
1126
1127 ATOM atomWindowClass = RegisterClass(&wc);
1128
1129 if (atomWindowClass != 0)
1130 {
1131 /* Create the window. */
1132 hwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1133 g_WndClassName, g_WndClassName,
1134 WS_POPUPWINDOW,
1135 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
1136
1137 if (hwnd)
1138 {
1139 SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
1140 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
1141
1142 MSG msg;
1143 while (GetMessage(&msg, NULL, 0, 0))
1144 {
1145 TranslateMessage(&msg);
1146 DispatchMessage(&msg);
1147 }
1148
1149 DestroyWindow (hwnd);
1150
1151 bExit = true;
1152 }
1153
1154 UnregisterClass (g_WndClassName, hInstance);
1155 }
1156
1157 if(bExit)
1158 {
1159 /* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
1160 exit(0);
1161 }
1162
1163 return 0;
1164}
1165
1166
1167
1168/** (We don't want a console usually.) */
1169int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1170{
1171#if 0
1172 NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
1173
1174 HANDLE hThread = CreateThread(
1175 NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
1176 0, /*__in SIZE_T dwStackSize, */
1177 MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
1178 NULL, /*__in_opt LPVOID lpParameter,*/
1179 0, /*__in DWORD dwCreationFlags,*/
1180 NULL /*__out_opt LPDWORD lpThreadId*/
1181 );
1182
1183 if(hThread != NULL)
1184 CloseHandle(hThread);
1185
1186#endif
1187 return main(__argc, __argv, environ);
1188}
1189# endif /* RT_OS_WINDOWS */
1190
1191#endif /* !VBOX_WITH_HARDENING */
1192
1193
1194
1195
1196
1197
Note: See TracBrowser for help on using the repository browser.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette