VirtualBox

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

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

VBoxNetLwipNAT: PortForwardListener uses default (de)constructor,

init's n_pNAT with init(...) functions,
PortForwardListener::HandleEvent checks m_pNAT before proxying event.

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