VirtualBox

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

Last change on this file since 47877 was 47877, checked in by vboxsync, 12 years ago

fix OSE

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