VirtualBox

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

Last change on this file since 48310 was 48289, checked in by vboxsync, 11 years ago

Move code to set up IPv6 addresses to VBoxNetLwipNAT::netifInit.
While there, clean up netifInit a bit.

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