VirtualBox

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

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

VBoxNetDHCP: nits.

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