VirtualBox

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

Last change on this file since 48420 was 48405, checked in by vboxsync, 11 years ago

NAT/Loopback mapping: changes semantically unrelated symbol ";" with more expressive "=" for map opperation.

VBoxManage natnework modify -t nat-test-1 -l "127.0.1.3=8"

  • 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 48405 2013-09-10 12:22:17Z 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 for(unsigned int i = 0; i < RT_ELEMENTS(g_aGetOptDef); ++i)
725 m_vecOptionDefs.push_back(&g_aGetOptDef[i]);
726
727 m_enmTrunkType = kIntNetTrunkType_SrvNat;
728
729 LogFlowFuncLeave();
730}
731
732
733VBoxNetLwipNAT::~VBoxNetLwipNAT()
734{
735 if (m_ProxyOptions.tftp_root != NULL)
736 {
737 RTStrFree((char *)m_ProxyOptions.tftp_root);
738 }
739}
740
741
742int VBoxNetLwipNAT::natServicePfRegister(NATSEVICEPORTFORWARDRULE& natPf)
743{
744 int lrc = 0;
745 int rc = VINF_SUCCESS;
746 int socketSpec = SOCK_STREAM;
747 char *pszHostAddr;
748 int sockFamily = (natPf.Pfr.fPfrIPv6 ? PF_INET6 : PF_INET);
749
750 switch(natPf.Pfr.iPfrProto)
751 {
752 case IPPROTO_TCP:
753 socketSpec = SOCK_STREAM;
754 break;
755 case IPPROTO_UDP:
756 socketSpec = SOCK_DGRAM;
757 break;
758 default:
759 return VERR_IGNORED; /* Ah, just ignore the garbage */
760 }
761
762 pszHostAddr = natPf.Pfr.aszPfrHostAddr;
763
764 /* XXX: workaround for inet_pton and an empty ipv4 address
765 * in rule declaration.
766 */
767 if ( sockFamily == PF_INET
768 && pszHostAddr[0] == 0)
769 pszHostAddr = (char *)"0.0.0.0"; /* XXX: fix it! without type cast */
770
771
772 lrc = fwspec_set(&natPf.FWSpec,
773 sockFamily,
774 socketSpec,
775 pszHostAddr,
776 natPf.Pfr.u16PfrHostPort,
777 natPf.Pfr.aszPfrGuestAddr,
778 natPf.Pfr.u16PfrGuestPort);
779
780 AssertReturn(!lrc, VERR_IGNORED);
781
782 fwspec *pFwCopy = (fwspec *)RTMemAllocZ(sizeof(fwspec));
783 AssertPtrReturn(pFwCopy, VERR_IGNORED);
784
785 /*
786 * We need pass the copy, because we can't be sure
787 * how much this pointer will be valid in LWIP environment.
788 */
789 memcpy(pFwCopy, &natPf.FWSpec, sizeof(fwspec));
790
791 lrc = portfwd_rule_add(pFwCopy);
792
793 AssertReturn(!lrc, VERR_IGNORED);
794
795 return VINF_SUCCESS;
796}
797
798
799int VBoxNetLwipNAT::natServiceProcessRegisteredPf(VECNATSERVICEPF& vecRules){
800 ITERATORNATSERVICEPF it;
801 for (it = vecRules.begin();
802 it != vecRules.end(); ++it)
803 {
804 int rc = natServicePfRegister((*it));
805 if (RT_FAILURE(rc))
806 {
807 LogRel(("PF: %s is ignored\n", (*it).Pfr.aszPfrName));
808 continue;
809 }
810 }
811 return VINF_SUCCESS;
812}
813
814
815int VBoxNetLwipNAT::init()
816{
817 com::Bstr bstr;
818 int rc = VINF_SUCCESS;
819 LogFlowFuncEnter();
820
821
822 /* virtualbox initialized in super class */
823
824 HRESULT hrc;
825 hrc = virtualbox->FindNATNetworkByName(com::Bstr(m_Network.c_str()).raw(),
826 net.asOutParam());
827 AssertComRCReturn(hrc, VERR_NOT_FOUND);
828#if !defined(RT_OS_WINDOWS)
829 /* XXX: Temporaly disabled this code on Windows for further debugging */
830 ComPtr<IEventSource> pES;
831
832 hrc = net->COMGETTER(EventSource)(pES.asOutParam());
833 AssertComRC(hrc);
834
835 ComObjPtr<PortForwardListenerImpl> listener;
836 hrc = listener.createObject();
837 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
838
839 hrc = listener->init(new PortForwardListener(), this);
840 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
841
842 com::SafeArray<VBoxEventType_T> events;
843
844 events.push_back(VBoxEventType_OnNATNetworkPortForward);
845
846 hrc = pES->RegisterListener(listener, ComSafeArrayAsInParam(events), true);
847 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
848#endif
849
850 com::Bstr bstrSourceIp4Key = com::BstrFmt("NAT/%s/SourceIp4",m_Network.c_str());
851 com::Bstr bstrSourceIpX;
852 RTNETADDRIPV4 addr;
853 hrc = virtualbox->GetExtraData(bstrSourceIp4Key.raw(), bstrSourceIpX.asOutParam());
854 if (SUCCEEDED(hrc))
855 {
856 rc = RTNetStrToIPv4Addr(com::Utf8Str(bstrSourceIpX).c_str(), &addr);
857 if (RT_SUCCESS(rc))
858 {
859 RT_ZERO(m_src4);
860
861 m_src4.sin_addr.s_addr = addr.u;
862 m_ProxyOptions.src4 = &m_src4;
863
864 bstrSourceIpX.setNull();
865 }
866 }
867
868 if (!fDontLoadRulesOnStartup)
869 {
870 /* XXX: extract function and do not duplicate */
871 com::SafeArray<BSTR> rules;
872 hrc = net->COMGETTER(PortForwardRules4)(ComSafeArrayAsOutParam(rules));
873 Assert(SUCCEEDED(hrc));
874
875 size_t idxRules = 0;
876 for (idxRules = 0; idxRules < rules.size(); ++idxRules)
877 {
878 Log(("%d-rule: %ls\n", idxRules, rules[idxRules]));
879 NATSEVICEPORTFORWARDRULE Rule;
880 RT_ZERO(Rule);
881 rc = netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 0, &Rule.Pfr);
882 AssertRC(rc);
883 m_vecPortForwardRule4.push_back(Rule);
884 }
885
886 rules.setNull();
887 hrc = net->COMGETTER(PortForwardRules6)(ComSafeArrayAsOutParam(rules));
888 Assert(SUCCEEDED(hrc));
889
890 for (idxRules = 0; idxRules < rules.size(); ++idxRules)
891 {
892 Log(("%d-rule: %ls\n", idxRules, rules[idxRules]));
893 NATSEVICEPORTFORWARDRULE Rule;
894 netPfStrToPf(com::Utf8Str(rules[idxRules]).c_str(), 1, &Rule.Pfr);
895 m_vecPortForwardRule6.push_back(Rule);
896 }
897
898 com::SafeArray<BSTR> strs;
899 int count_strs;
900 hrc = net->COMGETTER(LocalMappings)(ComSafeArrayAsOutParam(strs));
901 if ( SUCCEEDED(hrc)
902 && (count_strs = strs.size()))
903 {
904 unsigned int j = 0;
905 int i;
906
907 for (i = 0; i < count_strs && j < RT_ELEMENTS(m_lo2off); ++i)
908 {
909 char aszAddr[17];
910 RTNETADDRIPV4 ip4addr;
911 char *pszTerm;
912 uint32_t u32Off;
913 const char *pszLo2Off = com::Utf8Str(strs[i]).c_str();
914
915 RT_ZERO(aszAddr);
916
917 pszTerm = RTStrStr(pszLo2Off, "=");
918
919 if ( !pszTerm
920 || (pszTerm - pszLo2Off) >= 17)
921 continue;
922
923 memcpy(aszAddr, pszLo2Off, (pszTerm - pszLo2Off));
924 rc = RTNetStrToIPv4Addr(aszAddr, &ip4addr);
925 if (RT_FAILURE(rc))
926 continue;
927
928 u32Off = RTStrToUInt32(pszTerm + 1);
929 if (u32Off == 0)
930 continue;
931
932 ip4_addr_set_u32(&m_lo2off[j].loaddr, ip4addr.u);
933 m_lo2off[j].off = u32Off;
934 ++j;
935 }
936
937 m_loOptDescriptor.lomap = m_lo2off;
938 m_loOptDescriptor.num_lomap = j;
939 m_ProxyOptions.lomap_desc = &m_loOptDescriptor;
940 }
941
942 } /* if (!fDontLoadRulesOnStartup) */
943
944 hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
945 AssertComRCReturn(hrc, VERR_NOT_FOUND);
946 if (!bstr.isEmpty())
947 {
948 com::Utf8Str strTftpRoot(com::Utf8StrFmt("%ls%c%s",
949 bstr.raw(), RTPATH_DELIMITER, "TFTP"));
950 char *pszStrTemp; // avoid const char ** vs char **
951 rc = RTStrUtf8ToCurrentCP(&pszStrTemp, strTftpRoot.c_str());
952 AssertRC(rc);
953 m_ProxyOptions.tftp_root = pszStrTemp;
954 }
955
956 /* end of COM initialization */
957
958 rc = RTSemEventCreate(&hSemSVC);
959 AssertRCReturn(rc, rc);
960
961 rc = RTReqQueueCreate(&hReqIntNet);
962 AssertRCReturn(rc, rc);
963
964 g_pLwipNat->tryGoOnline();
965 vboxLwipCoreInitialize(VBoxNetLwipNAT::onLwipTcpIpInit, this);
966
967 rc = RTThreadCreate(&g_pLwipNat->hThrIntNetRecv, /* thread handle*/
968 VBoxNetLwipNAT::intNetThreadRecv, /* routine */
969 NULL, /* user data */
970 128 * _1K, /* stack size */
971 RTTHREADTYPE_IO, /* type */
972 0, /* flags, @todo: waitable ?*/
973 "INTNET-RECV");
974 AssertRCReturn(rc,rc);
975
976
977
978 LogFlowFuncLeaveRC(rc);
979 return rc;
980}
981
982
983int VBoxNetLwipNAT::parseOpt(int rc, const RTGETOPTUNION& Val)
984{
985 switch (rc)
986 {
987 case 'p':
988 case 'P':
989 {
990 NATSEVICEPORTFORWARDRULE Rule;
991 VECNATSERVICEPF& rules = (rc == 'P'?
992 m_vecPortForwardRule6
993 : m_vecPortForwardRule4);
994
995 fDontLoadRulesOnStartup = true;
996
997 RT_ZERO(Rule);
998
999 int irc = netPfStrToPf(Val.psz, (rc == 'P'), &Rule.Pfr);
1000 rules.push_back(Rule);
1001 return VINF_SUCCESS;
1002 }
1003 default:;
1004 }
1005 return VERR_NOT_FOUND;
1006}
1007
1008
1009int VBoxNetLwipNAT::run()
1010{
1011
1012 while(true)
1013 {
1014 RTSemEventWait(g_pLwipNat->hSemSVC, RT_INDEFINITE_WAIT);
1015 }
1016
1017 vboxLwipCoreFinalize(VBoxNetLwipNAT::onLwipTcpIpFini, this);
1018
1019 /* @todo: clean up of port-forward rules */
1020 m_vecPortForwardRule4.clear();
1021 m_vecPortForwardRule6.clear();
1022
1023 return VINF_SUCCESS;
1024}
1025
1026
1027/**
1028 * Entry point.
1029 */
1030extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1031{
1032 LogFlowFuncEnter();
1033#ifdef RT_OS_WINDOWS
1034 WSADATA wsaData;
1035 int err;
1036
1037 err = WSAStartup(MAKEWORD(2,2), &wsaData);
1038 if (err)
1039 {
1040 fprintf(stderr, "wsastartup: failed (%d)\n", err);
1041 return 1;
1042 }
1043#endif
1044
1045 HRESULT hrc = com::Initialize();
1046#ifdef VBOX_WITH_XPCOM
1047 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
1048 {
1049 char szHome[RTPATH_MAX] = "";
1050 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
1051 return RTMsgErrorExit(RTEXITCODE_FAILURE,
1052 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
1053 }
1054#endif
1055 if (FAILED(hrc))
1056 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM!");
1057
1058 g_pLwipNat = new VBoxNetLwipNAT();
1059
1060 Log2(("NAT: initialization\n"));
1061 int rc = g_pLwipNat->parseArgs(argc - 1, argv + 1);
1062 AssertRC(rc);
1063
1064
1065 if (!rc)
1066 {
1067
1068 g_pLwipNat->init();
1069 g_pLwipNat->run();
1070
1071 }
1072 delete g_pLwipNat;
1073 return 0;
1074}
1075
1076
1077#ifndef VBOX_WITH_HARDENING
1078
1079int main(int argc, char **argv, char **envp)
1080{
1081 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
1082 if (RT_FAILURE(rc))
1083 return RTMsgInitFailure(rc);
1084
1085 return TrustedMain(argc, argv, envp);
1086}
1087
1088# if defined(RT_OS_WINDOWS)
1089
1090static LRESULT CALLBACK WindowProc(HWND hwnd,
1091 UINT uMsg,
1092 WPARAM wParam,
1093 LPARAM lParam
1094)
1095{
1096 if(uMsg == WM_DESTROY)
1097 {
1098 PostQuitMessage(0);
1099 return 0;
1100 }
1101 return DefWindowProc (hwnd, uMsg, wParam, lParam);
1102}
1103
1104static LPCWSTR g_WndClassName = L"VBoxNetNatLwipClass";
1105
1106static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
1107{
1108 HWND hwnd = 0;
1109 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
1110 bool bExit = false;
1111
1112 /* Register the Window Class. */
1113 WNDCLASS wc;
1114 wc.style = 0;
1115 wc.lpfnWndProc = WindowProc;
1116 wc.cbClsExtra = 0;
1117 wc.cbWndExtra = sizeof(void *);
1118 wc.hInstance = hInstance;
1119 wc.hIcon = NULL;
1120 wc.hCursor = NULL;
1121 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1122 wc.lpszMenuName = NULL;
1123 wc.lpszClassName = g_WndClassName;
1124
1125 ATOM atomWindowClass = RegisterClass(&wc);
1126
1127 if (atomWindowClass != 0)
1128 {
1129 /* Create the window. */
1130 hwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1131 g_WndClassName, g_WndClassName,
1132 WS_POPUPWINDOW,
1133 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
1134
1135 if (hwnd)
1136 {
1137 SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
1138 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
1139
1140 MSG msg;
1141 while (GetMessage(&msg, NULL, 0, 0))
1142 {
1143 TranslateMessage(&msg);
1144 DispatchMessage(&msg);
1145 }
1146
1147 DestroyWindow (hwnd);
1148
1149 bExit = true;
1150 }
1151
1152 UnregisterClass (g_WndClassName, hInstance);
1153 }
1154
1155 if(bExit)
1156 {
1157 /* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
1158 exit(0);
1159 }
1160
1161 return 0;
1162}
1163
1164
1165
1166/** (We don't want a console usually.) */
1167int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1168{
1169#if 0
1170 NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
1171
1172 HANDLE hThread = CreateThread(
1173 NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
1174 0, /*__in SIZE_T dwStackSize, */
1175 MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
1176 NULL, /*__in_opt LPVOID lpParameter,*/
1177 0, /*__in DWORD dwCreationFlags,*/
1178 NULL /*__out_opt LPDWORD lpThreadId*/
1179 );
1180
1181 if(hThread != NULL)
1182 CloseHandle(hThread);
1183
1184#endif
1185 return main(__argc, __argv, environ);
1186}
1187# endif /* RT_OS_WINDOWS */
1188
1189#endif /* !VBOX_WITH_HARDENING */
1190
1191
1192
1193
1194
1195
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