VirtualBox

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

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

lwip-nat: DHCP using system wide definition INET_ADDSTRLEN, on Windows we redefine it to BSD/Posix style.

  • 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 48401 2013-09-10 11:34:05Z 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 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
415 memcpy(aszAddr, pszLo2Off, (pszTerm - pszLo2Off));
416 int rc = RTNetStrToIPv4Addr(aszAddr, &ip4addr);
417 if (RT_SUCCESS(rc))
418 {
419
420 u32Off = RTStrToUInt32(pszTerm + 1);
421 if (u32Off != 0)
422 MapIp4Addr2Off.insert(
423 std::map<RTNETADDRIPV4,uint32_t>::value_type(ip4addr, u32Off));
424 }
425 }
426 }
427 }
428
429 strs.setNull();
430 ComPtr<IHost> host;
431 if (SUCCEEDED(virtualbox->COMGETTER(Host)(host.asOutParam())))
432 {
433 if (SUCCEEDED(host->COMGETTER(NameServers)(ComSafeArrayAsOutParam(strs))))
434 {
435 RTNETADDRIPV4 addr;
436 confManager->flushAddressList(RTNET_DHCP_OPT_DNS);
437 int rc;
438 for (i = 0; i < strs.size(); ++i)
439 {
440 rc = RTNetStrToIPv4Addr(com::Utf8Str(strs[i]).c_str(), &addr);
441 if (RT_SUCCESS(rc))
442 {
443 if (addr.au8[0] == 127)
444 {
445 if (MapIp4Addr2Off[addr] != 0)
446 {
447 addr.u = RT_H2N_U32(RT_N2H_U32(m_Ipv4Address.u & m_Ipv4Netmask.u)
448 + MapIp4Addr2Off[addr]);
449 }
450 else
451 continue;
452 }
453
454 confManager->addToAddressList(RTNET_DHCP_OPT_DNS, addr);
455 }
456 }
457 }
458
459 strs.setNull();
460#if 0
461 if (SUCCEEDED(host->COMGETTER(SearchStrings)(ComSafeArrayAsOutParam(strs))))
462 {
463 /* XXX: todo. */;
464 }
465 strs.setNull();
466
467 Bstr domain;
468 if (SUCCEEDED(host->COMGETTER(DomainName)(domain.asOutPutParam())))
469 {
470 /* XXX: todo. */
471 }
472#endif
473 }
474 }
475
476 NetworkManager *netManager = NetworkManager::getNetworkManager();
477
478 netManager->setOurAddress(m_Ipv4Address);
479 netManager->setOurNetmask(m_Ipv4Netmask);
480 netManager->setOurMac(m_MacAddress);
481
482 /* Configuration fetching */
483 if (m_fIgnoreCmdLineParameters)
484 {
485 /* just fetch option array and add options to config */
486 /* per VM-settings ???
487 *
488 * - we have vms with attached adapters with known mac-addresses
489 * - mac-addresses might be changed as well as names, how keep our config cleaned ????
490 */
491 com::SafeArray<BSTR> sf;
492 hrc = m_DhcpServer->COMGETTER(GlobalOptions)(ComSafeArrayAsOutParam(sf));
493 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
494
495#if 0
496 for (int i = 0; i < sf.size(); ++i)
497 {
498 RTPrintf("%d: %s\n", i, com::Utf8Str(sf[i]).c_str());
499 }
500
501#endif
502 com::Bstr strUpperIp, strLowerIp;
503
504 RTNETADDRIPV4 LowerAddress;
505 RTNETADDRIPV4 UpperAddress;
506
507 hrc = m_DhcpServer->COMGETTER(UpperIP)(strUpperIp.asOutParam());
508 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
509 RTNetStrToIPv4Addr(com::Utf8Str(strUpperIp).c_str(), &UpperAddress);
510
511
512 hrc = m_DhcpServer->COMGETTER(LowerIP)(strLowerIp.asOutParam());
513 AssertComRCReturn(hrc, VERR_INTERNAL_ERROR);
514 RTNetStrToIPv4Addr(com::Utf8Str(strLowerIp).c_str(), &LowerAddress);
515
516 RTNETADDRIPV4 networkId;
517 networkId.u = m_Ipv4Address.u & m_Ipv4Netmask.u;
518 std::string name = std::string("default");
519
520 NetworkConfigEntity *pCfg = confManager->addNetwork(unconst(g_RootConfig),
521 networkId,
522 m_Ipv4Netmask,
523 LowerAddress,
524 UpperAddress);
525
526 } /* if(m_fIgnoreCmdLineParameters) */
527 else
528 {
529 CmdParameterIterator it;
530
531 RTNETADDRIPV4 networkId;
532 networkId.u = m_Ipv4Address.u & m_Ipv4Netmask.u;
533 RTNETADDRIPV4 netmask = m_Ipv4Netmask;
534 RTNETADDRIPV4 LowerAddress;
535 RTNETADDRIPV4 UpperAddress;
536
537 LowerAddress = networkId;
538 UpperAddress.u = RT_H2N_U32(RT_N2H_U32(LowerAddress.u) | RT_N2H_U32(netmask.u));
539
540 int idx = 0;
541 char name[64];
542
543
544 for (it = CmdParameterll.begin(); it != CmdParameterll.end(); ++it)
545 {
546 idx++;
547 RTStrPrintf(name, RT_ELEMENTS(name), "network-%d", idx);
548 std::string strname(name);
549
550 switch(it->Key)
551 {
552 case 'b':
553 /* config */
554 NetworkConfigEntity(strname,
555 g_RootConfig,
556 g_AnyClient,
557 5,
558 networkId,
559 netmask,
560 LowerAddress,
561 UpperAddress);
562 case 'l':
563 case 'u':
564 case 'm':
565 case 'g':
566 /* XXX: TBD */
567 break;
568 }
569 }
570 }
571 return VINF_SUCCESS;
572}
573
574/**
575 * Runs the DHCP server.
576 *
577 * @returns exit code + error message to stderr on failure, won't return on
578 * success (you must kill this process).
579 */
580int VBoxNetDhcp::run(void)
581{
582
583 /* XXX: shortcut should be hidden from network manager */
584 NetworkManager *netManager = NetworkManager::getNetworkManager();
585 netManager->m_pSession = m_pSession;
586 netManager->m_hIf = m_hIf;
587 netManager->m_pIfBuf = m_pIfBuf;
588
589 /*
590 * The loop.
591 */
592 PINTNETRINGBUF pRingBuf = &m_pIfBuf->Recv;
593 for (;;)
594 {
595 /*
596 * Wait for a packet to become available.
597 */
598 INTNETIFWAITREQ WaitReq;
599 WaitReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
600 WaitReq.Hdr.cbReq = sizeof(WaitReq);
601 WaitReq.pSession = m_pSession;
602 WaitReq.hIf = m_hIf;
603 WaitReq.cMillies = 2000; /* 2 secs - the sleep is for some reason uninterruptible... */ /** @todo fix interruptability in SrvIntNet! */
604 int rc = SUPR3CallVMMR0Ex(NIL_RTR0PTR, NIL_VMCPUID, VMMR0_DO_INTNET_IF_WAIT, 0, &WaitReq.Hdr);
605 if (RT_FAILURE(rc))
606 {
607 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED)
608 continue;
609 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: VMMR0_DO_INTNET_IF_WAIT returned %Rrc\n", rc);
610 return 1;
611 }
612
613 /*
614 * Process the receive buffer.
615 */
616 while (IntNetRingHasMoreToRead(pRingBuf))
617 {
618 size_t cb;
619 void *pv = VBoxNetUDPMatch(m_pIfBuf, RTNETIPV4_PORT_BOOTPS, &m_MacAddress,
620 VBOXNETUDP_MATCH_UNICAST | VBOXNETUDP_MATCH_BROADCAST | VBOXNETUDP_MATCH_CHECKSUM
621 | (m_cVerbosity > 2 ? VBOXNETUDP_MATCH_PRINT_STDERR : 0),
622 &m_CurHdrs, &cb);
623 if (pv && cb)
624 {
625 PCRTNETBOOTP pDhcpMsg = (PCRTNETBOOTP)pv;
626 m_pCurMsg = pDhcpMsg;
627 m_cbCurMsg = cb;
628
629 uint8_t uMsgType;
630 if (RTNetIPv4IsDHCPValid(NULL /* why is this here? */, pDhcpMsg, cb, &uMsgType))
631 {
632 m_uCurMsgType = uMsgType;
633 handleDhcpMsg(uMsgType, pDhcpMsg, cb);
634 m_uCurMsgType = UINT8_MAX;
635 }
636 else
637 debugPrint(1, true, "VBoxNetDHCP: Skipping invalid DHCP packet.\n"); /** @todo handle pure bootp clients too? */
638
639 m_pCurMsg = NULL;
640 m_cbCurMsg = 0;
641 }
642 else if (VBoxNetArpHandleIt(m_pSession, m_hIf, m_pIfBuf, &m_MacAddress, m_Ipv4Address))
643 {
644 /* nothing */
645 }
646
647 /* Advance to the next frame. */
648 IntNetRingSkipFrame(pRingBuf);
649 }
650 }
651
652 return 0;
653}
654
655
656/**
657 * Handles a DHCP message.
658 *
659 * @returns true if handled, false if not.
660 * @param uMsgType The message type.
661 * @param pDhcpMsg The DHCP message.
662 * @param cb The size of the DHCP message.
663 */
664bool VBoxNetDhcp::handleDhcpMsg(uint8_t uMsgType, PCRTNETBOOTP pDhcpMsg, size_t cb)
665{
666 if (pDhcpMsg->bp_op == RTNETBOOTP_OP_REQUEST)
667 {
668 switch (uMsgType)
669 {
670 case RTNET_DHCP_MT_DISCOVER:
671 return handleDhcpReqDiscover(pDhcpMsg, cb);
672
673 case RTNET_DHCP_MT_REQUEST:
674 return handleDhcpReqRequest(pDhcpMsg, cb);
675
676 case RTNET_DHCP_MT_DECLINE:
677 return handleDhcpReqDecline(pDhcpMsg, cb);
678
679 case RTNET_DHCP_MT_RELEASE:
680 return handleDhcpReqRelease(pDhcpMsg, cb);
681
682 case RTNET_DHCP_MT_INFORM:
683 debugPrint(0, true, "Should we handle this?");
684 break;
685
686 default:
687 debugPrint(0, true, "Unexpected.");
688 break;
689 }
690 }
691 return false;
692}
693
694
695/**
696 * The client is requesting an offer.
697 *
698 * @returns true.
699 *
700 * @param pDhcpMsg The message.
701 * @param cb The message size.
702 */
703bool VBoxNetDhcp::handleDhcpReqDiscover(PCRTNETBOOTP pDhcpMsg, size_t cb)
704{
705
706 /* let's main first */
707 if (!m_DhcpServer.isNull())
708 {
709#if 0
710 HRESULT hrc;
711 com::SafeArray<BSTR> sf;
712 hrc = m_DhcpServer->GetMacOptions(com::BstrFmt("%02X%02X%02X%02X%02X%02X",
713 pDhcpMsg->bp_chaddr.Mac.au8[0],
714 pDhcpMsg->bp_chaddr.Mac.au8[1],
715 pDhcpMsg->bp_chaddr.Mac.au8[2],
716 pDhcpMsg->bp_chaddr.Mac.au8[3],
717 pDhcpMsg->bp_chaddr.Mac.au8[4],
718 pDhcpMsg->bp_chaddr.Mac.au8[5]).raw(),
719 ComSafeArrayAsOutParam(sf));
720 if (SUCCEEDED(hrc))
721 {
722 /* XXX: per-host configuration */
723 }
724#endif
725 RawOption opt;
726 memset(&opt, 0, sizeof(RawOption));
727 /* 1. Find client */
728 ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();
729 Client *client = confManager->getClientByDhcpPacket(pDhcpMsg, cb);
730
731 /* 2. Find/Bind lease for client */
732 Lease *lease = confManager->allocateLease4Client(client, pDhcpMsg, cb);
733 AssertPtrReturn(lease, VINF_SUCCESS);
734
735 int rc = ConfigurationManager::extractRequestList(pDhcpMsg, cb, opt);
736
737 /* 3. Send of offer */
738 NetworkManager *networkManager = NetworkManager::getNetworkManager();
739
740 lease->fBinding = true;
741 lease->u64TimestampBindingStarted = RTTimeMilliTS();
742 lease->u32BindExpirationPeriod = 300; /* 3 min. */
743 networkManager->offer4Client(client, pDhcpMsg->bp_xid, opt.au8RawOpt, opt.cbRawOpt);
744 } /* end of if(!m_DhcpServer.isNull()) */
745
746 return VINF_SUCCESS;
747}
748
749
750/**
751 * The client is requesting an offer.
752 *
753 * @returns true.
754 *
755 * @param pDhcpMsg The message.
756 * @param cb The message size.
757 */
758bool VBoxNetDhcp::handleDhcpReqRequest(PCRTNETBOOTP pDhcpMsg, size_t cb)
759{
760 ConfigurationManager *confManager = ConfigurationManager::getConfigurationManager();
761 NetworkManager *networkManager = NetworkManager::getNetworkManager();
762
763 /* 1. find client */
764 Client *client = confManager->getClientByDhcpPacket(pDhcpMsg, cb);
765
766 /* 2. find bound lease */
767 if (client->m_lease)
768 {
769
770 if (client->m_lease->isExpired())
771 {
772 /* send client to INIT state */
773 networkManager->nak(client, pDhcpMsg->bp_xid);
774 confManager->expireLease4Client(client);
775 return true;
776 }
777 /* XXX: Validate request */
778 RawOption opt;
779 memset((void *)&opt, 0, sizeof(RawOption));
780
781 int rc = confManager->commitLease4Client(client);
782 AssertRCReturn(rc, false);
783
784 rc = ConfigurationManager::extractRequestList(pDhcpMsg, cb, opt);
785 AssertRCReturn(rc, false);
786
787 networkManager->ack(client, pDhcpMsg->bp_xid, opt.au8RawOpt, opt.cbRawOpt);
788 }
789 else
790 {
791 networkManager->nak(client, pDhcpMsg->bp_xid);
792 }
793 return true;
794}
795
796
797/**
798 * The client is declining an offer we've made.
799 *
800 * @returns true.
801 *
802 * @param pDhcpMsg The message.
803 * @param cb The message size.
804 */
805bool VBoxNetDhcp::handleDhcpReqDecline(PCRTNETBOOTP pDhcpMsg, size_t cb)
806{
807 /** @todo Probably need to match the server IP here to work correctly with
808 * other servers. */
809
810 /*
811 * The client is supposed to pass us option 50, requested address,
812 * from the offer. We also match the lease state. Apparently the
813 * MAC address is not supposed to be checked here.
814 */
815
816 /** @todo this is not required in the initial implementation, do it later. */
817 debugPrint(1, true, "DECLINE is not implemented");
818 return true;
819}
820
821
822/**
823 * The client is releasing its lease - good boy.
824 *
825 * @returns true.
826 *
827 * @param pDhcpMsg The message.
828 * @param cb The message size.
829 */
830bool VBoxNetDhcp::handleDhcpReqRelease(PCRTNETBOOTP pDhcpMsg, size_t cb)
831{
832 /** @todo Probably need to match the server IP here to work correctly with
833 * other servers. */
834
835 /*
836 * The client may pass us option 61, client identifier, which we should
837 * use to find the lease by.
838 *
839 * We're matching MAC address and lease state as well.
840 */
841
842 /*
843 * If no client identifier or if we couldn't find a lease by using it,
844 * we will try look it up by the client IP address.
845 */
846
847
848 /*
849 * If found, release it.
850 */
851
852
853 /** @todo this is not required in the initial implementation, do it later. */
854 debugPrint(1, true, "RELEASE is not implemented");
855 return true;
856}
857
858
859/**
860 * Print debug message depending on the m_cVerbosity level.
861 *
862 * @param iMinLevel The minimum m_cVerbosity level for this message.
863 * @param fMsg Whether to dump parts for the current DHCP message.
864 * @param pszFmt The message format string.
865 * @param va Optional arguments.
866 */
867void VBoxNetDhcp::debugPrintV(int iMinLevel, bool fMsg, const char *pszFmt, va_list va) const
868{
869 if (iMinLevel <= m_cVerbosity)
870 {
871 va_list vaCopy; /* This dude is *very* special, thus the copy. */
872 va_copy(vaCopy, va);
873 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: %s: %N\n", iMinLevel >= 2 ? "debug" : "info", pszFmt, &vaCopy);
874 va_end(vaCopy);
875
876 if ( fMsg
877 && m_cVerbosity >= 2
878 && m_pCurMsg)
879 {
880 /* XXX: export this to debugPrinfDhcpMsg or variant and other method export
881 * to base class
882 */
883 const char *pszMsg = m_uCurMsgType != UINT8_MAX ? debugDhcpName(m_uCurMsgType) : "";
884 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",
885 pszMsg,
886 &m_pCurMsg->bp_chaddr,
887 m_pCurMsg->bp_ciaddr.au8[0], m_pCurMsg->bp_ciaddr.au8[1], m_pCurMsg->bp_ciaddr.au8[2], m_pCurMsg->bp_ciaddr.au8[3],
888 m_pCurMsg->bp_yiaddr.au8[0], m_pCurMsg->bp_yiaddr.au8[1], m_pCurMsg->bp_yiaddr.au8[2], m_pCurMsg->bp_yiaddr.au8[3],
889 m_pCurMsg->bp_siaddr.au8[0], m_pCurMsg->bp_siaddr.au8[1], m_pCurMsg->bp_siaddr.au8[2], m_pCurMsg->bp_siaddr.au8[3],
890 m_pCurMsg->bp_xid);
891 }
892 }
893}
894
895
896/**
897 * Gets the name of given DHCP message type.
898 *
899 * @returns Readonly name.
900 * @param uMsgType The message number.
901 */
902/* static */ const char *VBoxNetDhcp::debugDhcpName(uint8_t uMsgType)
903{
904 switch (uMsgType)
905 {
906 case 0: return "MT_00";
907 case RTNET_DHCP_MT_DISCOVER: return "DISCOVER";
908 case RTNET_DHCP_MT_OFFER: return "OFFER";
909 case RTNET_DHCP_MT_REQUEST: return "REQUEST";
910 case RTNET_DHCP_MT_DECLINE: return "DECLINE";
911 case RTNET_DHCP_MT_ACK: return "ACK";
912 case RTNET_DHCP_MT_NAC: return "NAC";
913 case RTNET_DHCP_MT_RELEASE: return "RELEASE";
914 case RTNET_DHCP_MT_INFORM: return "INFORM";
915 case 9: return "MT_09";
916 case 10: return "MT_0a";
917 case 11: return "MT_0b";
918 case 12: return "MT_0c";
919 case 13: return "MT_0d";
920 case 14: return "MT_0e";
921 case 15: return "MT_0f";
922 case 16: return "MT_10";
923 case 17: return "MT_11";
924 case 18: return "MT_12";
925 case 19: return "MT_13";
926 case UINT8_MAX: return "MT_ff";
927 default: return "UNKNOWN";
928 }
929}
930
931
932
933/**
934 * Entry point.
935 */
936extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
937{
938 /*
939 * Instantiate the DHCP server and hand it the options.
940 */
941 HRESULT hrc = com::Initialize();
942 Assert(!FAILED(hrc));
943
944 VBoxNetDhcp *pDhcp = new VBoxNetDhcp();
945 if (!pDhcp)
946 {
947 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: new VBoxNetDhcp failed!\n");
948 return 1;
949 }
950 int rc = pDhcp->parseArgs(argc - 1, argv + 1);
951 if (rc)
952 return rc;
953
954 pDhcp->init();
955
956 /*
957 * Try connect the server to the network.
958 */
959 rc = pDhcp->tryGoOnline();
960 if (rc)
961 {
962 delete pDhcp;
963 return rc;
964 }
965
966 /*
967 * Process requests.
968 */
969 g_pDhcp = pDhcp;
970 rc = pDhcp->run();
971 g_pDhcp = NULL;
972 delete pDhcp;
973
974 return rc;
975}
976
977
978#ifndef VBOX_WITH_HARDENING
979
980int main(int argc, char **argv, char **envp)
981{
982 int rc = RTR3InitExe(argc, &argv, RTR3INIT_FLAGS_SUPLIB);
983 if (RT_FAILURE(rc))
984 return RTMsgInitFailure(rc);
985
986 return TrustedMain(argc, argv, envp);
987}
988
989# ifdef RT_OS_WINDOWS
990
991static LRESULT CALLBACK WindowProc(HWND hwnd,
992 UINT uMsg,
993 WPARAM wParam,
994 LPARAM lParam
995)
996{
997 if(uMsg == WM_DESTROY)
998 {
999 PostQuitMessage(0);
1000 return 0;
1001 }
1002 return DefWindowProc (hwnd, uMsg, wParam, lParam);
1003}
1004
1005static LPCWSTR g_WndClassName = L"VBoxNetDHCPClass";
1006
1007static DWORD WINAPI MsgThreadProc(__in LPVOID lpParameter)
1008{
1009 HWND hwnd = 0;
1010 HINSTANCE hInstance = (HINSTANCE)GetModuleHandle (NULL);
1011 bool bExit = false;
1012
1013 /* Register the Window Class. */
1014 WNDCLASS wc;
1015 wc.style = 0;
1016 wc.lpfnWndProc = WindowProc;
1017 wc.cbClsExtra = 0;
1018 wc.cbWndExtra = sizeof(void *);
1019 wc.hInstance = hInstance;
1020 wc.hIcon = NULL;
1021 wc.hCursor = NULL;
1022 wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND + 1);
1023 wc.lpszMenuName = NULL;
1024 wc.lpszClassName = g_WndClassName;
1025
1026 ATOM atomWindowClass = RegisterClass(&wc);
1027
1028 if (atomWindowClass != 0)
1029 {
1030 /* Create the window. */
1031 hwnd = CreateWindowEx (WS_EX_TOOLWINDOW | WS_EX_TRANSPARENT | WS_EX_TOPMOST,
1032 g_WndClassName, g_WndClassName,
1033 WS_POPUPWINDOW,
1034 -200, -200, 100, 100, NULL, NULL, hInstance, NULL);
1035
1036 if (hwnd)
1037 {
1038 SetWindowPos(hwnd, HWND_TOPMOST, -200, -200, 0, 0,
1039 SWP_NOACTIVATE | SWP_HIDEWINDOW | SWP_NOCOPYBITS | SWP_NOREDRAW | SWP_NOSIZE);
1040
1041 MSG msg;
1042 while (GetMessage(&msg, NULL, 0, 0))
1043 {
1044 TranslateMessage(&msg);
1045 DispatchMessage(&msg);
1046 }
1047
1048 DestroyWindow (hwnd);
1049
1050 bExit = true;
1051 }
1052
1053 UnregisterClass (g_WndClassName, hInstance);
1054 }
1055
1056 if(bExit)
1057 {
1058 /* no need any accuracy here, in anyway the DHCP server usually gets terminated with TerminateProcess */
1059 exit(0);
1060 }
1061
1062 return 0;
1063}
1064
1065
1066/** (We don't want a console usually.) */
1067int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
1068{
1069 NOREF(hInstance); NOREF(hPrevInstance); NOREF(lpCmdLine); NOREF(nCmdShow);
1070
1071 HANDLE hThread = CreateThread(
1072 NULL, /*__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, */
1073 0, /*__in SIZE_T dwStackSize, */
1074 MsgThreadProc, /*__in LPTHREAD_START_ROUTINE lpStartAddress,*/
1075 NULL, /*__in_opt LPVOID lpParameter,*/
1076 0, /*__in DWORD dwCreationFlags,*/
1077 NULL /*__out_opt LPDWORD lpThreadId*/
1078 );
1079
1080 if(hThread != NULL)
1081 CloseHandle(hThread);
1082
1083 return main(__argc, __argv, environ);
1084}
1085# endif /* RT_OS_WINDOWS */
1086
1087#endif /* !VBOX_WITH_HARDENING */
1088
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