VirtualBox

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

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

Oops, use sin_len/sin6_len instead of sa_len.

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

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