VirtualBox

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

Last change on this file since 49017 was 49016, checked in by vboxsync, 11 years ago

Change vestigial names proxytest.* to proxy.*

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