VirtualBox

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

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

lwip-nat: warnings [-Wshadow]

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