VirtualBox

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

Last change on this file since 48767 was 48482, checked in by vboxsync, 11 years ago

VBoxNetLwipNAT::init(): vbox-style of multiline if-clause.

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

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