VirtualBox

source: vbox/trunk/src/VBox/NetworkServices/DHCP/VBoxNetDHCP.cpp@ 49523

Last change on this file since 49523 was 49516, checked in by vboxsync, 11 years ago

Introduce option "--need-main(-M) on|off" in network services to emphosize whether network service need to establish connection with Main (by default this optiois off).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.3 KB
Line 
1/* $Id: VBoxNetDHCP.cpp 49516 2013-11-16 06:42:31Z vboxsync $ */
2/** @file
3 * VBoxNetDHCP - DHCP Service for connecting to IntNet.
4 */
5
6/*
7 * Copyright (C) 2009-2011 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/** @page pg_net_dhcp VBoxNetDHCP
19 *
20 * Write a few words...
21 *
22 */
23
24/*******************************************************************************
25* Header Files *
26*******************************************************************************/
27#include <VBox/com/com.h>
28#include <VBox/com/listeners.h>
29#include <VBox/com/string.h>
30#include <VBox/com/Guid.h>
31#include <VBox/com/array.h>
32#include <VBox/com/ErrorInfo.h>
33#include <VBox/com/errorprint.h>
34#include <VBox/com/EventQueue.h>
35#include <VBox/com/VirtualBox.h>
36
37#include <iprt/alloca.h>
38#include <iprt/buildconfig.h>
39#include <iprt/err.h>
40#include <iprt/net.h> /* must come before getopt */
41#include <iprt/getopt.h>
42#include <iprt/initterm.h>
43#include <iprt/message.h>
44#include <iprt/param.h>
45#include <iprt/path.h>
46#include <iprt/stream.h>
47#include <iprt/time.h>
48#include <iprt/string.h>
49
50#include <VBox/sup.h>
51#include <VBox/intnet.h>
52#include <VBox/intnetinline.h>
53#include <VBox/vmm/vmm.h>
54#include <VBox/version.h>
55
56
57#include "../NetLib/VBoxNetLib.h"
58#include "../NetLib/shared_ptr.h"
59
60#include <vector>
61#include <list>
62#include <string>
63#include <map>
64
65#include "../NetLib/VBoxNetBaseService.h"
66
67#ifdef RT_OS_WINDOWS /* WinMain */
68# include <Windows.h>
69# include <stdlib.h>
70# ifdef INET_ADDRSTRLEN
71/* On Windows INET_ADDRSTRLEN defined as 22 Ws2ipdef.h, because it include port number */
72# undef INET_ADDRSTRLEN
73# endif
74# define INET_ADDRSTRLEN 16
75#else
76# include <netinet/in.h>
77#endif
78
79
80#include "Config.h"
81/*******************************************************************************
82* Structures and Typedefs *
83*******************************************************************************/
84/**
85 * DHCP server instance.
86 */
87class VBoxNetDhcp: public VBoxNetBaseService
88{
89public:
90 VBoxNetDhcp();
91 virtual ~VBoxNetDhcp();
92
93 int init();
94 int run(void);
95 void usage(void) { /* XXX: document options */ };
96 int parseOpt(int rc, const RTGETOPTUNION& getOptVal);
97
98protected:
99 bool handleDhcpMsg(uint8_t uMsgType, PCRTNETBOOTP pDhcpMsg, size_t cb);
100 bool handleDhcpReqDiscover(PCRTNETBOOTP pDhcpMsg, size_t cb);
101 bool handleDhcpReqRequest(PCRTNETBOOTP pDhcpMsg, size_t cb);
102 bool handleDhcpReqDecline(PCRTNETBOOTP pDhcpMsg, size_t cb);
103 bool handleDhcpReqRelease(PCRTNETBOOTP pDhcpMsg, size_t cb);
104
105 void debugPrintV(int32_t iMinLevel, bool fMsg, const char *pszFmt, va_list va) const;
106 static const char *debugDhcpName(uint8_t uMsgType);
107
108private:
109 int initNoMain();
110 int initWithMain();
111
112protected:
113 /** @name The DHCP server specific configuration data members.
114 * @{ */
115 /*
116 * XXX: what was the plan? SQL3 or plain text file?
117 * How it will coexists with managment from VBoxManagement, who should manage db
118 * in that case (VBoxManage, VBoxSVC ???)
119 */
120 std::string m_LeaseDBName;
121
122 /** @} */
123
124 /* corresponding dhcp server description in Main */
125 ComPtr<IDHCPServer> m_DhcpServer;
126
127 ComPtr<INATNetwork> m_NATNetwork;
128
129 /*
130 * We will ignore cmd line parameters IFF there will be some DHCP specific arguments
131 * otherwise all paramters will come from Main.
132 */
133 bool m_fIgnoreCmdLineParameters;
134
135 /*
136 * -b -n 10.0.1.2 -m 255.255.255.0 -> to the list processing in
137 */
138 typedef struct
139 {
140 char Key;
141 std::string strValue;
142 } CMDLNPRM;
143 std::list<CMDLNPRM> CmdParameterll;
144 typedef std::list<CMDLNPRM>::iterator CmdParameterIterator;
145
146 /** @name Debug stuff
147 * @{ */
148 int32_t m_cVerbosity;
149 uint8_t m_uCurMsgType;
150 size_t m_cbCurMsg;
151 PCRTNETBOOTP m_pCurMsg;
152 VBOXNETUDPHDRS m_CurHdrs;
153 /** @} */
154};
155#if 0
156/* XXX: clean up it. */
157typedef std::vector<VBoxNetDhcpLease> DhcpLeaseContainer;
158typedef DhcpLeaseContainer::iterator DhcpLeaseIterator;
159typedef DhcpLeaseContainer::reverse_iterator DhcpLeaseRIterator;
160typedef DhcpLeaseContainer::const_iterator DhcpLeaseCIterator;
161#endif
162
163/*******************************************************************************
164* Global Variables *
165*******************************************************************************/
166/** Pointer to the DHCP server. */
167static VBoxNetDhcp *g_pDhcp;
168
169/* DHCP server specific options */
170static RTGETOPTDEF g_aOptionDefs[] =
171{
172 { "--lease-db", 'D', RTGETOPT_REQ_STRING },
173 { "--begin-config", 'b', RTGETOPT_REQ_NOTHING },
174 { "--gateway", 'g', RTGETOPT_REQ_IPV4ADDR },
175 { "--lower-ip", 'l', RTGETOPT_REQ_IPV4ADDR },
176 { "--upper-ip", 'u', RTGETOPT_REQ_IPV4ADDR },
177};
178
179#if 0
180/* XXX this will gone */
181/**
182 * Offer this lease to a client.
183 *
184 * @param xid The transaction ID.
185 */
186void VBoxNetDhcpLease::offer(uint32_t xid)
187{
188 m_enmState = kState_Offer;
189 m_xid = xid;
190 RTTimeNow(&m_ExpireTime);
191 RTTimeSpecAddSeconds(&m_ExpireTime, 60);
192}
193
194
195/**
196 * Activate this lease (i.e. a client is now using it).
197 */
198void VBoxNetDhcpLease::activate(void)
199{
200 m_enmState = kState_Active;
201 RTTimeNow(&m_ExpireTime);
202 RTTimeSpecAddSeconds(&m_ExpireTime, m_pCfg ? m_pCfg->m_cSecLease : 60); /* m_pCfg can be NULL right now... */
203}
204
205
206/**
207 * Activate this lease with a new transaction ID.
208 *
209 * @param xid The transaction ID.
210 * @todo check if this is really necessary.
211 */
212void VBoxNetDhcpLease::activate(uint32_t xid)
213{
214 activate();
215 m_xid = xid;
216}
217
218
219/**
220 * Release a lease either upon client request or because it didn't quite match a
221 * DHCP_REQUEST.
222 */
223void VBoxNetDhcpLease::release(void)
224{
225 m_enmState = kState_Free;
226 RTTimeNow(&m_ExpireTime);
227 RTTimeSpecAddSeconds(&m_ExpireTime, 5);
228}
229
230
231/**
232 * Checks if the lease has expired or not.
233 *
234 * This just checks the expiration time not the state. This is so that this
235 * method will work for reusing RELEASEd leases when the client comes back after
236 * a reboot or ipconfig /renew. Callers not interested in info on released
237 * leases should check the state first.
238 *
239 * @returns true if expired, false if not.
240 */
241bool VBoxNetDhcpLease::hasExpired() const
242{
243 RTTIMESPEC Now;
244 return RTTimeSpecGetSeconds(&m_ExpireTime) > RTTimeSpecGetSeconds(RTTimeNow(&Now));
245}
246#endif
247
248/**
249 * Construct a DHCP server with a default configuration.
250 */
251VBoxNetDhcp::VBoxNetDhcp()
252{
253 m_Name = "VBoxNetDhcp";
254 m_Network = "VBoxNetDhcp";
255 m_TrunkName = "";
256 m_enmTrunkType = kIntNetTrunkType_WhateverNone;
257 m_MacAddress.au8[0] = 0x08;
258 m_MacAddress.au8[1] = 0x00;
259 m_MacAddress.au8[2] = 0x27;
260 m_MacAddress.au8[3] = 0x40;
261 m_MacAddress.au8[4] = 0x41;
262 m_MacAddress.au8[5] = 0x42;
263 m_Ipv4Address.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2, 5)));
264
265 m_pSession = NIL_RTR0PTR;
266 m_cbSendBuf = 8192;
267 m_cbRecvBuf = 51200; /** @todo tune to 64 KB with help from SrvIntR0 */
268 m_hIf = INTNET_HANDLE_INVALID;
269 m_pIfBuf = NULL;
270
271 m_cVerbosity = 0;
272 m_uCurMsgType = UINT8_MAX;
273 m_cbCurMsg = 0;
274 m_pCurMsg = NULL;
275 memset(&m_CurHdrs, '\0', sizeof(m_CurHdrs));
276
277 m_fIgnoreCmdLineParameters = true;
278
279 for(unsigned int i = 0; i < RT_ELEMENTS(g_aOptionDefs); ++i)
280 m_vecOptionDefs.push_back(&g_aOptionDefs[i]);
281
282#if 0 /* enable to hack the code without a mile long argument list. */
283 VBoxNetDhcpCfg *pDefCfg = new VBoxNetDhcpCfg();
284 pDefCfg->m_LowerAddr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2,100)));
285 pDefCfg->m_UpperAddr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2,250)));
286 pDefCfg->m_SubnetMask.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8(255,255,255, 0)));
287 RTNETADDRIPV4 Addr;
288 Addr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2, 1)));
289 pDefCfg->m_Routers.push_back(Addr);
290 Addr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2, 2)));
291 pDefCfg->m_DNSes.push_back(Addr);
292 pDefCfg->m_DomainName = "vboxnetdhcp.org";
293# if 0
294 pDefCfg->m_cSecLease = 60*60; /* 1 hour */
295# else
296 pDefCfg->m_cSecLease = 30; /* sec */
297# endif
298 pDefCfg->m_TftpServer = "10.0.2.3"; //??
299 this->addConfig(pDefCfg);
300#endif
301}
302
303
304/**
305 * Destruct a DHCP server.
306 */
307VBoxNetDhcp::~VBoxNetDhcp()
308{
309}
310
311
312
313
314/**
315 * Parse the DHCP specific arguments.
316 *
317 * This callback caled for each paramenter so
318 * ....
319 * we nee post analisys of the parameters, at least
320 * for -b, -g, -l, -u, -m
321 */
322int VBoxNetDhcp::parseOpt(int rc, const RTGETOPTUNION& Val)
323{
324 CMDLNPRM prm;
325
326 /* Ok, we've entered here, thus we can't ignore cmd line parameters anymore */
327 m_fIgnoreCmdLineParameters = false;
328
329 prm.Key = rc;
330
331 switch (rc)
332 {
333 case 'l':
334 case 'u':
335 case 'g':
336 {
337 char buf[17];
338 RTStrPrintf(buf, 17, "%RTnaipv4", Val.IPv4Addr.u);
339 prm.strValue = buf;
340 CmdParameterll.push_back(prm);
341 }
342 break;
343
344 case 'b': // ignore
345 case 'D': // ignore
346 break;
347
348 default:
349 rc = RTGetOptPrintError(rc, &Val);
350 RTPrintf("Use --help for more information.\n");
351 return rc;
352 }
353
354 return VINF_SUCCESS;
355}
356
357int VBoxNetDhcp::init()
358{
359 int rc = this->VBoxNetBaseService::init();
360 AssertRCReturn(rc, rc);
361
362 NetworkManager *netManager = NetworkManager::getNetworkManager();
363
364 netManager->setOurAddress(m_Ipv4Address);
365 netManager->setOurNetmask(m_Ipv4Netmask);
366 netManager->setOurMac(m_MacAddress);
367
368 if (m_fNeedMain)
369 rc = initWithMain();
370 else
371 rc = initNoMain();
372
373 AssertRCReturn(rc, rc);
374
375 return VINF_SUCCESS;
376}
377
378/**
379 * Runs the DHCP server.
380 *
381 * @returns exit code + error message to stderr on failure, won't return on
382 * success (you must kill this process).
383 */
384int VBoxNetDhcp::run(void)
385{
386
387 /* XXX: shortcut should be hidden from network manager */
388 NetworkManager *netManager = NetworkManager::getNetworkManager();
389 netManager->m_pSession = m_pSession;
390 netManager->m_hIf = m_hIf;
391 netManager->m_pIfBuf = m_pIfBuf;
392
393 /*
394 * The loop.
395 */
396 PINTNETRINGBUF pRingBuf = &m_pIfBuf->Recv;
397 for (;;)
398 {
399 /*
400 * Wait for a packet to become available.
401 */
402 INTNETIFWAITREQ WaitReq;
403 WaitReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
404 WaitReq.Hdr.cbReq = sizeof(WaitReq);
405 WaitReq.pSession = m_pSession;
406 WaitReq.hIf = m_hIf;
407 WaitReq.cMillies = 2000; /* 2 secs - the sleep is for some reason uninterruptible... */ /** @todo fix interruptability in SrvIntNet! */
408 int rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_WAIT, 0, &WaitReq.Hdr);
409 if (RT_FAILURE(rc))
410 {
411 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED)
412 continue;
413 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: VMMR0_DO_INTNET_IF_WAIT returned %Rrc\n", rc);
414 return 1;
415 }
416
417 /*
418 * Process the receive buffer.
419 */
420 while (IntNetRingHasMoreToRead(pRingBuf))
421 {
422 size_t cb;
423 void *pv = VBoxNetUDPMatch(m_pIfBuf, RTNETIPV4_PORT_BOOTPS, &m_MacAddress,
424 VBOXNETUDP_MATCH_UNICAST | VBOXNETUDP_MATCH_BROADCAST | VBOXNETUDP_MATCH_CHECKSUM
425 | (m_cVerbosity > 2 ? VBOXNETUDP_MATCH_PRINT_STDERR : 0),
426 &m_CurHdrs, &cb);
427 if (pv && cb)
428 {
429 PCRTNETBOOTP pDhcpMsg = (PCRTNETBOOTP)pv;
430 m_pCurMsg = pDhcpMsg;
431 m_cbCurMsg = cb;
432
433 uint8_t uMsgType;
434 if (RTNetIPv4IsDHCPValid(NULL /* why is this here? */, pDhcpMsg, cb, &uMsgType))
435 {
436 m_uCurMsgType = uMsgType;
437 handleDhcpMsg(uMsgType, pDhcpMsg, cb);
438 m_uCurMsgType = UINT8_MAX;
439 }
440 else
441 debugPrint(1, true, "VBoxNetDHCP: Skipping invalid DHCP packet.\n"); /** @todo handle pure bootp clients too? */
442
443 m_pCurMsg = NULL;
444 m_cbCurMsg = 0;
445 }
446 else if (VBoxNetArpHandleIt(m_pSession, m_hIf, m_pIfBuf, &m_MacAddress, m_Ipv4Address))
447 {
448 /* nothing */
449 }
450
451 /* Advance to the next frame. */
452 IntNetRingSkipFrame(pRingBuf);
453 }
454 }
455
456 return 0;
457}
458
459
460/**
461 * Handles a DHCP message.
462 *
463 * @returns true if handled, false if not.
464 * @param uMsgType The message type.
465 * @param pDhcpMsg The DHCP message.
466 * @param cb The size of the DHCP message.
467 */
468bool VBoxNetDhcp::handleDhcpMsg(uint8_t uMsgType, PCRTNETBOOTP pDhcpMsg, size_t cb)
469{
470 if (pDhcpMsg->bp_op == RTNETBOOTP_OP_REQUEST)
471 {
472 switch (uMsgType)
473 {
474 case RTNET_DHCP_MT_DISCOVER:
475 return handleDhcpReqDiscover(pDhcpMsg, cb);
476
477 case RTNET_DHCP_MT_REQUEST:
478 return handleDhcpReqRequest(pDhcpMsg, cb);
479
480 case RTNET_DHCP_MT_DECLINE:
481 return handleDhcpReqDecline(pDhcpMsg, cb);
482
483 case RTNET_DHCP_MT_RELEASE:
484 return handleDhcpReqRelease(pDhcpMsg, cb);
485
486 case RTNET_DHCP_MT_INFORM:
487 debugPrint(0, true, "Should we handle this?");
488 break;
489
490 default:
491 debugPrint(0, true, "Unexpected.");
492 break;
493 }
494 }
495 return false;
496}
497
498
499/**
500 * The client is requesting an offer.
501 *
502 * @returns true.
503 *
504 * @param pDhcpMsg The message.
505 * @param cb The message size.
506 */
507bool VBoxNetDhcp::handleDhcpReqDiscover(PCRTNETBOOTP pDhcpMsg, size_t cb)
508{
509 RawOption opt;
510 memset(&opt, 0, sizeof(RawOption));
511 /* 1. Find client */
512 ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();
513 Client client = confManager->getClientByDhcpPacket(pDhcpMsg, cb);
514
515 /* 2. Find/Bind lease for client */
516 Lease lease = confManager->allocateLease4Client(client, pDhcpMsg, cb);
517 AssertReturn(lease != Lease::NullLease, VINF_SUCCESS);
518
519 int rc = ConfigurationManager::extractRequestList(pDhcpMsg, cb, opt);
520
521 /* 3. Send of offer */
522 NetworkManager *networkManager = NetworkManager::getNetworkManager();
523
524 lease.bindingPhase(true);
525 lease.phaseStart(RTTimeMilliTS());
526 lease.setExpiration(300); /* 3 min. */
527 networkManager->offer4Client(client, pDhcpMsg->bp_xid, opt.au8RawOpt, opt.cbRawOpt);
528
529 return VINF_SUCCESS;
530}
531
532
533/**
534 * The client is requesting an offer.
535 *
536 * @returns true.
537 *
538 * @param pDhcpMsg The message.
539 * @param cb The message size.
540 */
541bool VBoxNetDhcp::handleDhcpReqRequest(PCRTNETBOOTP pDhcpMsg, size_t cb)
542{
543 ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();
544 NetworkManager *networkManager = NetworkManager::getNetworkManager();
545
546 /* 1. find client */
547 Client client = confManager->getClientByDhcpPacket(pDhcpMsg, cb);
548
549 /* 2. find bound lease */
550 Lease l = client.lease();
551 if (l != Lease::NullLease)
552 {
553
554 if (l.isExpired())
555 {
556 /* send client to INIT state */
557 Client c(client);
558 networkManager->nak(client, pDhcpMsg->bp_xid);
559 confManager->expireLease4Client(c);
560 return true;
561 }
562 else {
563 /* XXX: Validate request */
564 RawOption opt;
565 RT_ZERO(opt);
566
567 Client c(client);
568 int rc = confManager->commitLease4Client(c);
569 AssertRCReturn(rc, false);
570
571 rc = ConfigurationManager::extractRequestList(pDhcpMsg, cb, opt);
572 AssertRCReturn(rc, false);
573
574 networkManager->ack(client, pDhcpMsg->bp_xid, opt.au8RawOpt, opt.cbRawOpt);
575 }
576 }
577 else
578 {
579 networkManager->nak(client, pDhcpMsg->bp_xid);
580 }
581 return true;
582}
583
584
585/**
586 * The client is declining an offer we've made.
587 *
588 * @returns true.
589 *
590 * @param pDhcpMsg The message.
591 * @param cb The message size.
592 */
593bool VBoxNetDhcp::handleDhcpReqDecline(PCRTNETBOOTP, size_t)
594{
595 /** @todo Probably need to match the server IP here to work correctly with
596 * other servers. */
597
598 /*
599 * The client is supposed to pass us option 50, requested address,
600 * from the offer. We also match the lease state. Apparently the
601 * MAC address is not supposed to be checked here.
602 */
603
604 /** @todo this is not required in the initial implementation, do it later. */
605 debugPrint(1, true, "DECLINE is not implemented");
606 return true;
607}
608
609
610/**
611 * The client is releasing its lease - good boy.
612 *
613 * @returns true.
614 *
615 * @param pDhcpMsg The message.
616 * @param cb The message size.
617 */
618bool VBoxNetDhcp::handleDhcpReqRelease(PCRTNETBOOTP, size_t)
619{
620 /** @todo Probably need to match the server IP here to work correctly with
621 * other servers. */
622
623 /*
624 * The client may pass us option 61, client identifier, which we should
625 * use to find the lease by.
626 *
627 * We're matching MAC address and lease state as well.
628 */
629
630 /*
631 * If no client identifier or if we couldn't find a lease by using it,
632 * we will try look it up by the client IP address.
633 */
634
635
636 /*
637 * If found, release it.
638 */
639
640
641 /** @todo this is not required in the initial implementation, do it later. */
642 debugPrint(1, true, "RELEASE is not implemented");
643 return true;
644}
645
646
647/**
648 * Print debug message depending on the m_cVerbosity level.
649 *
650 * @param iMinLevel The minimum m_cVerbosity level for this message.
651 * @param fMsg Whether to dump parts for the current DHCP message.
652 * @param pszFmt The message format string.
653 * @param va Optional arguments.
654 */
655void VBoxNetDhcp::debugPrintV(int iMinLevel, bool fMsg, const char *pszFmt, va_list va) const
656{
657 if (iMinLevel <= m_cVerbosity)
658 {
659 va_list vaCopy; /* This dude is *very* special, thus the copy. */
660 va_copy(vaCopy, va);
661 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: %s: %N\n", iMinLevel >= 2 ? "debug" : "info", pszFmt, &vaCopy);
662 va_end(vaCopy);
663
664 if ( fMsg
665 && m_cVerbosity >= 2
666 && m_pCurMsg)
667 {
668 /* XXX: export this to debugPrinfDhcpMsg or variant and other method export
669 * to base class
670 */
671 const char *pszMsg = m_uCurMsgType != UINT8_MAX ? debugDhcpName(m_uCurMsgType) : "";
672 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: debug: %8s chaddr=%.6Rhxs ciaddr=%d.%d.%d.%d yiaddr=%d.%d.%d.%d siaddr=%d.%d.%d.%d xid=%#x\n",
673 pszMsg,
674 &m_pCurMsg->bp_chaddr,
675 m_pCurMsg->bp_ciaddr.au8[0], m_pCurMsg->bp_ciaddr.au8[1], m_pCurMsg->bp_ciaddr.au8[2], m_pCurMsg->bp_ciaddr.au8[3],
676 m_pCurMsg->bp_yiaddr.au8[0], m_pCurMsg->bp_yiaddr.au8[1], m_pCurMsg->bp_yiaddr.au8[2], m_pCurMsg->bp_yiaddr.au8[3],
677 m_pCurMsg->bp_siaddr.au8[0], m_pCurMsg->bp_siaddr.au8[1], m_pCurMsg->bp_siaddr.au8[2], m_pCurMsg->bp_siaddr.au8[3],
678 m_pCurMsg->bp_xid);
679 }
680 }
681}
682
683
684/**
685 * Gets the name of given DHCP message type.
686 *
687 * @returns Readonly name.
688 * @param uMsgType The message number.
689 */
690/* static */ const char *VBoxNetDhcp::debugDhcpName(uint8_t uMsgType)
691{
692 switch (uMsgType)
693 {
694 case 0: return "MT_00";
695 case RTNET_DHCP_MT_DISCOVER: return "DISCOVER";
696 case RTNET_DHCP_MT_OFFER: return "OFFER";
697 case RTNET_DHCP_MT_REQUEST: return "REQUEST";
698 case RTNET_DHCP_MT_DECLINE: return "DECLINE";
699 case RTNET_DHCP_MT_ACK: return "ACK";
700 case RTNET_DHCP_MT_NAC: return "NAC";
701 case RTNET_DHCP_MT_RELEASE: return "RELEASE";
702 case RTNET_DHCP_MT_INFORM: return "INFORM";
703 case 9: return "MT_09";
704 case 10: return "MT_0a";
705 case 11: return "MT_0b";
706 case 12: return "MT_0c";
707 case 13: return "MT_0d";
708 case 14: return "MT_0e";
709 case 15: return "MT_0f";
710 case 16: return "MT_10";
711 case 17: return "MT_11";
712 case 18: return "MT_12";
713 case 19: return "MT_13";
714 case UINT8_MAX: return "MT_ff";
715 default: return "UNKNOWN";
716 }
717}
718
719
720int VBoxNetDhcp::initNoMain()
721{
722 CmdParameterIterator it;
723
724 RTNETADDRIPV4 networkId;
725 networkId.u = m_Ipv4Address.u & m_Ipv4Netmask.u;
726 RTNETADDRIPV4 netmask = m_Ipv4Netmask;
727
728 RTNETADDRIPV4 UpperAddress;
729 RTNETADDRIPV4 LowerAddress = networkId;
730 UpperAddress.u = RT_H2N_U32(RT_N2H_U32(LowerAddress.u) | RT_N2H_U32(netmask.u));
731
732 for (it = CmdParameterll.begin(); it != CmdParameterll.end(); ++it)
733 {
734 switch(it->Key)
735 {
736 case 'l':
737 RTNetStrToIPv4Addr(it->strValue.c_str(), &LowerAddress);
738 break;
739
740 case 'u':
741 RTNetStrToIPv4Addr(it->strValue.c_str(), &UpperAddress);
742 break;
743 case 'b':
744 break;
745
746 }
747 }
748
749 ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();
750 AssertPtrReturn(confManager, VERR_INTERNAL_ERROR);
751 confManager->addNetwork(unconst(g_RootConfig),
752 networkId,
753 m_Ipv4Netmask,
754 LowerAddress,
755 UpperAddress);
756
757 return VINF_SUCCESS;
758}
759
760
761int VBoxNetDhcp::initWithMain()
762{
763 /* ok, here we should initiate instance of dhcp server
764 * and listener for Dhcp configuration events
765 */
766 AssertRCReturn(virtualbox.isNull(), VERR_INTERNAL_ERROR);
767
768 HRESULT hrc = virtualbox->FindDHCPServerByNetworkName(com::Bstr(m_Network.c_str()).raw(),
769 m_DhcpServer.asOutParam());
770 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
771
772 hrc = virtualbox->FindNATNetworkByName(com::Bstr(m_Network.c_str()).raw(),
773 m_NATNetwork.asOutParam());
774
775 BOOL fNeedDhcpServer = false;
776 if (FAILED(m_NATNetwork->COMGETTER(NeedDhcpServer)(&fNeedDhcpServer)))
777 return VERR_INTERNAL_ERROR;
778
779 if (!fNeedDhcpServer)
780 return VERR_CANCELLED;
781
782 RTNETADDRIPV4 gateway;
783 com::Bstr strGateway;
784
785 hrc = m_NATNetwork->COMGETTER(Gateway)(strGateway.asOutParam());
786 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
787 RTNetStrToIPv4Addr(com::Utf8Str(strGateway).c_str(), &gateway);
788
789 ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();
790 AssertPtrReturn(confManager, VERR_INTERNAL_ERROR);
791 confManager->addToAddressList(RTNET_DHCP_OPT_ROUTERS, gateway);
792
793 unsigned int i;
794 unsigned int count_strs;
795 com::SafeArray<BSTR> strs;
796 std::map<RTNETADDRIPV4, uint32_t> MapIp4Addr2Off;
797
798 hrc = m_NATNetwork->COMGETTER(LocalMappings)(ComSafeArrayAsOutParam(strs));
799 if ( SUCCEEDED(hrc)
800 && (count_strs = strs.size()))
801 {
802 for (i = 0; i < count_strs; ++i)
803 {
804 char szAddr[17];
805 RTNETADDRIPV4 ip4addr;
806 char *pszTerm;
807 uint32_t u32Off;
808 com::Utf8Str strLo2Off(strs[i]);
809 const char *pszLo2Off = strLo2Off.c_str();
810
811 RT_ZERO(szAddr);
812
813 pszTerm = RTStrStr(pszLo2Off, "=");
814
815 if ( pszTerm
816 && (pszTerm - pszLo2Off) <= INET_ADDRSTRLEN)
817 {
818 memcpy(szAddr, pszLo2Off, (pszTerm - pszLo2Off));
819 int rc = RTNetStrToIPv4Addr(szAddr, &ip4addr);
820 if (RT_SUCCESS(rc))
821 {
822 u32Off = RTStrToUInt32(pszTerm + 1);
823 if (u32Off != 0)
824 MapIp4Addr2Off.insert(
825 std::map<RTNETADDRIPV4,uint32_t>::value_type(ip4addr, u32Off));
826 }
827 }
828 }
829 }
830
831 strs.setNull();
832 ComPtr<IHost> host;
833 if (SUCCEEDED(virtualbox->COMGETTER(Host)(host.asOutParam())))
834 {
835 if (SUCCEEDED(host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(strs))))
836 {
837 RTNETADDRIPV4 addr;
838
839 confManager->flushAddressList(RTNET_DHCP_OPT_DNS);
840 int rc;
841 for (i = 0; i < strs.size(); ++i)
842 {
843 rc = RTNetStrToIPv4Addr(com::Utf8Str(strs[i]).c_str(), &addr);
844 if (RT_SUCCESS(rc))
845 {
846 if (addr.au8[0] == 127)
847 {
848 if (MapIp4Addr2Off[addr] != 0)
849 {
850 addr.u = RT_H2N_U32(RT_N2H_U32(m_Ipv4Address.u & m_Ipv4Netmask.u)
851 + MapIp4Addr2Off[addr]);
852 }
853 else
854 continue;
855 }
856
857 confManager->addToAddressList(RTNET_DHCP_OPT_DNS, addr);
858 }
859 }
860 }
861
862 strs.setNull();
863#if 0
864 if (SUCCEEDED(host->COMGETTER(SearchStrings)(ComSafeArrayAsOutParam(strs))))
865 {
866 /* XXX: todo. */;
867 }
868 strs.setNull();
869#endif
870 com::Bstr domain;
871 if (SUCCEEDED(host->COMGETTER(DomainName)(domain.asOutParam())))
872 confManager->setString(RTNET_DHCP_OPT_DOMAIN_NAME, std::string(com::Utf8Str(domain).c_str()));
873 }
874
875 com::Bstr strUpperIp, strLowerIp;
876
877 RTNETADDRIPV4 LowerAddress;
878 RTNETADDRIPV4 UpperAddress;
879
880 hrc = m_DhcpServer->COMGETTER(UpperIP)(strUpperIp.asOutParam());
881 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
882 RTNetStrToIPv4Addr(com::Utf8Str(strUpperIp).c_str(), &UpperAddress);
883
884
885 hrc = m_DhcpServer->COMGETTER(LowerIP)(strLowerIp.asOutParam());
886 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
887 RTNetStrToIPv4Addr(com::Utf8Str(strLowerIp).c_str(), &LowerAddress);
888
889 RTNETADDRIPV4 networkId;
890 networkId.u = m_Ipv4Address.u & m_Ipv4Netmask.u;
891 std::string name = std::string("default");
892
893 confManager->addNetwork(unconst(g_RootConfig),
894 networkId,
895 m_Ipv4Netmask,
896 LowerAddress,
897 UpperAddress);
898
899 com::Bstr bstr;
900 hrc = virtualbox->COMGETTER(HomeFolder)(bstr.asOutParam());
901 std::string strXmlLeaseFile(com::Utf8StrFmt("%ls%c%s.leases",
902 bstr.raw(), RTPATH_DELIMITER, m_Network.c_str()).c_str());
903 confManager->loadFromFile(strXmlLeaseFile);
904
905 return VINF_SUCCESS;
906}
907
908/**
909 * Entry point.
910 */
911extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv)
912{
913 /*
914 * Instantiate the DHCP server and hand it the options.
915 */
916
917 VBoxNetDhcp *pDhcp = new VBoxNetDhcp();
918 if (!pDhcp)
919 {
920 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: new VBoxNetDhcp failed!\n");
921 return 1;
922 }
923 int rc = pDhcp->parseArgs(argc - 1, argv + 1);
924 if (rc)
925 return rc;
926
927 pDhcp->init();
928
929 /*
930 * Try connect the server to the network.
931 */
932 rc = pDhcp->tryGoOnline();
933 if (RT_FAILURE(rc))
934 {
935 delete pDhcp;
936 return 1;
937 }
938
939 /*
940 * Process requests.
941 */
942 g_pDhcp = pDhcp;
943 rc = pDhcp->run();
944 g_pDhcp = NULL;
945 delete pDhcp;
946
947 return 0;
948}
949
950
951#ifndef VBOX_WITH_HARDENING
952
953int main(int argc, char **argv)
954{
955 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
956 if (RT_FAILURE(rc))
957 return RTMsgInitFailure(rc);
958
959 return TrustedMain(argc, argv);
960}
961
962# ifdef RT_OS_WINDOWS
963
964static LRESULT CALLBACK WindowProc(HWND hwnd,
965 UINT uMsg,
966 WPARAM wParam,
967 LPARAM lParam
968)
969{
970 if(uMsg == WM_DESTROY)
971 {
972 PostQuitMessage(0);
973 return 0;
974 }
975 return DefWindowProc (hwnd, uMsg, wParam, lParam);
976}
977
978static LPCWSTR g_WndClassName = L"VBoxNetDHCPClass";
979
980static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
981{
982 HWND hwnd = 0;
983 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
984 bool bExit = false;
985
986 /* Register the Window Class. */
987 WNDCLASS wc;
988 wc.style = 0;
989 wc.lpfnWndProc = WindowProc;
990 wc.cbClsExtra = 0;
991 wc.cbWndExtra = sizeof(void *);
992 wc.hInstance = hInstance;
993 wc.hIcon = NULL;
994 wc.hCursor = NULL;
995 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
996 wc.lpszMenuName = NULL;
997 wc.lpszClassName = g_WndClassName;
998
999 ATOM atomWindowClass = RegisterClass(&wc);
1000
1001 if (atomWindowClass != 0)
1002 {
1003 /* Create the window. */
1004 hwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1005 g_WndClassName, g_WndClassName,
1006 WS_POPUPWINDOW,
1007 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
1008
1009 if (hwnd)
1010 {
1011 SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
1012 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
1013
1014 MSG msg;
1015 while (GetMessage(&msg, NULL, 0, 0))
1016 {
1017 TranslateMessage(&msg);
1018 DispatchMessage(&msg);
1019 }
1020
1021 DestroyWindow (hwnd);
1022
1023 bExit = true;
1024 }
1025
1026 UnregisterClass (g_WndClassName, hInstance);
1027 }
1028
1029 if(bExit)
1030 {
1031 /* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
1032 exit(0);
1033 }
1034
1035 return 0;
1036}
1037
1038
1039/** (We don't want a console usually.) */
1040int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1041{
1042 NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
1043
1044 HANDLE hThread = CreateThread(
1045 NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
1046 0, /*__in SIZE_T dwStackSize, */
1047 MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
1048 NULL, /*__in_opt LPVOID lpParameter,*/
1049 0, /*__in DWORD dwCreationFlags,*/
1050 NULL /*__out_opt LPDWORD lpThreadId*/
1051 );
1052
1053 if(hThread != NULL)
1054 CloseHandle(hThread);
1055
1056 return main(__argc, __argv);
1057}
1058# endif /* RT_OS_WINDOWS */
1059
1060#endif /* !VBOX_WITH_HARDENING */
1061
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