VirtualBox

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

Last change on this file since 17883 was 17864, checked in by vboxsync, 16 years ago

VBoxNetDHCP: A couple of more options for configuring the trunk.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 62.9 KB
Line 
1/* $Id: VBoxNetDHCP.cpp 17864 2009-03-13 23:04:21Z vboxsync $ */
2/** @file
3 * VBoxNetDHCP - DHCP Service for connecting to IntNet.
4 */
5
6/*
7 * Copyright (C) 2009 Sun Microsystems, Inc.
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 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
18 * Clara, CA 95054 USA or visit http://www.sun.com if you need
19 * additional information or have any questions.
20 */
21
22/** @page pg_net_dhcp VBoxNetDHCP
23 *
24 * Write a few words...
25 *
26 */
27
28/*******************************************************************************
29* Header Files *
30*******************************************************************************/
31#include <iprt/net.h>
32#include <iprt/initterm.h>
33#include <iprt/alloca.h>
34#include <iprt/err.h>
35#include <iprt/time.h>
36#include <iprt/stream.h>
37#include <iprt/path.h>
38#include <iprt/param.h>
39#include <iprt/getopt.h>
40#include <iprt/string.h>
41
42#include <VBox/sup.h>
43#include <VBox/intnet.h>
44#include <VBox/vmm.h>
45#include <VBox/version.h>
46
47#include "../NetLib/VBoxNetLib.h"
48
49#include <vector>
50#include <string>
51
52
53/*******************************************************************************
54* Structures and Typedefs *
55*******************************************************************************/
56
57/**
58 * DHCP configuration item.
59 *
60 * This is all public data because I'm too lazy to do it propertly right now.
61 */
62class VBoxNetDhcpCfg
63{
64public:
65 /** The etheret addresses this matches config applies to.
66 * An empty vector means 'ANY'. */
67 std::vector<RTMAC> m_MacAddresses;
68 /** The upper address in the range. */
69 RTNETADDRIPV4 m_UpperAddr;
70 /** The lower address in the range. */
71 RTNETADDRIPV4 m_LowerAddr;
72
73 /** Option 1: The net mask. */
74 RTNETADDRIPV4 m_SubnetMask;
75 /* * Option 2: The time offset. */
76 /** Option 3: Routers for the subnet. */
77 std::vector<RTNETADDRIPV4> m_Routers;
78 /* * Option 4: Time server. */
79 /* * Option 5: Name server. */
80 /** Option 6: Domain Name Server (DNS) */
81 std::vector<RTNETADDRIPV4> m_DNSes;
82 /* * Option 7: Log server. */
83 /* * Option 8: Cookie server. */
84 /* * Option 9: LPR server. */
85 /* * Option 10: Impress server. */
86 /* * Option 11: Resource location server. */
87 /* * Option 12: Host name. */
88 std::string m_HostName;
89 /* * Option 13: Boot file size option. */
90 /* * Option 14: Merit dump file. */
91 /** Option 15: Domain name. */
92 std::string m_DomainName;
93 /* * Option 16: Swap server. */
94 /* * Option 17: Root path. */
95 /* * Option 18: Extension path. */
96 /* * Option 19: IP forwarding enable/disable. */
97 /* * Option 20: Non-local routing enable/disable. */
98 /* * Option 21: Policy filter. */
99 /* * Option 22: Maximum datagram reassembly size (MRS). */
100 /* * Option 23: Default IP time-to-live. */
101 /* * Option 24: Path MTU aging timeout. */
102 /* * Option 25: Path MTU plateau table. */
103 /* * Option 26: Interface MTU. */
104 /* * Option 27: All subnets are local. */
105 /* * Option 28: Broadcast address. */
106 /* * Option 29: Perform maximum discovery. */
107 /* * Option 30: Mask supplier. */
108 /* * Option 31: Perform route discovery. */
109 /* * Option 32: Router solicitation address. */
110 /* * Option 33: Static route. */
111 /* * Option 34: Trailer encapsulation. */
112 /* * Option 35: ARP cache timeout. */
113 /* * Option 36: Ethernet encapsulation. */
114 /* * Option 37: TCP Default TTL. */
115 /* * Option 38: TCP Keepalive Interval. */
116 /* * Option 39: TCP Keepalive Garbage. */
117 /* * Option 40: Network Information Service (NIS) Domain. */
118 /* * Option 41: Network Information Servers. */
119 /* * Option 42: Network Time Protocol Servers. */
120 /* * Option 43: Vendor Specific Information. */
121 /* * Option 44: NetBIOS over TCP/IP Name Server (NBNS). */
122 /* * Option 45: NetBIOS over TCP/IP Datagram distribution Server (NBDD). */
123 /* * Option 46: NetBIOS over TCP/IP Node Type. */
124 /* * Option 47: NetBIOS over TCP/IP Scope. */
125 /* * Option 48: X Window System Font Server. */
126 /* * Option 49: X Window System Display Manager. */
127
128 /** Option 51: IP Address Lease Time. */
129 uint32_t m_cSecLease;
130
131 /* * Option 64: Network Information Service+ Domain. */
132 /* * Option 65: Network Information Service+ Servers. */
133 /** Option 66: TFTP server name. */
134 std::string m_TftpServer;
135 /** Address for the bp_siaddr field corresponding to m_TftpServer. */
136 RTNETADDRIPV4 m_TftpServerAddr;
137 /** Option 67: Bootfile name. */
138 std::string m_BootfileName;
139
140 /* * Option 68: Mobile IP Home Agent. */
141 /* * Option 69: Simple Mail Transport Protocol (SMPT) Server. */
142 /* * Option 70: Post Office Protocol (POP3) Server. */
143 /* * Option 71: Network News Transport Protocol (NNTP) Server. */
144 /* * Option 72: Default World Wide Web (WWW) Server. */
145 /* * Option 73: Default Finger Server. */
146 /* * Option 74: Default Internet Relay Chat (IRC) Server. */
147 /* * Option 75: StreetTalk Server. */
148
149 /* * Option 119: Domain Search. */
150
151
152 VBoxNetDhcpCfg()
153 {
154 m_UpperAddr.u = UINT32_MAX;
155 m_LowerAddr.u = UINT32_MAX;
156 m_SubnetMask.u = UINT32_MAX;
157 m_cSecLease = 60*60; /* 1 hour */
158 }
159
160 /** Validates the configuration.
161 * @returns 0 on success, exit code + error message to stderr on failure. */
162 int validate(void)
163 {
164 if ( m_UpperAddr.u == UINT32_MAX
165 || m_LowerAddr.u == UINT32_MAX
166 || m_SubnetMask.u == UINT32_MAX)
167 {
168 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: Config is missing:");
169 if (m_UpperAddr.u == UINT32_MAX)
170 RTStrmPrintf(g_pStdErr, " --upper-ip");
171 if (m_LowerAddr.u == UINT32_MAX)
172 RTStrmPrintf(g_pStdErr, " --lower-ip");
173 if (m_SubnetMask.u == UINT32_MAX)
174 RTStrmPrintf(g_pStdErr, " --netmask");
175 return 2;
176 }
177
178 if (RT_N2H_U32(m_UpperAddr.u) < RT_N2H_U32(m_LowerAddr.u))
179 {
180 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: The --upper-ip value is lower than the --lower-ip one!\n"
181 " %d.%d.%d.%d < %d.%d.%d.%d\n",
182 m_UpperAddr.au8[0], m_UpperAddr.au8[1], m_UpperAddr.au8[2], m_UpperAddr.au8[3],
183 m_LowerAddr.au8[0], m_LowerAddr.au8[1], m_LowerAddr.au8[2], m_LowerAddr.au8[3]);
184 return 3;
185 }
186
187 /* the code goes insane if we have too many atm. lazy bird */
188 uint32_t cIPs = RT_N2H_U32(m_UpperAddr.u) - RT_N2H_U32(m_LowerAddr.u);
189 if (cIPs > 1024)
190 {
191 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: Too many IPs between --upper-ip and --lower-ip! %d (max 1024)\n"
192 " %d.%d.%d.%d < %d.%d.%d.%d\n",
193 cIPs,
194 m_UpperAddr.au8[0], m_UpperAddr.au8[1], m_UpperAddr.au8[2], m_UpperAddr.au8[3],
195 m_LowerAddr.au8[0], m_LowerAddr.au8[1], m_LowerAddr.au8[2], m_LowerAddr.au8[3]);
196 return 3;
197 }
198 return 0;
199 }
200
201 /**
202 * Is this config for one specific client?
203 *
204 * @return true / false.
205 */
206 bool isOneSpecificClient(void) const
207 {
208 return m_LowerAddr.u == m_UpperAddr.u
209 && m_MacAddresses.size() > 0;
210 }
211
212 /**
213 * Checks if this config matches the specified MAC address.
214 *
215 * @returns true / false.
216 *
217 * @param pMac The MAC address to match.
218 */
219 bool matchesMacAddress(PCRTMAC pMac) const
220 {
221 size_t i = m_MacAddresses.size();
222 if (RT_LIKELY(i < 1))
223 return true; /* no entries == ALL wildcard match */
224
225 while (i--)
226 {
227 PCRTMAC pCur = &m_MacAddresses[i];
228 if ( pCur->au16[0] == pMac->au16[0]
229 && pCur->au16[1] == pMac->au16[1]
230 && pCur->au16[2] == pMac->au16[2])
231 return true;
232 }
233 return false;
234 }
235
236};
237
238/**
239 * DHCP lease.
240 */
241class VBoxNetDhcpLease
242{
243public:
244 typedef enum State
245 {
246 /** Invalid. */
247 kState_Invalid = 0,
248 /** The lease is free / released. */
249 kState_Free,
250 /** An offer has been made.
251 * Expire time indicates when the offer expires. */
252 kState_Offer,
253 /** The lease is active.
254 * Expire time indicates when the lease expires. */
255 kState_Active
256 } State;
257
258 /** The client MAC address. */
259 RTMAC m_MacAddress;
260 /** The IPv4 address. */
261 RTNETADDRIPV4 m_IPv4Address;
262
263 /** The current lease state. */
264 State m_enmState;
265 /** The lease expiration time. */
266 RTTIMESPEC m_ExpireTime;
267 /** Transaction ID. */
268 uint32_t m_xid;
269 /** The configuration for this lease. */
270 VBoxNetDhcpCfg *m_pCfg;
271
272public:
273 /** Constructor taking an IPv4 address and a Config. */
274 VBoxNetDhcpLease(RTNETADDRIPV4 IPv4Addr, VBoxNetDhcpCfg *pCfg)
275 {
276 m_pCfg = pCfg;
277 m_IPv4Address = IPv4Addr;
278
279 m_MacAddress.au16[0] = m_MacAddress.au16[1] = m_MacAddress.au16[2] = 0xff;
280 m_enmState = kState_Free;
281 RTTimeSpecSetSeconds(&m_ExpireTime, 0);
282 m_xid = UINT32_MAX;
283 }
284
285 /** Destructor. */
286 ~VBoxNetDhcpLease()
287 {
288 m_IPv4Address.u = UINT32_MAX;
289 m_pCfg = NULL;
290 m_MacAddress.au16[0] = m_MacAddress.au16[1] = m_MacAddress.au16[2] = 0xff;
291 m_enmState = kState_Free;
292 m_xid = UINT32_MAX;
293 }
294
295 void offer(uint32_t xid);
296 void activate(void);
297 void activate(uint32_t xid);
298 void release(void);
299 bool hasExpired(void) const;
300
301 /**
302 * Checks if the lease is in use or not.
303 *
304 * @returns true if active, false if free or expired.
305 *
306 * @param pNow The current time to use. Optional.
307 */
308 bool isInUse(PCRTTIMESPEC pNow = NULL) const
309 {
310 if ( m_enmState == kState_Offer
311 || m_enmState == kState_Active)
312 {
313 RTTIMESPEC Now;
314 if (!pNow)
315 pNow = RTTimeNow(&Now);
316 return RTTimeSpecGetSeconds(&m_ExpireTime) > RTTimeSpecGetSeconds(pNow);
317 }
318 return false;
319 }
320
321 /**
322 * Is this lease for one specific client?
323 *
324 * @return true/false.
325 */
326 bool isOneSpecificClient(void) const
327 {
328 return m_pCfg
329 && m_pCfg->isOneSpecificClient();
330 }
331
332 /**
333 * Is this lease currently being offered to a client.
334 *
335 * @returns true / false.
336 */
337 bool isBeingOffered(void) const
338 {
339 return m_enmState == kState_Offer
340 && isInUse();
341 }
342
343 /**
344 * Is the lease in the current config or not.
345 *
346 * When updating the config we might leave active leases behind which aren't
347 * included in the new config. These will have m_pCfg set to NULL and should be
348 * freed up when they expired.
349 *
350 * @returns true / false.
351 */
352 bool isInCurrentConfig(void) const
353 {
354 return m_pCfg != NULL;
355 }
356};
357
358/**
359 * DHCP server instance.
360 */
361class VBoxNetDhcp
362{
363public:
364 VBoxNetDhcp();
365 virtual ~VBoxNetDhcp();
366
367 int parseArgs(int argc, char **argv);
368 int tryGoOnline(void);
369 int run(void);
370
371protected:
372 int addConfig(VBoxNetDhcpCfg *pCfg);
373 void explodeConfig(void);
374
375 bool handleDhcpMsg(uint8_t uMsgType, PCRTNETBOOTP pDhcpMsg, size_t cb);
376 bool handleDhcpReqDiscover(PCRTNETBOOTP pDhcpMsg, size_t cb);
377 bool handleDhcpReqRequest(PCRTNETBOOTP pDhcpMsg, size_t cb);
378 bool handleDhcpReqDecline(PCRTNETBOOTP pDhcpMsg, size_t cb);
379 bool handleDhcpReqRelease(PCRTNETBOOTP pDhcpMsg, size_t cb);
380 void makeDhcpReply(uint8_t uMsgType, VBoxNetDhcpLease *pLease, PCRTNETBOOTP pDhcpMsg, size_t cb);
381
382 VBoxNetDhcpLease *findLeaseByMacAddress(PCRTMAC pMacAddress, bool fAnyState);
383 VBoxNetDhcpLease *findLeaseByIpv4AndMacAddresses(RTNETADDRIPV4 IPv4Addr, PCRTMAC pMacAddress, bool fAnyState);
384 VBoxNetDhcpLease *newLease(PCRTNETBOOTP pDhcpMsg, size_t cb);
385
386 static uint8_t const *findOption(uint8_t uOption, PCRTNETBOOTP pDhcpMsg, size_t cb, size_t *pcbMaxOpt);
387 static bool findOptionIPv4Addr(uint8_t uOption, PCRTNETBOOTP pDhcpMsg, size_t cb, PRTNETADDRIPV4 pIPv4Addr);
388
389 inline void debugPrint( int32_t iMinLevel, bool fMsg, const char *pszFmt, ...) const;
390 void debugPrintV(int32_t iMinLevel, bool fMsg, const char *pszFmt, va_list va) const;
391 static const char *debugDhcpName(uint8_t uMsgType);
392
393protected:
394 /** @name The server configuration data members.
395 * @{ */
396 std::string m_Name;
397 std::string m_Network;
398 std::string m_TrunkName;
399 INTNETTRUNKTYPE m_enmTrunkType;
400 RTMAC m_MacAddress;
401 RTNETADDRIPV4 m_Ipv4Address;
402 std::string m_LeaseDBName;
403 /** @} */
404
405 /** The current configs. */
406 std::vector<VBoxNetDhcpCfg *> m_Cfgs;
407
408 /** The current leases. */
409 std::vector<VBoxNetDhcpLease> m_Leases;
410
411 /** @name The network interface
412 * @{ */
413 PSUPDRVSESSION m_pSession;
414 uint32_t m_cbSendBuf;
415 uint32_t m_cbRecvBuf;
416 INTNETIFHANDLE m_hIf; /**< The handle to the network interface. */
417 PINTNETBUF m_pIfBuf; /**< Interface buffer. */
418 /** @} */
419
420 /** @name Debug stuff
421 * @{ */
422 int32_t m_cVerbosity;
423 uint8_t m_uCurMsgType;
424 uint16_t m_cbCurMsg;
425 PCRTNETBOOTP m_pCurMsg;
426 VBOXNETUDPHDRS m_CurHdrs;
427 /** @} */
428};
429
430
431/*******************************************************************************
432* Global Variables *
433*******************************************************************************/
434/** Pointer to the DHCP server. */
435static VBoxNetDhcp *g_pDhcp;
436
437
438/**
439 * Offer this lease to a client.
440 *
441 * @param xid The transaction ID.
442 */
443void VBoxNetDhcpLease::offer(uint32_t xid)
444{
445 m_enmState = kState_Offer;
446 m_xid = xid;
447 RTTimeNow(&m_ExpireTime);
448 RTTimeSpecAddSeconds(&m_ExpireTime, 60);
449}
450
451
452/**
453 * Activate this lease (i.e. a client is now using it).
454 */
455void VBoxNetDhcpLease::activate(void)
456{
457 m_enmState = kState_Active;
458 RTTimeNow(&m_ExpireTime);
459 RTTimeSpecAddSeconds(&m_ExpireTime, m_pCfg ? m_pCfg->m_cSecLease : 60); /* m_pCfg can be NULL right now... */
460}
461
462
463/**
464 * Activate this lease with a new transaction ID.
465 *
466 * @param xid The transaction ID.
467 * @todo check if this is really necessary.
468 */
469void VBoxNetDhcpLease::activate(uint32_t xid)
470{
471 activate();
472 m_xid = xid;
473}
474
475
476/**
477 * Release a lease either upon client request or because it didn't quite match a
478 * DHCP_REQUEST.
479 */
480void VBoxNetDhcpLease::release(void)
481{
482 m_enmState = kState_Free;
483 RTTimeNow(&m_ExpireTime);
484 RTTimeSpecAddSeconds(&m_ExpireTime, 5);
485}
486
487
488/**
489 * Checks if the lease has expired or not.
490 *
491 * This just checks the expiration time not the state. This is so that this
492 * method will work for reusing RELEASEd leases when the client comes back after
493 * a reboot or ipconfig /renew. Callers not interested in info on released
494 * leases should check the state first.
495 *
496 * @returns true if expired, false if not.
497 */
498bool VBoxNetDhcpLease::hasExpired() const
499{
500 RTTIMESPEC Now;
501 return RTTimeSpecGetSeconds(&m_ExpireTime) > RTTimeSpecGetSeconds(RTTimeNow(&Now));
502}
503
504
505
506
507/**
508 * Construct a DHCP server with a default configuration.
509 */
510VBoxNetDhcp::VBoxNetDhcp()
511{
512 m_Name = "VBoxNetDhcp";
513 m_Network = "VBoxNetDhcp";
514 m_TrunkName = "";
515 m_enmTrunkType = kIntNetTrunkType_WhateverNone;
516 m_MacAddress.au8[0] = 0x08;
517 m_MacAddress.au8[1] = 0x00;
518 m_MacAddress.au8[2] = 0x27;
519 m_MacAddress.au8[3] = 0x40;
520 m_MacAddress.au8[4] = 0x41;
521 m_MacAddress.au8[5] = 0x42;
522 m_Ipv4Address.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2, 5)));
523
524 m_pSession = NIL_RTR0PTR;
525 m_cbSendBuf = 8192;
526 m_cbRecvBuf = 51200; /** @todo tune to 64 KB with help from SrvIntR0 */
527 m_hIf = INTNET_HANDLE_INVALID;
528 m_pIfBuf = NULL;
529
530 m_cVerbosity = 0;
531 m_uCurMsgType = UINT8_MAX;
532 m_cbCurMsg = 0;
533 m_pCurMsg = NULL;
534 memset(&m_CurHdrs, '\0', sizeof(m_CurHdrs));
535
536#if 0 /* enable to hack the code without a mile long argument list. */
537 VBoxNetDhcpCfg *pDefCfg = new VBoxNetDhcpCfg();
538 pDefCfg->m_LowerAddr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2,100)));
539 pDefCfg->m_UpperAddr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2,250)));
540 pDefCfg->m_SubnetMask.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8(255,255,255, 0)));
541 RTNETADDRIPV4 Addr;
542 Addr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2, 1)));
543 pDefCfg->m_Routers.push_back(Addr);
544 Addr.u = RT_H2N_U32_C(RT_BSWAP_U32_C(RT_MAKE_U32_FROM_U8( 10, 0, 2, 2)));
545 pDefCfg->m_DNSes.push_back(Addr);
546 pDefCfg->m_DomainName = "vboxnetdhcp.org";
547#if 0
548 pDefCfg->m_cSecLease = 60*60; /* 1 hour */
549#else
550 pDefCfg->m_cSecLease = 30; /* sec */
551#endif
552 pDefCfg->m_TftpServer = "10.0.2.3"; //??
553 this->addConfig(pDefCfg);
554#endif
555}
556
557
558/**
559 * Destruct a DHCP server.
560 */
561VBoxNetDhcp::~VBoxNetDhcp()
562{
563 /*
564 * Close the interface connection.
565 */
566 if (m_hIf != INTNET_HANDLE_INVALID)
567 {
568 INTNETIFCLOSEREQ CloseReq;
569 CloseReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
570 CloseReq.Hdr.cbReq = sizeof(CloseReq);
571 CloseReq.pSession = m_pSession;
572 CloseReq.hIf = m_hIf;
573 m_hIf = INTNET_HANDLE_INVALID;
574 int rc = SUPCallVMMR0Ex(NIL_RTR0PTR, VMMR0_DO_INTNET_IF_CLOSE, 0, &CloseReq.Hdr);
575 AssertRC(rc);
576 }
577
578 if (m_pSession)
579 {
580 SUPTerm(false /* not forced */);
581 m_pSession = NIL_RTR0PTR;
582 }
583}
584
585
586/**
587 * Adds a config to the tail.
588 *
589 * @returns See VBoxNetDHCP::validate().
590 * @param pCfg The config too add.
591 * This object will be consumed by this call!
592 */
593int VBoxNetDhcp::addConfig(VBoxNetDhcpCfg *pCfg)
594{
595 int rc = 0;
596 if (pCfg)
597 {
598 rc = pCfg->validate();
599 if (!rc)
600 m_Cfgs.push_back(pCfg);
601 else
602 delete pCfg;
603 }
604 return rc;
605}
606
607
608/**
609 * Explodes the config into leases.
610 *
611 * @remarks This code is brute force and not very fast nor memory efficient.
612 * We will have to revisit this later.
613 *
614 * @remarks If an IP has been reconfigured for a fixed mac address and it's
615 * already leased to a client, we it won't be available until the
616 * client releases its lease or it expires.
617 */
618void VBoxNetDhcp::explodeConfig(void)
619{
620 RTTIMESPEC Now;
621 RTTimeNow(&Now);
622
623 /*
624 * Remove all non-active leases from the vector and zapping the
625 * config pointers of the once left behind.
626 */
627 std::vector<VBoxNetDhcpLease>::iterator Itr = m_Leases.begin();
628 while (Itr != m_Leases.end())
629 {
630 if (!Itr->isInUse(&Now))
631 Itr = m_Leases.erase(Itr);
632 else
633 {
634 Itr->m_pCfg = NULL;
635 Itr++;
636 }
637 }
638
639 /*
640 * Loop thru the configurations in reverse order, giving the last
641 * configs priority of the newer ones.
642 */
643 size_t iCfg = m_Cfgs.size();
644 while (iCfg-- > 0)
645 {
646 VBoxNetDhcpCfg *pCfg = m_Cfgs[iCfg];
647
648 /* Expand the IP lease range. */
649 uint32_t const uEnd = RT_N2H_U32(pCfg->m_UpperAddr.u);
650 for (uint32_t i = RT_N2H_U32(pCfg->m_LowerAddr.u); i < uEnd; i++)
651 {
652 RTNETADDRIPV4 IPv4Addr;
653 IPv4Addr.u = RT_H2N_U32(i);
654
655 /* Check if it exists and is configured. */
656 VBoxNetDhcpLease *pLease = NULL;
657 for (size_t i = 0; i < m_Leases.size(); i++)
658 if (m_Leases[i].m_IPv4Address.u == IPv4Addr.u)
659 {
660 pLease = &m_Leases[i];
661 break;
662 }
663 if (pLease)
664 {
665 if (!pLease->m_pCfg)
666 pLease->m_pCfg = pCfg;
667 }
668 else
669 {
670 /* add it. */
671 VBoxNetDhcpLease NewLease(IPv4Addr, pCfg);
672 m_Leases.push_back(NewLease);
673 debugPrint(10, false, "exploseConfig: new lease %d.%d.%d.%d",
674 IPv4Addr.au8[0], IPv4Addr.au8[1], IPv4Addr.au8[2], IPv4Addr.au8[3]);
675 }
676 }
677 }
678}
679
680
681/**
682 * Parse the arguments.
683 *
684 * @returns 0 on success, fully bitched exit code on failure.
685 *
686 * @param argc Argument count.
687 * @param argv Argument vector.
688 */
689int VBoxNetDhcp::parseArgs(int argc, char **argv)
690{
691 static const RTGETOPTDEF s_aOptionDefs[] =
692 {
693 { "--name", 'N', RTGETOPT_REQ_STRING },
694 { "--network", 'n', RTGETOPT_REQ_STRING },
695 { "--trunk-name", 't', RTGETOPT_REQ_STRING },
696 { "--trunk-type", 'T', RTGETOPT_REQ_STRING },
697 { "--mac-address", 'a', RTGETOPT_REQ_MACADDR },
698 { "--ip-address", 'i', RTGETOPT_REQ_IPV4ADDR },
699 { "--lease-db", 'D', RTGETOPT_REQ_STRING },
700 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
701
702 { "--begin-config", 'b', RTGETOPT_REQ_NOTHING },
703 { "--gateway", 'g', RTGETOPT_REQ_IPV4ADDR },
704 { "--lower-ip", 'l', RTGETOPT_REQ_IPV4ADDR },
705 { "--upper-ip", 'u', RTGETOPT_REQ_IPV4ADDR },
706 { "--netmask", 'm', RTGETOPT_REQ_IPV4ADDR },
707
708 { "--help", 'h', RTGETOPT_REQ_NOTHING },
709 { "--version ", 'V', RTGETOPT_REQ_NOTHING },
710 };
711
712 RTGETOPTSTATE State;
713 int rc = RTGetOptInit(&State, argc, argv, &s_aOptionDefs[0], RT_ELEMENTS(s_aOptionDefs), 0, 0);
714 AssertRCReturn(rc, 49);
715
716 VBoxNetDhcpCfg *pCurCfg = NULL;
717 for (;;)
718 {
719 RTGETOPTUNION Val;
720 rc = RTGetOpt(&State, &Val);
721 if (!rc)
722 break;
723 switch (rc)
724 {
725 case 'N':
726 m_Name = Val.psz;
727 break;
728 case 'n':
729 m_Network = Val.psz;
730 break;
731 case 't':
732 m_TrunkName = Val.psz;
733 break;
734 case 'T':
735 if (!strcmp(Val.psz, "whatever"))
736 m_enmTrunkType = kIntNetTrunkType_WhateverNone;
737 else if (!strcmp(Val.psz, "netflt"))
738 m_enmTrunkType = kIntNetTrunkType_NetFlt;
739 else if (!strcmp(Val.psz, "netadp"))
740 m_enmTrunkType = kIntNetTrunkType_NetAdp;
741 else if (!strcmp(Val.psz, "srvnat"))
742 m_enmTrunkType = kIntNetTrunkType_SrvNat;
743 else
744 {
745 RTStrmPrintf(g_pStdErr, "Invalid trunk type '%s'\n", Val.psz);
746 return 1;
747 }
748 break;
749 case 'a':
750 m_MacAddress = Val.MacAddr;
751 break;
752 case 'i':
753 m_Ipv4Address = Val.IPv4Addr;
754 break;
755 case 'd':
756 m_LeaseDBName = Val.psz;
757 break;
758
759 case 'v':
760 m_cVerbosity++;
761 break;
762
763 /* Begin config. */
764 case 'b':
765 rc = addConfig(pCurCfg);
766 if (rc)
767 break;
768 pCurCfg = NULL;
769 /* fall thru */
770
771 /* config specific ones. */
772 case 'g':
773 case 'l':
774 case 'u':
775 case 'm':
776 if (!pCurCfg)
777 {
778 pCurCfg = new VBoxNetDhcpCfg();
779 if (!pCurCfg)
780 {
781 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: new VBoxDhcpCfg failed\n");
782 return 1;
783 }
784 }
785
786 switch (rc)
787 {
788 case 'g':
789 pCurCfg->m_Routers.push_back(Val.IPv4Addr);
790 break;
791
792 case 'l':
793 pCurCfg->m_LowerAddr = Val.IPv4Addr;
794 break;
795
796 case 'u':
797 pCurCfg->m_UpperAddr = Val.IPv4Addr;
798 break;
799
800 case 'm':
801 pCurCfg->m_SubnetMask = Val.IPv4Addr;
802 break;
803
804 case 0: /* ignore */ break;
805 default:
806 AssertMsgFailed(("%d", rc));
807 return 1;
808 }
809 break;
810
811 case 'V':
812 RTPrintf("%sr%d\n", VBOX_VERSION_STRING, VBOX_SVN_REV);
813 return 0;
814
815 case 'h':
816 RTPrintf("VBoxNetDHCP Version %s\n"
817 "(C) 2009 Sun Microsystems, Inc.\n"
818 "All rights reserved\n"
819 "\n"
820 "Usage: VBoxNetDHCP <options>\n"
821 "\n"
822 "Options:\n"
823 VBOX_VERSION_STRING);
824 for (size_t i = 0; i < RT_ELEMENTS(s_aOptionDefs); i++)
825 RTPrintf(" -%c, %s\n", s_aOptionDefs[i].iShort, s_aOptionDefs[i].pszLong);
826 return 1;
827
828 default:
829 break;
830 }
831 }
832
833 /*
834 * Do the reconfig. (move this later)
835 */
836 if (!rc)
837 explodeConfig();
838
839 return rc;
840}
841
842
843/**
844 * Tries to connect to the internal network.
845 *
846 * @returns 0 on success, exit code + error message to stderr on failure.
847 */
848int VBoxNetDhcp::tryGoOnline(void)
849{
850 /*
851 * Open the session, load ring-0 and issue the request.
852 */
853 int rc = SUPR3Init(&m_pSession);
854 if (RT_FAILURE(rc))
855 {
856 m_pSession = NIL_RTR0PTR;
857 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: SUPR3Init -> %Rrc", rc);
858 return 1;
859 }
860
861 char szPath[RTPATH_MAX];
862 rc = RTPathProgram(szPath, sizeof(szPath) - sizeof("/VMMR0.r0"));
863 if (RT_FAILURE(rc))
864 {
865 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: RTPathProgram -> %Rrc", rc);
866 return 1;
867 }
868
869 rc = SUPLoadVMM(strcat(szPath, "/VMMR0.r0"));
870 if (RT_FAILURE(rc))
871 {
872 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: SUPLoadVMM(\"%s\") -> %Rrc", szPath, rc);
873 return 1;
874 }
875
876 /*
877 * Create the open request.
878 */
879 INTNETOPENREQ OpenReq;
880 OpenReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
881 OpenReq.Hdr.cbReq = sizeof(OpenReq);
882 OpenReq.pSession = m_pSession;
883 strncpy(OpenReq.szNetwork, m_Network.c_str(), sizeof(OpenReq.szNetwork));
884 OpenReq.szNetwork[sizeof(OpenReq.szNetwork) - 1] = '\0';
885 strncpy(OpenReq.szTrunk, m_TrunkName.c_str(), sizeof(OpenReq.szTrunk));
886 OpenReq.szTrunk[sizeof(OpenReq.szTrunk) - 1] = '\0';
887 OpenReq.enmTrunkType = m_enmTrunkType;
888 OpenReq.fFlags = 0; /** @todo check this */
889 OpenReq.cbSend = m_cbSendBuf;
890 OpenReq.cbRecv = m_cbRecvBuf;
891 OpenReq.hIf = INTNET_HANDLE_INVALID;
892
893 /*
894 * Issue the request.
895 */
896 debugPrint(2, false, "attempting to open/create network \"%s\"...", OpenReq.szNetwork);
897 rc = SUPCallVMMR0Ex(NIL_RTR0PTR, VMMR0_DO_INTNET_OPEN, 0, &OpenReq.Hdr);
898 if (RT_SUCCESS(rc))
899 {
900 m_hIf = OpenReq.hIf;
901 debugPrint(1, false, "successfully opened/created \"%s\" - hIf=%#x", OpenReq.szNetwork, m_hIf);
902
903 /*
904 * Get the ring-3 address of the shared interface buffer.
905 */
906 INTNETIFGETRING3BUFFERREQ GetRing3BufferReq;
907 GetRing3BufferReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
908 GetRing3BufferReq.Hdr.cbReq = sizeof(GetRing3BufferReq);
909 GetRing3BufferReq.pSession = m_pSession;
910 GetRing3BufferReq.hIf = m_hIf;
911 GetRing3BufferReq.pRing3Buf = NULL;
912 rc = SUPCallVMMR0Ex(NIL_RTR0PTR, VMMR0_DO_INTNET_IF_GET_RING3_BUFFER, 0, &GetRing3BufferReq.Hdr);
913 if (RT_SUCCESS(rc))
914 {
915 PINTNETBUF pBuf = GetRing3BufferReq.pRing3Buf;
916 debugPrint(1, false, "pBuf=%p cbBuf=%d cbSend=%d cbRecv=%d",
917 pBuf, pBuf->cbBuf, pBuf->cbSend, pBuf->cbRecv);
918 m_pIfBuf = pBuf;
919
920 /*
921 * Activate the interface.
922 */
923 INTNETIFSETACTIVEREQ ActiveReq;
924 ActiveReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
925 ActiveReq.Hdr.cbReq = sizeof(ActiveReq);
926 ActiveReq.pSession = m_pSession;
927 ActiveReq.hIf = m_hIf;
928 ActiveReq.fActive = true;
929 rc = SUPCallVMMR0Ex(NIL_RTR0PTR, VMMR0_DO_INTNET_IF_SET_ACTIVE, 0, &ActiveReq.Hdr);
930 if (RT_SUCCESS(rc))
931 return 0;
932
933 /* bail out */
934 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: SUPCallVMMR0Ex(,VMMR0_DO_INTNET_IF_SET_PROMISCUOUS_MODE,) failed, rc=%Rrc\n", rc);
935 }
936 else
937 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: SUPCallVMMR0Ex(,VMMR0_DO_INTNET_IF_GET_RING3_BUFFER,) failed, rc=%Rrc\n", rc);
938 }
939 else
940 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: SUPCallVMMR0Ex(,VMMR0_DO_INTNET_OPEN,) failed, rc=%Rrc\n", rc);
941
942 return RT_SUCCESS(rc) ? 0 : 1;
943}
944
945
946/**
947 * Runs the DHCP server.
948 *
949 * @returns exit code + error message to stderr on failure, won't return on
950 * success (you must kill this process).
951 */
952int VBoxNetDhcp::run(void)
953{
954 /*
955 * The loop.
956 */
957 PINTNETRINGBUF pRingBuf = &m_pIfBuf->Recv;
958 for (;;)
959 {
960 /*
961 * Wait for a packet to become available.
962 */
963 INTNETIFWAITREQ WaitReq;
964 WaitReq.Hdr.u32Magic = SUPVMMR0REQHDR_MAGIC;
965 WaitReq.Hdr.cbReq = sizeof(WaitReq);
966 WaitReq.pSession = m_pSession;
967 WaitReq.hIf = m_hIf;
968 WaitReq.cMillies = 2000; /* 2 secs - the sleep is for some reason uninterruptible... */ /** @todo fix interruptability in SrvIntNet! */
969 int rc = SUPCallVMMR0Ex(NIL_RTR0PTR, VMMR0_DO_INTNET_IF_WAIT, 0, &WaitReq.Hdr);
970 if (RT_FAILURE(rc))
971 {
972 if (rc == VERR_TIMEOUT)
973 continue;
974 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: VMMR0_DO_INTNET_IF_WAIT returned %Rrc\n", rc);
975 return 1;
976 }
977
978 /*
979 * Process the receive buffer.
980 */
981 while (INTNETRingGetReadable(pRingBuf) > 0)
982 {
983 size_t cb;
984 void *pv = VBoxNetUDPMatch(m_pIfBuf, RTNETIPV4_PORT_BOOTPS, &m_MacAddress,
985 VBOXNETUDP_MATCH_UNICAST | VBOXNETUDP_MATCH_BROADCAST | VBOXNETUDP_MATCH_CHECKSUM
986 | (m_cVerbosity > 2 ? VBOXNETUDP_MATCH_PRINT_STDERR : 0),
987 &m_CurHdrs, &cb);
988 if (pv && cb)
989 {
990 PCRTNETBOOTP pDhcpMsg = (PCRTNETBOOTP)pv;
991 m_pCurMsg = pDhcpMsg;
992 m_cbCurMsg = cb;
993
994 uint8_t uMsgType;
995 if (RTNetIPv4IsDHCPValid(NULL /* why is this here? */, pDhcpMsg, cb, &uMsgType))
996 {
997 m_uCurMsgType = uMsgType;
998 handleDhcpMsg(uMsgType, pDhcpMsg, cb);
999 m_uCurMsgType = UINT8_MAX;
1000 }
1001 else
1002 debugPrint(1, true, "VBoxNetDHCP: Skipping invalid DHCP packet.\n"); /** @todo handle pure bootp clients too? */
1003
1004 m_pCurMsg = NULL;
1005 m_cbCurMsg = 0;
1006 }
1007 else if (VBoxNetArpHandleIt(m_pSession, m_hIf, m_pIfBuf, &m_MacAddress, m_Ipv4Address))
1008 /* nothing */;
1009
1010 /* Advance to the next frame. */
1011 INTNETRingSkipFrame(m_pIfBuf, pRingBuf);
1012 }
1013 }
1014
1015 return 0;
1016}
1017
1018
1019/**
1020 * Handles a DHCP message.
1021 *
1022 * @returns true if handled, false if not.
1023 * @param uMsgType The message type.
1024 * @param pDhcpMsg The DHCP message.
1025 * @param cb The size of the DHCP message.
1026 */
1027bool VBoxNetDhcp::handleDhcpMsg(uint8_t uMsgType, PCRTNETBOOTP pDhcpMsg, size_t cb)
1028{
1029 if (pDhcpMsg->bp_op == RTNETBOOTP_OP_REQUEST)
1030 {
1031 switch (uMsgType)
1032 {
1033 case RTNET_DHCP_MT_DISCOVER:
1034 return handleDhcpReqDiscover(pDhcpMsg, cb);
1035
1036 case RTNET_DHCP_MT_REQUEST:
1037 return handleDhcpReqRequest(pDhcpMsg, cb);
1038
1039 case RTNET_DHCP_MT_DECLINE:
1040 return handleDhcpReqDecline(pDhcpMsg, cb);
1041
1042 case RTNET_DHCP_MT_RELEASE:
1043 return handleDhcpReqRelease(pDhcpMsg, cb);
1044
1045 case RTNET_DHCP_MT_INFORM:
1046 debugPrint(0, true, "Should we handle this?");
1047 break;
1048
1049 default:
1050 debugPrint(0, true, "Unexpected.");
1051 break;
1052 }
1053 }
1054 return false;
1055}
1056
1057
1058/**
1059 * The client is requesting an offer.
1060 *
1061 * @returns true.
1062 *
1063 * @param pDhcpMsg The message.
1064 * @param cb The message size.
1065 */
1066bool VBoxNetDhcp::handleDhcpReqDiscover(PCRTNETBOOTP pDhcpMsg, size_t cb)
1067{
1068 /*
1069 * The newLease() method contains logic for finding current leases
1070 * and reusing them in case the client is forgetful.
1071 */
1072 VBoxNetDhcpLease *pLease = newLease(pDhcpMsg, cb);
1073 if (!pLease)
1074 return false;
1075 debugPrint(1, true, "Offering %d.%d.%d.%d to %.6Rhxs xid=%#x",
1076 pLease->m_IPv4Address.au8[0],
1077 pLease->m_IPv4Address.au8[1],
1078 pLease->m_IPv4Address.au8[2],
1079 pLease->m_IPv4Address.au8[3],
1080 &pDhcpMsg->bp_chaddr.Mac,
1081 pDhcpMsg->bp_xid);
1082 pLease->offer(pDhcpMsg->bp_xid);
1083
1084 makeDhcpReply(RTNET_DHCP_MT_OFFER, pLease, pDhcpMsg, cb);
1085 return true;
1086}
1087
1088
1089/**
1090 * The client is requesting an offer.
1091 *
1092 * @returns true.
1093 *
1094 * @param pDhcpMsg The message.
1095 * @param cb The message size.
1096 */
1097bool VBoxNetDhcp::handleDhcpReqRequest(PCRTNETBOOTP pDhcpMsg, size_t cb)
1098{
1099 /** @todo Probably need to match the server IP here to work correctly with
1100 * other servers. */
1101 /** @todo This code isn't entirely correct and quite a bit of a hack, but it
1102 * will have to do for now as the right thing (tm) is very complex.
1103 * Part of the fun is verifying that the request is something we can
1104 * and should handle. */
1105
1106 /*
1107 * Try find the lease by the requested address + client MAC address.
1108 */
1109 VBoxNetDhcpLease *pLease = NULL;
1110 RTNETADDRIPV4 IPv4Addr;
1111 bool fReqAddr = findOptionIPv4Addr(RTNET_DHCP_OPT_REQ_ADDR, pDhcpMsg, cb, &IPv4Addr);
1112 if (fReqAddr)
1113 {
1114 fReqAddr = true;
1115 pLease = findLeaseByIpv4AndMacAddresses(IPv4Addr, &pDhcpMsg->bp_chaddr.Mac, true /* fAnyState */);
1116 }
1117
1118 /*
1119 * Try find the lease by the client IP address + client MAC address.
1120 */
1121 if ( !pLease
1122 && pDhcpMsg->bp_ciaddr.u)
1123 pLease = findLeaseByIpv4AndMacAddresses(pDhcpMsg->bp_ciaddr, &pDhcpMsg->bp_chaddr.Mac, true /* fAnyState */);
1124
1125#if 0 /** @todo client id stuff - it doesn't make sense here imho, we need IP + MAC. What would make sense
1126 though is to compare the client id with what we've got in the lease and use it to root out
1127 bad requests. */
1128 /*
1129 * Try find the lease by using the client id.
1130 */
1131 if (!pLease)
1132 {
1133 size_t cbClientID = 0;
1134 uint8_t const *pbClientID = findOption(RTNET_DHCP_OPT_CLIENT_ID, pDhcpMsg, cb, &cbClientID);
1135 if ( pbClientID
1136 && cbClientID == sizeof(RTMAC) + 1
1137 && pbClientID[0] == RTNET_ARP_ETHER
1138 &&
1139 )
1140 {
1141 pLease = findLeaseByIpv4AndMacAddresses(pDhcpMsg->bp_ciaddr, &pDhcpMsg->bp_chaddr.Mac, true /* fAnyState */);
1142 }
1143 }
1144#endif
1145
1146 /*
1147 * Validate the lease that's requested.
1148 * We've already check the MAC and IP addresses.
1149 */
1150 bool fAckIt = false;
1151 if (pLease)
1152 {
1153 if (pLease->isBeingOffered())
1154 {
1155 if (pLease->m_xid == pDhcpMsg->bp_xid)
1156 {
1157 fAckIt = true;
1158 debugPrint(2, true, "REQUEST for offered lease.");
1159 pLease->activate();
1160 }
1161 else
1162 debugPrint(2, true, "REQUEST for offered lease, xid mismatch. Expected %#x, got %#x.",
1163 pLease->m_xid, pDhcpMsg->bp_xid);
1164 }
1165 else if (!pLease->isInCurrentConfig())
1166 debugPrint(1, true, "REQUEST for obsolete lease -> NAK");
1167 else if (fReqAddr != (pDhcpMsg->bp_ciaddr.u != 0)) // ???
1168 {
1169 /** @todo this ain't safe. */
1170 debugPrint(1, true, "REQUEST for lease not on offer, assuming renewal. lease_xid=%#x bp_xid=%#x",
1171 pLease->m_xid, pDhcpMsg->bp_xid);
1172 fAckIt = true;
1173 pLease->activate(pDhcpMsg->bp_xid);
1174 }
1175 else
1176 debugPrint(1, true, "REQUEST for lease not on offer, NAK it.");
1177 }
1178
1179 /*
1180 * NAK if if no lease was found.
1181 */
1182 if (fAckIt)
1183 {
1184 debugPrint(1, false, "ACK'ing DHCP_REQUEST");
1185 makeDhcpReply(RTNET_DHCP_MT_ACK, pLease, pDhcpMsg, cb);
1186 }
1187 else
1188 {
1189 debugPrint(1, false, "NAK'ing DHCP_REQUEST");
1190 makeDhcpReply(RTNET_DHCP_MT_NAC, NULL, pDhcpMsg, cb);
1191 }
1192
1193 return true;
1194}
1195
1196
1197/**
1198 * The client is declining an offer we've made.
1199 *
1200 * @returns true.
1201 *
1202 * @param pDhcpMsg The message.
1203 * @param cb The message size.
1204 */
1205bool VBoxNetDhcp::handleDhcpReqDecline(PCRTNETBOOTP pDhcpMsg, size_t cb)
1206{
1207 /** @todo Probably need to match the server IP here to work correctly with
1208 * other servers. */
1209
1210 /*
1211 * The client is supposed to pass us option 50, requested address,
1212 * from the offer. We also match the lease state. Apparently the
1213 * MAC address is not supposed to be checked here.
1214 */
1215
1216 /** @todo this is not required in the initial implementation, do it later. */
1217 debugPrint(1, true, "DECLINE is not implemented");
1218 return true;
1219}
1220
1221
1222/**
1223 * The client is releasing its lease - good boy.
1224 *
1225 * @returns true.
1226 *
1227 * @param pDhcpMsg The message.
1228 * @param cb The message size.
1229 */
1230bool VBoxNetDhcp::handleDhcpReqRelease(PCRTNETBOOTP pDhcpMsg, size_t cb)
1231{
1232 /** @todo Probably need to match the server IP here to work correctly with
1233 * other servers. */
1234
1235 /*
1236 * The client may pass us option 61, client identifier, which we should
1237 * use to find the lease by.
1238 *
1239 * We're matching MAC address and lease state as well.
1240 */
1241
1242 /*
1243 * If no client identifier or if we couldn't find a lease by using it,
1244 * we will try look it up by the client IP address.
1245 */
1246
1247
1248 /*
1249 * If found, release it.
1250 */
1251
1252
1253 /** @todo this is not required in the initial implementation, do it later. */
1254 debugPrint(1, true, "RELEASE is not implemented");
1255 return true;
1256}
1257
1258
1259/**
1260 * Helper class for stuffing DHCP options into a reply packet.
1261 */
1262class VBoxNetDhcpWriteCursor
1263{
1264private:
1265 uint8_t *m_pbCur; /**< The current cursor position. */
1266 uint8_t *m_pbEnd; /**< The end the current option space. */
1267 uint8_t *m_pfOverload; /**< Pointer to the flags of the overload option. */
1268 uint8_t m_fUsed; /**< Overload fields that have been used. */
1269 PRTNETDHCPOPT m_pOpt; /**< The current option. */
1270 PRTNETBOOTP m_pDhcp; /**< The DHCP packet. */
1271 bool m_fOverflowed; /**< Set if we've overflowed, otherwise false. */
1272
1273public:
1274 /** Instantiate an option cursor for the specified DHCP message. */
1275 VBoxNetDhcpWriteCursor(PRTNETBOOTP pDhcp, size_t cbDhcp) :
1276 m_pbCur(&pDhcp->bp_vend.Dhcp.dhcp_opts[0]),
1277 m_pbEnd((uint8_t *)pDhcp + cbDhcp),
1278 m_pfOverload(NULL),
1279 m_fUsed(0),
1280 m_pOpt(NULL),
1281 m_pDhcp(pDhcp),
1282 m_fOverflowed(false)
1283 {
1284 AssertPtr(pDhcp);
1285 Assert(cbDhcp > RT_UOFFSETOF(RTNETBOOTP, bp_vend.Dhcp.dhcp_opts[10]));
1286 }
1287
1288 /** Destructor. */
1289 ~VBoxNetDhcpWriteCursor()
1290 {
1291 m_pbCur = m_pbEnd = m_pfOverload = NULL;
1292 m_pOpt = NULL;
1293 m_pDhcp = NULL;
1294 }
1295
1296 /**
1297 * Try use the bp_file field.
1298 * @returns true if not overloaded, false otherwise.
1299 */
1300 bool useBpFile(void)
1301 {
1302 if ( m_pfOverload
1303 && (*m_pfOverload & 1))
1304 return false;
1305 m_fUsed |= 1 /* bp_file flag*/;
1306 return true;
1307 }
1308
1309
1310 /**
1311 * Try overload more BOOTP fields
1312 */
1313 bool overloadMore(void)
1314 {
1315 /* switch option area. */
1316 uint8_t *pbNew;
1317 uint8_t *pbNewEnd;
1318 uint8_t fField;
1319 if (!(m_fUsed & 1))
1320 {
1321 fField = 1;
1322 pbNew = &m_pDhcp->bp_file[0];
1323 pbNewEnd = &m_pDhcp->bp_file[sizeof(m_pDhcp->bp_file)];
1324 }
1325 else if (!(m_fUsed & 2))
1326 {
1327 fField = 2;
1328 pbNew = &m_pDhcp->bp_sname[0];
1329 pbNewEnd = &m_pDhcp->bp_sname[sizeof(m_pDhcp->bp_sname)];
1330 }
1331 else
1332 return false;
1333
1334 if (!m_pfOverload)
1335 {
1336 /* Add an overload option. */
1337 *m_pbCur++ = RTNET_DHCP_OPT_OPTION_OVERLOAD;
1338 *m_pbCur++ = fField;
1339 m_pfOverload = m_pbCur;
1340 *m_pbCur++ = 1; /* bp_file flag */
1341 }
1342 else
1343 *m_pfOverload |= fField;
1344
1345 /* pad current option field */
1346 while (m_pbCur != m_pbEnd)
1347 *m_pbCur++ = RTNET_DHCP_OPT_PAD; /** @todo not sure if this stuff is at all correct... */
1348
1349 /* switch */
1350 m_pbCur = pbNew;
1351 m_pbEnd = pbNewEnd;
1352 return true;
1353 }
1354
1355 /**
1356 * Begin an option.
1357 *
1358 * @returns true on succes, false if we're out of space.
1359 *
1360 * @param uOption The option number.
1361 * @param cb The amount of data.
1362 */
1363 bool begin(uint8_t uOption, size_t cb)
1364 {
1365 /* Check that the data of the previous option has all been written. */
1366 Assert( !m_pOpt
1367 || (m_pbCur - m_pOpt->dhcp_len == (uint8_t *)(m_pOpt + 1)));
1368 AssertMsg(cb <= 255, ("%#x\n", cb));
1369
1370 /* Check if we need to overload more stuff. */
1371 if ((uintptr_t)(m_pbEnd - m_pbCur) < cb + 2 + (m_pfOverload ? 1 : 3))
1372 {
1373 m_pOpt = NULL;
1374 if (!overloadMore())
1375 {
1376 m_fOverflowed = true;
1377 AssertMsgFailedReturn(("%u %#x\n", uOption, cb), false);
1378 }
1379 if ((uintptr_t)(m_pbEnd - m_pbCur) < cb + 2 + 1)
1380 {
1381 m_fOverflowed = true;
1382 AssertMsgFailedReturn(("%u %#x\n", uOption, cb), false);
1383 }
1384 }
1385
1386 /* Emit the option header. */
1387 m_pOpt = (PRTNETDHCPOPT)m_pbCur;
1388 m_pOpt->dhcp_opt = uOption;
1389 m_pOpt->dhcp_len = cb;
1390 m_pbCur += 2;
1391 return true;
1392 }
1393
1394 /**
1395 * Puts option data.
1396 *
1397 * @param pvData The data.
1398 * @param cb The amount to put.
1399 */
1400 void put(void const *pvData, size_t cb)
1401 {
1402 Assert(m_pOpt || m_fOverflowed);
1403 if (RT_LIKELY(m_pOpt))
1404 {
1405 Assert((uintptr_t)m_pbCur - (uintptr_t)(m_pOpt + 1) + cb <= (size_t)m_pOpt->dhcp_len);
1406 memcpy(m_pbCur, pvData, cb);
1407 m_pbCur += cb;
1408 }
1409 }
1410
1411 /**
1412 * Puts an IPv4 Address.
1413 *
1414 * @param IPv4Addr The address.
1415 */
1416 void putIPv4Addr(RTNETADDRIPV4 IPv4Addr)
1417 {
1418 put(&IPv4Addr, 4);
1419 }
1420
1421 /**
1422 * Adds an IPv4 address option.
1423 *
1424 * @returns true/false just like begin().
1425 *
1426 * @param uOption The option number.
1427 * @param IPv4Addr The address.
1428 */
1429 bool optIPv4Addr(uint8_t uOption, RTNETADDRIPV4 IPv4Addr)
1430 {
1431 if (!begin(uOption, 4))
1432 return false;
1433 putIPv4Addr(IPv4Addr);
1434 return true;
1435 }
1436
1437 /**
1438 * Adds an option taking 1 or more IPv4 address.
1439 *
1440 * If the vector contains no addresses, the option will not be added.
1441 *
1442 * @returns true/false just like begin().
1443 *
1444 * @param uOption The option number.
1445 * @param rIPv4Addrs Reference to the address vector.
1446 */
1447 bool optIPv4Addrs(uint8_t uOption, std::vector<RTNETADDRIPV4> const &rIPv4Addrs)
1448 {
1449 size_t const c = rIPv4Addrs.size();
1450 if (!c)
1451 return true;
1452
1453 if (!begin(uOption, 4*c))
1454 return false;
1455 for (size_t i = 0; i < c; i++)
1456 putIPv4Addr(rIPv4Addrs[i]);
1457 return true;
1458 }
1459
1460 /**
1461 * Puts an 8-bit integer.
1462 *
1463 * @param u8 The integer.
1464 */
1465 void putU8(uint8_t u8)
1466 {
1467 put(&u8, 1);
1468 }
1469
1470 /**
1471 * Adds an 8-bit integer option.
1472 *
1473 * @returns true/false just like begin().
1474 *
1475 * @param uOption The option number.
1476 * @param u8 The integer
1477 */
1478 bool optU8(uint8_t uOption, uint8_t u8)
1479 {
1480 if (!begin(uOption, 1))
1481 return false;
1482 putU8(u8);
1483 return true;
1484 }
1485
1486 /**
1487 * Puts an 32-bit integer (network endian).
1488 *
1489 * @param u32Network The integer.
1490 */
1491 void putU32(uint32_t u32)
1492 {
1493 put(&u32, 4);
1494 }
1495
1496 /**
1497 * Adds an 32-bit integer (network endian) option.
1498 *
1499 * @returns true/false just like begin().
1500 *
1501 * @param uOption The option number.
1502 * @param u32Network The integer.
1503 */
1504 bool optU32(uint8_t uOption, uint32_t u32)
1505 {
1506 if (!begin(uOption, 4))
1507 return false;
1508 putU32(u32);
1509 return true;
1510 }
1511
1512 /**
1513 * Puts a std::string.
1514 *
1515 * @param rStr Reference to the string.
1516 */
1517 void putStr(std::string const &rStr)
1518 {
1519 put(rStr.c_str(), rStr.size());
1520 }
1521
1522 /**
1523 * Adds an std::string option if the string isn't empty.
1524 *
1525 * @returns true/false just like begin().
1526 *
1527 * @param uOption The option number.
1528 * @param rStr Reference to the string.
1529 */
1530 bool optStr(uint8_t uOption, std::string const &rStr)
1531 {
1532 const size_t cch = rStr.size();
1533 if (!cch)
1534 return true;
1535
1536 if (!begin(uOption, cch))
1537 return false;
1538 put(rStr.c_str(), cch);
1539 return true;
1540 }
1541
1542 /**
1543 * Whether we've overflowed.
1544 *
1545 * @returns true on overflow, false otherwise.
1546 */
1547 bool hasOverflowed(void) const
1548 {
1549 return m_fOverflowed;
1550 }
1551
1552 /**
1553 * Adds the terminating END option.
1554 *
1555 * The END will always be added as we're reserving room for it, however, we
1556 * might've dropped previous options due to overflows and that is what the
1557 * return status indicates.
1558 *
1559 * @returns true on success, false on a (previous) overflow.
1560 */
1561 bool optEnd(void)
1562 {
1563 Assert((uintptr_t)(m_pbEnd - m_pbCur) < 4096);
1564 *m_pbCur++ = RTNET_DHCP_OPT_END;
1565 return !hasOverflowed();
1566 }
1567};
1568
1569
1570/**
1571 * Constructs and sends a reply to a client.
1572 *
1573 * @returns
1574 * @param uMsgType The DHCP message type.
1575 * @param pLease The lease. This can be NULL for some replies.
1576 * @param pDhcpMsg The client message. We will dig out the MAC address,
1577 * transaction ID, and requested options from this.
1578 * @param cb The size of the client message.
1579 */
1580void VBoxNetDhcp::makeDhcpReply(uint8_t uMsgType, VBoxNetDhcpLease *pLease, PCRTNETBOOTP pDhcpMsg, size_t cb)
1581{
1582 size_t cbReply = RTNET_DHCP_NORMAL_SIZE; /** @todo respect the RTNET_DHCP_OPT_MAX_DHCP_MSG_SIZE option */
1583 PRTNETBOOTP pReply = (PRTNETBOOTP)alloca(cbReply);
1584
1585 /*
1586 * The fixed bits stuff.
1587 */
1588 pReply->bp_op = RTNETBOOTP_OP_REPLY;
1589 pReply->bp_htype = RTNET_ARP_ETHER;
1590 pReply->bp_hlen = sizeof(RTMAC);
1591 pReply->bp_hops = 0;
1592 pReply->bp_xid = pDhcpMsg->bp_xid;
1593 pReply->bp_secs = 0;
1594 pReply->bp_flags = 0; // (pDhcpMsg->bp_flags & RTNET_DHCP_FLAGS_NO_BROADCAST); ??
1595 pReply->bp_ciaddr.u = 0;
1596 pReply->bp_yiaddr.u = pLease ? pLease->m_IPv4Address.u : 0xffffffff;
1597 pReply->bp_siaddr.u = pLease && pLease->m_pCfg ? pLease->m_pCfg->m_TftpServerAddr.u : 0; /* (next server == TFTP)*/
1598 pReply->bp_giaddr.u = 0;
1599 memset(&pReply->bp_chaddr, '\0', sizeof(pReply->bp_chaddr));
1600 pReply->bp_chaddr.Mac = pDhcpMsg->bp_chaddr.Mac;
1601 memset(&pReply->bp_sname[0], '\0', sizeof(pReply->bp_sname));
1602 memset(&pReply->bp_file[0], '\0', sizeof(pReply->bp_file));
1603 pReply->bp_vend.Dhcp.dhcp_cookie = RT_H2N_U32_C(RTNET_DHCP_COOKIE);
1604 memset(&pReply->bp_vend.Dhcp.dhcp_opts[0], '\0', RTNET_DHCP_OPT_SIZE);
1605
1606 /*
1607 * The options - use a cursor class for dealing with the ugly stuff.
1608 */
1609 VBoxNetDhcpWriteCursor Cursor(pReply, cbReply);
1610
1611 /* The basics */
1612 Cursor.optU8(RTNET_DHCP_OPT_MSG_TYPE, uMsgType);
1613 Cursor.optIPv4Addr(RTNET_DHCP_OPT_SERVER_ID, m_Ipv4Address);
1614
1615 if (uMsgType != RTNET_DHCP_MT_NAC)
1616 {
1617 AssertReturnVoid(pLease && pLease->m_pCfg);
1618 const VBoxNetDhcpCfg *pCfg = pLease->m_pCfg; /* no need to retain it. */
1619
1620 /* The IP config. */
1621 Cursor.optU32(RTNET_DHCP_OPT_LEASE_TIME, RT_H2N_U32(pCfg->m_cSecLease));
1622 Cursor.optIPv4Addr(RTNET_DHCP_OPT_SUBNET_MASK, pCfg->m_SubnetMask);
1623 Cursor.optIPv4Addrs(RTNET_DHCP_OPT_ROUTERS, pCfg->m_Routers);
1624 Cursor.optIPv4Addrs(RTNET_DHCP_OPT_ROUTERS, pCfg->m_DNSes);
1625 Cursor.optStr(RTNET_DHCP_OPT_HOST_NAME, pCfg->m_HostName);
1626 Cursor.optStr(RTNET_DHCP_OPT_DOMAIN_NAME, pCfg->m_DomainName);
1627
1628 /* The PXE config. */
1629 if (pCfg->m_BootfileName.size())
1630 {
1631 if (Cursor.useBpFile())
1632 RTStrPrintf((char *)&pReply->bp_file[0], sizeof(pReply->bp_file), "%s", pCfg->m_BootfileName.c_str());
1633 else
1634 Cursor.optStr(RTNET_DHCP_OPT_BOOTFILE_NAME, pCfg->m_BootfileName);
1635 }
1636 }
1637
1638 /* Terminate the options. */
1639 if (!Cursor.optEnd())
1640 debugPrint(0, true, "option overflow\n");
1641
1642 /*
1643 * Send it.
1644 */
1645 int rc;
1646#if 0
1647 if (!(pDhcpMsg->bp_flags & RTNET_DHCP_FLAGS_NO_BROADCAST)) /** @todo need to see someone set this flag to check that it's correct. */
1648 {
1649 RTNETADDRIPV4 IPv4AddrBrdCast;
1650 IPv4AddrBrdCast.u = UINT32_C(0xffffffff); /* broadcast IP */
1651 rc = VBoxNetUDPUnicast(m_pSession, m_hIf, m_pIfBuf,
1652 m_Ipv4Address, &m_MacAddress, RTNETIPV4_PORT_BOOTPS, /* sender */
1653 IPv4AddrBrdCast, &pDhcpMsg->bp_chaddr.Mac, RTNETIPV4_PORT_BOOTPC, /* receiver */
1654 pReply, cbReply);
1655 }
1656 else
1657#endif
1658 rc = VBoxNetUDPBroadcast(m_pSession, m_hIf, m_pIfBuf,
1659 m_Ipv4Address, &m_MacAddress, RTNETIPV4_PORT_BOOTPS, /* sender */
1660 RTNETIPV4_PORT_BOOTPC, /* receiver port */
1661 pReply, cbReply);
1662 if (RT_FAILURE(rc))
1663 debugPrint(0, true, "error %Rrc when sending the reply", rc);
1664}
1665
1666
1667/**
1668 * Look up a lease by MAC address.
1669 *
1670 * @returns Pointer to the lease if found, NULL if not found.
1671 * @param pMacAddress The mac address.
1672 * @param fAnyState Any state.
1673 */
1674VBoxNetDhcpLease *VBoxNetDhcp::findLeaseByMacAddress(PCRTMAC pMacAddress, bool fAnyState)
1675{
1676 size_t iLease = m_Leases.size();
1677 while (iLease-- > 0)
1678 {
1679 VBoxNetDhcpLease *pLease = &m_Leases[iLease];
1680 if ( pLease
1681 && pLease->m_MacAddress.au16[0] == pMacAddress->au16[0]
1682 && pLease->m_MacAddress.au16[1] == pMacAddress->au16[1]
1683 && pLease->m_MacAddress.au16[2] == pMacAddress->au16[2]
1684 && ( fAnyState
1685 || (pLease->m_enmState != VBoxNetDhcpLease::kState_Free)) )
1686 return pLease;
1687 }
1688
1689 return NULL;
1690}
1691
1692
1693/**
1694 * Look up a lease by IPv4 and MAC addresses.
1695 *
1696 * @returns Pointer to the lease if found, NULL if not found.
1697 * @param IPv4Addr The IPv4 address.
1698 * @param pMacAddress The mac address.
1699 * @param fAnyState Any state.
1700 */
1701VBoxNetDhcpLease *VBoxNetDhcp::findLeaseByIpv4AndMacAddresses(RTNETADDRIPV4 IPv4Addr, PCRTMAC pMacAddress, bool fAnyState)
1702{
1703 size_t iLease = m_Leases.size();
1704 while (iLease-- > 0)
1705 {
1706 VBoxNetDhcpLease *pLease = &m_Leases[iLease];
1707 if ( pLease
1708 && pLease->m_IPv4Address.u == IPv4Addr.u
1709 && pLease->m_MacAddress.au16[0] == pMacAddress->au16[0]
1710 && pLease->m_MacAddress.au16[1] == pMacAddress->au16[1]
1711 && pLease->m_MacAddress.au16[2] == pMacAddress->au16[2]
1712 && ( fAnyState
1713 || (pLease->m_enmState != VBoxNetDhcpLease::kState_Free)) )
1714 return pLease;
1715 }
1716
1717 return NULL;
1718}
1719
1720
1721/**
1722 * Creates a new lease for the client specified in the DHCP message.
1723 *
1724 * The caller has already made sure it doesn't already have a lease.
1725 *
1726 * @returns Pointer to the lease if found, NULL+log if not found.
1727 * @param IPv4Addr The IPv4 address.
1728 * @param pMacAddress The MAC address.
1729 */
1730VBoxNetDhcpLease *VBoxNetDhcp::newLease(PCRTNETBOOTP pDhcpMsg, size_t cb)
1731{
1732 RTMAC const MacAddr = pDhcpMsg->bp_chaddr.Mac;
1733 RTTIMESPEC Now;
1734 RTTimeNow(&Now);
1735
1736 /*
1737 * Search the possible leases.
1738 *
1739 * We'll try do all the searches in one pass, that is to say, perfect
1740 * match, old lease, and next free/expired lease.
1741 */
1742 VBoxNetDhcpLease *pBest = NULL;
1743 VBoxNetDhcpLease *pOld = NULL;
1744 VBoxNetDhcpLease *pFree = NULL;
1745
1746 size_t cLeases = m_Leases.size();
1747 for (size_t i = 0; i < cLeases; i++)
1748 {
1749 VBoxNetDhcpLease *pCur = &m_Leases[i];
1750
1751 /* Skip it if no configuration, that means its not in the current config. */
1752 if (!pCur->m_pCfg)
1753 continue;
1754
1755 /* best */
1756 if ( pCur->isOneSpecificClient()
1757 && pCur->m_pCfg->matchesMacAddress(&MacAddr))
1758 {
1759 if ( !pBest
1760 || pBest->m_pCfg->m_MacAddresses.size() < pCur->m_pCfg->m_MacAddresses.size())
1761 pBest = pCur;
1762 }
1763
1764 /* old lease */
1765 if ( pCur->m_MacAddress.au16[0] == MacAddr.au16[0]
1766 && pCur->m_MacAddress.au16[1] == MacAddr.au16[1]
1767 && pCur->m_MacAddress.au16[2] == MacAddr.au16[2])
1768 {
1769 if ( !pOld
1770 || RTTimeSpecGetSeconds(&pCur->m_ExpireTime) > RTTimeSpecGetSeconds(&pFree->m_ExpireTime))
1771 pOld = pCur;
1772 }
1773
1774 /* expired lease */
1775 if (!pCur->isInUse(&Now))
1776 {
1777 if ( !pFree
1778 || RTTimeSpecGetSeconds(&pCur->m_ExpireTime) < RTTimeSpecGetSeconds(&pFree->m_ExpireTime))
1779 pFree = pCur;
1780 }
1781 }
1782
1783 VBoxNetDhcpLease *pNew = pBest;
1784 if (!pNew)
1785 pNew = pOld;
1786 if (!pNew)
1787 pNew = pFree;
1788 if (!pNew)
1789 {
1790 debugPrint(0, true, "No more leases.");
1791 return NULL;
1792 }
1793
1794 /*
1795 * Init the lease.
1796 */
1797 pNew->m_MacAddress = MacAddr;
1798 pNew->m_xid = pDhcpMsg->bp_xid;
1799 /** @todo extract the client id. */
1800
1801 return pNew;
1802}
1803
1804
1805/**
1806 * Finds an option.
1807 *
1808 * @returns On success, a pointer to the first byte in the option data (no none
1809 * then it'll be the byte following the 0 size field) and *pcbOpt set
1810 * to the option length.
1811 * On failure, NULL is returned and *pcbOpt unchanged.
1812 *
1813 * @param uOption The option to search for.
1814 * @param pDhcpMsg The DHCP message.
1815 * @param cb The size of the message.
1816 * @param pcbOpt Where to store the option size size. Optional. Note
1817 * that this is adjusted if the option length is larger
1818 * than the message buffer.
1819 */
1820/* static */ const uint8_t *
1821VBoxNetDhcp::findOption(uint8_t uOption, PCRTNETBOOTP pDhcpMsg, size_t cb, size_t *pcbOpt)
1822{
1823 Assert(uOption != RTNET_DHCP_OPT_PAD);
1824
1825 /*
1826 * Validate the DHCP bits and figure the max size of the options in the vendor field.
1827 */
1828 if (cb <= RT_UOFFSETOF(RTNETBOOTP, bp_vend.Dhcp.dhcp_opts))
1829 return NULL;
1830 if (pDhcpMsg->bp_vend.Dhcp.dhcp_cookie != RT_H2N_U32_C(RTNET_DHCP_COOKIE))
1831 return NULL;
1832 size_t cbLeft = cb - RT_UOFFSETOF(RTNETBOOTP, bp_vend.Dhcp.dhcp_opts);
1833 if (cbLeft > RTNET_DHCP_OPT_SIZE)
1834 cbLeft = RTNET_DHCP_OPT_SIZE;
1835
1836 /*
1837 * Search the vendor field.
1838 */
1839 bool fExtended = false;
1840 uint8_t const *pb = &pDhcpMsg->bp_vend.Dhcp.dhcp_opts[0];
1841 while (pb && cbLeft > 0)
1842 {
1843 uint8_t uCur = *pb;
1844 if (uCur == RTNET_DHCP_OPT_PAD)
1845 {
1846 cbLeft--;
1847 pb++;
1848 }
1849 else if (cbLeft <= 1)
1850 break;
1851 else
1852 {
1853 size_t cbCur = pb[1];
1854 if (cbCur > cbLeft - 2)
1855 cbCur = cbLeft - 2;
1856 if (uCur == uOption)
1857 {
1858 if (pcbOpt)
1859 *pcbOpt = cbCur;
1860 return pb+2;
1861 }
1862 pb += cbCur + 2;
1863 cbLeft -= cbCur - 2;
1864 }
1865 }
1866
1867 /** @todo search extended dhcp option field(s) when present */
1868
1869 return NULL;
1870}
1871
1872
1873/**
1874 * Locates an option with an IPv4 address in the DHCP message.
1875 *
1876 * @returns true and *pIpv4Addr if found, false if not.
1877 *
1878 * @param uOption The option to find.
1879 * @param pDhcpMsg The DHCP message.
1880 * @param cb The size of the message.
1881 * @param pIPv4Addr Where to put the address.
1882 */
1883/* static */ bool
1884VBoxNetDhcp::findOptionIPv4Addr(uint8_t uOption, PCRTNETBOOTP pDhcpMsg, size_t cb, PRTNETADDRIPV4 pIPv4Addr)
1885{
1886 size_t cbOpt;
1887 uint8_t const *pbOpt = findOption(uOption, pDhcpMsg, cb, &cbOpt);
1888 if (pbOpt)
1889 {
1890 if (cbOpt >= sizeof(RTNETADDRIPV4))
1891 {
1892 *pIPv4Addr = *(PCRTNETADDRIPV4)pbOpt;
1893 return true;
1894 }
1895 }
1896 return false;
1897}
1898
1899
1900/**
1901 * Print debug message depending on the m_cVerbosity level.
1902 *
1903 * @param iMinLevel The minimum m_cVerbosity level for this message.
1904 * @param fMsg Whether to dump parts for the current DHCP message.
1905 * @param pszFmt The message format string.
1906 * @param ... Optional arguments.
1907 */
1908inline void VBoxNetDhcp::debugPrint(int32_t iMinLevel, bool fMsg, const char *pszFmt, ...) const
1909{
1910 if (iMinLevel <= m_cVerbosity)
1911 {
1912 va_list va;
1913 va_start(va, pszFmt);
1914 debugPrintV(iMinLevel, fMsg, pszFmt, va);
1915 va_end(va);
1916 }
1917}
1918
1919
1920/**
1921 * Print debug message depending on the m_cVerbosity level.
1922 *
1923 * @param iMinLevel The minimum m_cVerbosity level for this message.
1924 * @param fMsg Whether to dump parts for the current DHCP message.
1925 * @param pszFmt The message format string.
1926 * @param va Optional arguments.
1927 */
1928void VBoxNetDhcp::debugPrintV(int iMinLevel, bool fMsg, const char *pszFmt, va_list va) const
1929{
1930 if (iMinLevel <= m_cVerbosity)
1931 {
1932 va_list vaCopy; /* This dude is *very* special, thus the copy. */
1933 va_copy(vaCopy, va);
1934 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: %s: %N\n", iMinLevel >= 2 ? "debug" : "info", pszFmt, &vaCopy);
1935 va_end(vaCopy);
1936
1937 if ( fMsg
1938 && m_cVerbosity >= 2
1939 && m_pCurMsg)
1940 {
1941 const char *pszMsg = m_uCurMsgType != UINT8_MAX ? debugDhcpName(m_uCurMsgType) : "";
1942 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",
1943 pszMsg,
1944 &m_pCurMsg->bp_chaddr,
1945 m_pCurMsg->bp_ciaddr.au8[0], m_pCurMsg->bp_ciaddr.au8[1], m_pCurMsg->bp_ciaddr.au8[2], m_pCurMsg->bp_ciaddr.au8[3],
1946 m_pCurMsg->bp_yiaddr.au8[0], m_pCurMsg->bp_yiaddr.au8[1], m_pCurMsg->bp_yiaddr.au8[2], m_pCurMsg->bp_yiaddr.au8[3],
1947 m_pCurMsg->bp_siaddr.au8[0], m_pCurMsg->bp_siaddr.au8[1], m_pCurMsg->bp_siaddr.au8[2], m_pCurMsg->bp_siaddr.au8[3],
1948 m_pCurMsg->bp_xid);
1949 }
1950 }
1951}
1952
1953
1954/**
1955 * Gets the name of given DHCP message type.
1956 *
1957 * @returns Readonly name.
1958 * @param uMsgType The message number.
1959 */
1960/* static */ const char *VBoxNetDhcp::debugDhcpName(uint8_t uMsgType)
1961{
1962 switch (uMsgType)
1963 {
1964 case 0: return "MT_00";
1965 case RTNET_DHCP_MT_DISCOVER: return "DISCOVER";
1966 case RTNET_DHCP_MT_OFFER: return "OFFER";
1967 case RTNET_DHCP_MT_REQUEST: return "REQUEST";
1968 case RTNET_DHCP_MT_DECLINE: return "DECLINE";
1969 case RTNET_DHCP_MT_ACK: return "ACK";
1970 case RTNET_DHCP_MT_NAC: return "NAC";
1971 case RTNET_DHCP_MT_RELEASE: return "RELEASE";
1972 case RTNET_DHCP_MT_INFORM: return "INFORM";
1973 case 9: return "MT_09";
1974 case 10: return "MT_0a";
1975 case 11: return "MT_0b";
1976 case 12: return "MT_0c";
1977 case 13: return "MT_0d";
1978 case 14: return "MT_0e";
1979 case 15: return "MT_0f";
1980 case 16: return "MT_10";
1981 case 17: return "MT_11";
1982 case 18: return "MT_12";
1983 case 19: return "MT_13";
1984 case UINT8_MAX: return "MT_ff";
1985 default: return "UNKNOWN";
1986 }
1987}
1988
1989
1990
1991/**
1992 * Entry point.
1993 */
1994extern "C" DECLEXPORT(int) TrustedMain(int argc, char **argv, char **envp)
1995{
1996 /*
1997 * Instantiate the DHCP server and hand it the options.
1998 */
1999 VBoxNetDhcp *pDhcp = new VBoxNetDhcp();
2000 if (!pDhcp)
2001 {
2002 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: new VBoxNetDhcp failed!\n");
2003 return 1;
2004 }
2005 int rc = pDhcp->parseArgs(argc - 1, argv + 1);
2006 if (rc)
2007 return rc;
2008
2009 /*
2010 * Try connect the server to the network.
2011 */
2012 rc = pDhcp->tryGoOnline();
2013 if (rc)
2014 {
2015 delete pDhcp;
2016 return rc;
2017 }
2018
2019 /*
2020 * Process requests.
2021 */
2022 g_pDhcp = pDhcp;
2023 rc = pDhcp->run();
2024 g_pDhcp = NULL;
2025 delete pDhcp;
2026
2027 return rc;
2028}
2029
2030
2031
2032#ifndef VBOX_WITH_HARDENING
2033
2034int main(int argc, char **argv, char **envp)
2035{
2036 int rc = RTR3InitAndSUPLib();
2037 if (RT_FAILURE(rc))
2038 {
2039 RTStrmPrintf(g_pStdErr, "VBoxNetDHCP: RTR3InitAndSupLib failed, rc=%Rrc\n", rc);
2040 return 1;
2041 }
2042
2043 return TrustedMain(argc, argv, envp);
2044}
2045
2046#endif /* !VBOX_WITH_HARDENING */
2047
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