Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1758 lines
63 KiB

  1. /*++
  2. Copyright (c) 1994 Microsoft Corporation
  3. Module Name:
  4. protocol.cxx
  5. Abstract:
  6. This module contains the server to client protocol for DHCP.
  7. Author:
  8. Manny Weiser (mannyw) 21-Oct-1992
  9. Environment:
  10. User Mode - Win32
  11. Revision History:
  12. Madan Appiah (madana) 21-Oct-1993
  13. Arthur Bierer (arthurbi) 15-July-1998
  14. hacked up to use with Wininet's auto-proxy detection code
  15. --*/
  16. #include <wininetp.h>
  17. #include "aproxp.h"
  18. #include "apdetect.h"
  19. #ifndef VXD
  20. // ping routines.. ICMP
  21. #include <ipexport.h>
  22. //#include <icmpif.h>
  23. #include <icmpapi.h>
  24. #endif
  25. #ifdef NEWNT
  26. extern BOOL DhcpGlobalIsService;
  27. #endif // NEWNT
  28. DWORD // Time in seconds
  29. DhcpCalculateWaitTime( // how much time to wait
  30. IN DWORD RoundNum, // which round is this
  31. OUT DWORD *WaitMilliSecs // if needed the # in milli seconds
  32. );
  33. POPTION
  34. FormatDhcpInform(
  35. PDHCP_CONTEXT DhcpContext
  36. );
  37. DWORD
  38. SendDhcpInform(
  39. PDHCP_CONTEXT DhcpContext,
  40. PDWORD TransactionId
  41. );
  42. DWORD // status
  43. SendInformAndGetReplies( // send an inform packet and collect replies
  44. IN PDHCP_CONTEXT DhcpContext, // the context to send out of
  45. IN DWORD nInformsToSend,// how many informs to send?
  46. IN DWORD MaxAcksToWait, // how many acks to wait for
  47. OUT DHCP_EXPECTED_OPTIONS *pExpectedOptions // list of things parsed out of request
  48. );
  49. VOID
  50. DhcpExtractFullOrLiteOptions( // Extract some important options alone or ALL
  51. IN PDHCP_CONTEXT DhcpContext,
  52. IN LPBYTE OptStart, // start of the options stuff
  53. IN DWORD MessageSize, // # of bytes of options
  54. IN BOOL LiteOnly, // next struc is EXPECTED_OPTIONS and not FULL_OPTIONS
  55. OUT LPVOID DhcpOptions, // this is where the options would be stored
  56. IN OUT PLIST_ENTRY RecdOptions, // if !LiteOnly this gets filled with all incoming options
  57. IN OUT DWORD *LeaseExpiry, // if !LiteOnly input expiry time, else output expiry time
  58. IN LPBYTE ClassName, // if !LiteOnly this is used to add to the option above
  59. IN DWORD ClassLen // if !LiteOnly this gives the # of bytes of classname
  60. );
  61. DWORD
  62. SendDhcpMessage(
  63. PDHCP_CONTEXT DhcpContext,
  64. DWORD MessageLength,
  65. PDWORD TransactionId
  66. );
  67. DWORD
  68. OpenDhcpSocket(
  69. PDHCP_CONTEXT DhcpContext
  70. );
  71. DWORD
  72. GetSpecifiedDhcpMessage(
  73. PDHCP_CONTEXT DhcpContext,
  74. PDWORD BufferLength,
  75. DWORD TransactionId,
  76. DWORD TimeToWait
  77. );
  78. DWORD
  79. CloseDhcpSocket(
  80. PDHCP_CONTEXT DhcpContext
  81. );
  82. //
  83. // functions
  84. //
  85. DWORD // Time in seconds
  86. DhcpCalculateWaitTime( // how much time to wait
  87. IN DWORD RoundNum, // which round is this
  88. OUT DWORD *WaitMilliSecs // if needed the # in milli seconds
  89. ) {
  90. DWORD MilliSecs;
  91. //DWORD WaitTimes[4] = { 4000, 8000, 16000, 32000 };
  92. DWORD WaitTimes[4] = { 2000, 4000, 8000, 16000 };
  93. if( WaitMilliSecs ) *WaitMilliSecs = 0;
  94. if( RoundNum >= sizeof(WaitTimes)/sizeof(WaitTimes[0]) )
  95. return 0;
  96. MilliSecs = WaitTimes[RoundNum] - 1000 + ((rand()*((DWORD) 2000))/RAND_MAX);
  97. if( WaitMilliSecs ) *WaitMilliSecs = MilliSecs;
  98. return (MilliSecs + 501)/1000;
  99. }
  100. VOID _inline
  101. ConcatOption(
  102. IN OUT LPBYTE *Buf, // input buffer to re-alloc
  103. IN OUT ULONG *BufSize, // input buffer size
  104. IN BYTE UNALIGNED *Data, // data to append
  105. IN ULONG DataSize // how many bytes to add?
  106. )
  107. {
  108. LPBYTE NewBuf;
  109. ULONG NewSize;
  110. NewSize = (*BufSize) + DataSize;
  111. NewBuf = (LPBYTE) DhcpAllocateMemory(NewSize);
  112. if( NULL == NewBuf ) { // could not alloc memory?
  113. return; // can't do much
  114. }
  115. memcpy(NewBuf, *Buf, *BufSize); // copy existing part
  116. memcpy(NewBuf + *BufSize, Data, DataSize); // copy new stuff
  117. if( NULL != *Buf ) DhcpFreeMemory(*Buf); // if we alloc'ed mem, free it now
  118. *Buf = NewBuf;
  119. *BufSize = NewSize; // fill in new values..
  120. }
  121. VOID
  122. DhcpExtractFullOrLiteOptions( // Extract some important options alone or ALL
  123. IN PDHCP_CONTEXT DhcpContext, // input context
  124. IN LPBYTE OptStart, // start of the options stuff
  125. IN DWORD MessageSize, // # of bytes of options
  126. IN BOOL LiteOnly, // next struc is EXPECTED_OPTIONS and not FULL_OPTIONS
  127. OUT LPVOID DhcpOptions, // this is where the options would be stored
  128. IN OUT PLIST_ENTRY RecdOptions, // if !LiteOnly this gets filled with all incoming options
  129. IN OUT DWORD *LeaseExpiry, // if !LiteOnly input expiry time, else output expiry time
  130. IN LPBYTE ClassName, // if !LiteOnly this is used to add to the option above
  131. IN DWORD ClassLen // if !LiteOnly this gives the # of bytes of classname
  132. ) {
  133. BYTE UNALIGNED* ThisOpt;
  134. BYTE UNALIGNED* NextOpt;
  135. BYTE UNALIGNED* EndOpt;
  136. BYTE UNALIGNED* MagicCookie;
  137. DWORD Size, ThisSize, UClassSize = 0;
  138. LPBYTE UClass= NULL; // concatenation of all OPTION_USER_CLASS options
  139. PDHCP_EXPECTED_OPTIONS ExpOptions;
  140. PDHCP_FULL_OPTIONS FullOptions;
  141. BYTE ReqdCookie[] = {
  142. (BYTE)DHCP_MAGIC_COOKIE_BYTE1,
  143. (BYTE)DHCP_MAGIC_COOKIE_BYTE2,
  144. (BYTE)DHCP_MAGIC_COOKIE_BYTE3,
  145. (BYTE)DHCP_MAGIC_COOKIE_BYTE4
  146. };
  147. UNREFERENCED_PARAMETER(DhcpContext);
  148. UNREFERENCED_PARAMETER(RecdOptions);
  149. UNREFERENCED_PARAMETER(ClassName);
  150. UNREFERENCED_PARAMETER(ClassLen);
  151. EndOpt = OptStart + MessageSize; // all options should be < EndOpt;
  152. ExpOptions = (PDHCP_EXPECTED_OPTIONS)DhcpOptions;
  153. FullOptions = (PDHCP_FULL_OPTIONS)DhcpOptions;
  154. RtlZeroMemory((LPBYTE)DhcpOptions, LiteOnly?sizeof(*ExpOptions):sizeof(*FullOptions));
  155. // if(!LiteOnly) InitializeListHead(RecdOptions); -- clear off this list for getting ALL options
  156. // dont clear off options... just accumulate over..
  157. MagicCookie = OptStart;
  158. if( 0 == MessageSize ) goto DropPkt; // nothing to do in this case
  159. if( 0 != memcmp(MagicCookie, ReqdCookie, sizeof(ReqdCookie)) )
  160. goto DropPkt; // oops, cant handle this packet
  161. NextOpt = &MagicCookie[sizeof(ReqdCookie)];
  162. while( NextOpt < EndOpt && OPTION_END != *NextOpt ) {
  163. if( OPTION_PAD == *NextOpt ) { // handle pads right away
  164. NextOpt++;
  165. continue;
  166. }
  167. ThisOpt = NextOpt; // take a good look at this option
  168. if( NextOpt + 2 > EndOpt ) { // goes over boundary?
  169. break;
  170. }
  171. NextOpt += 2 + (unsigned)ThisOpt[1]; // Option[1] holds the size of this option
  172. Size = ThisOpt[1];
  173. if( NextOpt > EndOpt ) { // illegal option that goes over boundary!
  174. break; // ignore the error, but dont take this option
  175. }
  176. if(!LiteOnly) do { // look for any OPTION_MSFT_CONTINUED ..
  177. if( NextOpt >= EndOpt ) break; // no more options
  178. if( OPTION_MSFT_CONTINUED != NextOpt[0] ) break;
  179. if( NextOpt + 1 + NextOpt[1] > EndOpt ) {
  180. NextOpt = NULL; // do this so that we know to quit at the end..
  181. break;
  182. }
  183. NextOpt++; // skip opt code
  184. ThisSize = NextOpt[0]; // # of bytes to shift back..
  185. memcpy(ThisOpt+2+Size, NextOpt+1,ThisSize);
  186. NextOpt += ThisSize+1;
  187. Size += ThisSize;
  188. } while(1); // keep stringing up any "continued" options..
  189. if( NULL == NextOpt ) { // err parsing OPTION_MSFT_CONTINUED ..
  190. break;
  191. }
  192. if( LiteOnly ) { // handle the small subnet of options
  193. switch( ThisOpt[0] ) { // ThisOpt[0] is OptionId, ThisOpt[1] is size
  194. case OPTION_MESSAGE_TYPE:
  195. if( ThisOpt[1] != 1 ) goto DropPkt;
  196. ExpOptions->MessageType = &ThisOpt[2];
  197. continue;
  198. case OPTION_SUBNET_MASK:
  199. if( ThisOpt[1] != sizeof(DWORD) ) goto DropPkt;
  200. ExpOptions->SubnetMask = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  201. continue;
  202. case OPTION_LEASE_TIME:
  203. if( ThisOpt[1] != sizeof(DWORD) ) goto DropPkt;
  204. ExpOptions->LeaseTime = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  205. continue;
  206. case OPTION_SERVER_IDENTIFIER:
  207. if( ThisOpt[1] != sizeof(DWORD) ) goto DropPkt;
  208. ExpOptions->ServerIdentifier = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  209. continue;
  210. case OPTION_DOMAIN_NAME:
  211. if( ThisOpt[1] == 0 ) goto DropPkt;
  212. ExpOptions->DomainName = (BYTE UNALIGNED *)&ThisOpt[2];
  213. ExpOptions->DomainNameSize = ThisOpt[1];
  214. break;
  215. case OPTION_WPAD_URL:
  216. if( ThisOpt[1] == 0 ) goto DropPkt;
  217. ExpOptions->WpadUrl = (BYTE UNALIGNED *)&ThisOpt[2];
  218. ExpOptions->WpadUrlSize = ThisOpt[1];
  219. break;
  220. default:
  221. continue;
  222. }
  223. } else { // Handle the full set of options
  224. switch( ThisOpt[0] ) {
  225. case OPTION_MESSAGE_TYPE:
  226. if( Size != 1 ) goto DropPkt;
  227. FullOptions->MessageType = &ThisOpt[2];
  228. break;
  229. case OPTION_SUBNET_MASK:
  230. if( Size != sizeof(DWORD) ) goto DropPkt;
  231. FullOptions->SubnetMask = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  232. break;
  233. case OPTION_LEASE_TIME:
  234. if( Size != sizeof(DWORD) ) goto DropPkt;
  235. FullOptions->LeaseTime = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  236. break;
  237. case OPTION_SERVER_IDENTIFIER:
  238. if( Size != sizeof(DWORD) ) goto DropPkt;
  239. FullOptions->ServerIdentifier = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  240. break;
  241. case OPTION_RENEWAL_TIME: // T1Time
  242. if( Size != sizeof(DWORD) ) goto DropPkt;
  243. FullOptions->T1Time = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  244. break;
  245. case OPTION_REBIND_TIME: // T2Time
  246. if( Size != sizeof(DWORD) ) goto DropPkt;
  247. FullOptions->T2Time = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  248. break;
  249. case OPTION_ROUTER_ADDRESS:
  250. if( Size < sizeof(DWORD) || (Size % sizeof(DWORD) ) )
  251. goto DropPkt; // There can be many router addresses
  252. FullOptions->GatewayAddresses = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  253. FullOptions->nGateways = Size / sizeof(DWORD);
  254. break;
  255. case OPTION_STATIC_ROUTES:
  256. if( Size < 2*sizeof(DWORD) || (Size % (2*sizeof(DWORD))) )
  257. goto DropPkt; // the static routes come in pairs
  258. FullOptions->StaticRouteAddresses = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  259. FullOptions->nStaticRoutes = Size/(2*sizeof(DWORD));
  260. break;
  261. case OPTION_DYNDNS_BOTH:
  262. if( Size < 3 ) goto DropPkt;
  263. FullOptions->DnsFlags = (BYTE UNALIGNED *)&ThisOpt[2];
  264. FullOptions->DnsRcode1 = (BYTE UNALIGNED *)&ThisOpt[3];
  265. FullOptions->DnsRcode2 = (BYTE UNALIGNED *)&ThisOpt[3];
  266. break;
  267. case OPTION_DOMAIN_NAME:
  268. if( Size == 0 ) goto DropPkt;
  269. FullOptions->DomainName = (BYTE UNALIGNED *)&ThisOpt[2];
  270. FullOptions->DomainNameSize = Size;
  271. break;
  272. case OPTION_WPAD_URL:
  273. if( Size == 0 ) goto DropPkt;
  274. FullOptions->WpadUrl = (BYTE UNALIGNED *)&ThisOpt[2];
  275. FullOptions->WpadUrlSize = Size;
  276. break;
  277. case OPTION_DOMAIN_NAME_SERVERS:
  278. if( Size < sizeof(DWORD) || (Size % sizeof(DWORD) ))
  279. goto DropPkt;
  280. FullOptions->DnsServerList = (DHCP_IP_ADDRESS UNALIGNED *)&ThisOpt[2];
  281. FullOptions->nDnsServers = Size / sizeof(DWORD);
  282. break;
  283. case OPTION_MESSAGE:
  284. if( Size == 0 ) break; // ignore zero sized packets
  285. FullOptions->ServerMessage = &ThisOpt[2];
  286. FullOptions->ServerMessageLength = ThisOpt[1];
  287. break;
  288. case OPTION_MCAST_LEASE_START:
  289. if ( Size != sizeof(DATE_TIME) ) goto DropPkt;
  290. FullOptions->MCastLeaseStartTime = (DWORD UNALIGNED *)&ThisOpt[2];
  291. break;
  292. case OPTION_MCAST_TTL:
  293. if ( Size != 1 ) goto DropPkt;
  294. FullOptions->MCastTTL = (BYTE UNALIGNED *)&ThisOpt[2];
  295. break;
  296. case OPTION_USER_CLASS:
  297. if( Size <= 6) goto DropPkt;
  298. ConcatOption(&UClass, &UClassSize, &ThisOpt[2], Size);
  299. continue; // don't add this option yet...
  300. default:
  301. // unknowm message, nothing to do.. especially dont log this
  302. break;
  303. }
  304. } // if LiteOnly then else
  305. } // while NextOpt < EndOpt
  306. if( LiteOnly && LeaseExpiry ) { // If asked to calculate lease expiration time..
  307. DWORD LeaseTime;
  308. time_t TimeNow, ExpirationTime;
  309. // BBUGBUGBUG [arthurbi] broken intensionlly, dead code.
  310. //if( ExpOptions->LeaseTime ) LeaseTime = _I_ntohl(*ExpOptions->LeaseTime);
  311. if( ExpOptions->LeaseTime ) LeaseTime = 0;
  312. else LeaseTime = DHCP_MINIMUM_LEASE;
  313. ExpirationTime = (TimeNow = time(NULL)) + (time_t)LeaseTime;
  314. if( ExpirationTime < TimeNow ) {
  315. ExpirationTime = INFINIT_TIME;
  316. }
  317. *LeaseExpiry = (DWORD)ExpirationTime ;
  318. }
  319. if( !LiteOnly && NULL != UClass ) { // we have a user class list to pass on..
  320. DhcpAssert(UClassSize != 0 ); // we better have something here..
  321. DhcpFreeMemory(UClass); UClass = NULL;
  322. }
  323. return;
  324. DropPkt:
  325. RtlZeroMemory(DhcpOptions, LiteOnly?sizeof(ExpOptions):sizeof(FullOptions));
  326. if( LiteOnly && LeaseExpiry ) *LeaseExpiry = (DWORD) time(NULL) + DHCP_MINIMUM_LEASE;
  327. //if(!LiteOnly) DhcpFreeAllOptions(RecdOptions);// ok undo the options that we just added
  328. if(!LiteOnly && NULL != UClass ) DhcpFreeMemory(UClass);
  329. }
  330. POPTION // ptr to add additional options
  331. FormatDhcpInform( // format the packet for an INFORM
  332. IN PDHCP_CONTEXT DhcpContext // format for this context
  333. ) {
  334. LPOPTION option;
  335. LPBYTE OptionEnd;
  336. BYTE value;
  337. PDHCP_MESSAGE dhcpMessage;
  338. dhcpMessage = DhcpContext->MessageBuffer;
  339. RtlZeroMemory( dhcpMessage, DHCP_SEND_MESSAGE_SIZE );
  340. //
  341. // BUGBUG [arthurbi] -
  342. // For RAS client, use broadcast bit, otherwise the router will try
  343. // to send as unicast to made-up RAS client hardware address, which
  344. // will not work. So will this work without it?
  345. //
  346. //
  347. // Transaction ID is filled in during send
  348. //
  349. dhcpMessage->Operation = BOOT_REQUEST;
  350. dhcpMessage->HardwareAddressType = DhcpContext->HardwareAddressType;
  351. dhcpMessage->SecondsSinceBoot = (WORD) DhcpContext->SecondsSinceBoot;
  352. memcpy(dhcpMessage->HardwareAddress,DhcpContext->HardwareAddress,DhcpContext->HardwareAddressLength);
  353. dhcpMessage->HardwareAddressLength = (BYTE)DhcpContext->HardwareAddressLength;
  354. dhcpMessage->ClientIpAddress = DhcpContext->IpAddress;
  355. //dhcpMessage->Reserved = 0;
  356. //dhcpMessage->Reserved = _I_htons(DHCP_BROADCAST);
  357. //if ( IS_MDHCP_CTX(DhcpContext ) ) MDHCP_MESSAGE( dhcpMessage );
  358. option = &dhcpMessage->Option;
  359. OptionEnd = (LPBYTE)dhcpMessage + DHCP_SEND_MESSAGE_SIZE;
  360. //
  361. // always add magic cookie first
  362. //
  363. option = (LPOPTION) DhcpAppendMagicCookie( (LPBYTE) option, OptionEnd );
  364. value = DHCP_INFORM_MESSAGE;
  365. option = DhcpAppendOption(
  366. option,
  367. OPTION_MESSAGE_TYPE,
  368. &value,
  369. 1,
  370. OptionEnd
  371. );
  372. //
  373. // BUGBUG [arthurbi], shouldn't we uncomment this?
  374. //
  375. // un comment later on
  376. /*option = DhcpAppendClassIdOption(
  377. DhcpContext,
  378. (LPBYTE)option,
  379. OptionEnd
  380. );*/
  381. return( option );
  382. }
  383. DWORD // status
  384. SendDhcpInform( // send an inform packet after filling required options
  385. IN PDHCP_CONTEXT DhcpContext, // sned out for this context
  386. IN OUT DWORD *pdwXid // use this Xid (if zero fill something and return it)
  387. ) {
  388. DWORD size;
  389. POPTION option;
  390. LPBYTE OptionEnd;
  391. BYTE SentOpt[OPTION_END+1];
  392. BYTE SentVOpt[OPTION_END+1];
  393. BYTE VendorOpt[OPTION_END+1];
  394. DWORD VendorOptSize;
  395. RtlZeroMemory(SentOpt, sizeof(SentOpt)); // initialize boolean arrays
  396. RtlZeroMemory(SentVOpt, sizeof(SentVOpt)); // so that no option is presumed sent
  397. VendorOptSize = 0; // encapsulated vendor option is empty
  398. option = FormatDhcpInform( DhcpContext ); // core format
  399. OptionEnd = (LPBYTE)(DhcpContext->MessageBuffer) + DHCP_SEND_MESSAGE_SIZE;
  400. if( DhcpContext->ClientIdentifier.fSpecified) // client id specified in registy
  401. option = DhcpAppendClientIDOption( // ==> use this client id as option
  402. option,
  403. DhcpContext->ClientIdentifier.bType,
  404. DhcpContext->ClientIdentifier.pbID,
  405. (BYTE)DhcpContext->ClientIdentifier.cbID,
  406. OptionEnd
  407. );
  408. else // client id was not specified
  409. option = DhcpAppendClientIDOption( // ==> use hw addr as client id
  410. option,
  411. DhcpContext->HardwareAddressType,
  412. DhcpContext->HardwareAddress,
  413. (BYTE)DhcpContext->HardwareAddressLength,
  414. OptionEnd
  415. );
  416. { // add hostname and comment options
  417. char szHostName[255];
  418. if ( _I_gethostname(szHostName, ARRAY_ELEMENTS(szHostName)) != SOCKET_ERROR )
  419. {
  420. option = DhcpAppendOption(
  421. option,
  422. OPTION_HOST_NAME,
  423. (LPBYTE)szHostName,
  424. (BYTE)((strlen(szHostName) + 1) * sizeof(CHAR)),
  425. OptionEnd
  426. );
  427. }
  428. }
  429. if( NULL != DhcpGlobalClientClassInfo ) { // if we have any info on client class..
  430. option = DhcpAppendOption(
  431. option,
  432. OPTION_CLIENT_CLASS_INFO,
  433. (LPBYTE)DhcpGlobalClientClassInfo,
  434. strlen(DhcpGlobalClientClassInfo),
  435. OptionEnd
  436. );
  437. }
  438. SentOpt[OPTION_MESSAGE_TYPE] = TRUE; // these must have been added by now
  439. if(DhcpContext->ClassIdLength) SentOpt[OPTION_USER_CLASS] = TRUE;
  440. SentOpt[OPTION_CLIENT_CLASS_INFO] = TRUE;
  441. SentOpt[OPTION_CLIENT_ID] = TRUE;
  442. SentOpt[OPTION_REQUESTED_ADDRESS] = TRUE;
  443. SentOpt[OPTION_HOST_NAME] = TRUE;
  444. option = DhcpAppendSendOptions( // append all other options we need to send
  445. DhcpContext, // for this context
  446. &DhcpContext->SendOptionsList, // this is the list of options to send out
  447. DhcpContext->ClassId, // which class.
  448. DhcpContext->ClassIdLength, // how many bytes are there in the class id
  449. (LPBYTE)option, // start of the buffer to add the options
  450. (LPBYTE)OptionEnd, // end of the buffer up to which we can add options
  451. SentOpt, // this is the boolean array that marks what opt were sent
  452. SentVOpt, // this is for vendor spec options
  453. VendorOpt, // this would contain some vendor specific options
  454. &VendorOptSize // the # of bytes of vendor options added to VendorOpt param
  455. );
  456. if( !SentOpt[OPTION_VENDOR_SPEC_INFO] && VendorOptSize && VendorOptSize <= OPTION_END )
  457. option = DhcpAppendOption( // add vendor specific options if we havent already sent it
  458. option,
  459. OPTION_VENDOR_SPEC_INFO,
  460. VendorOpt,
  461. (BYTE)VendorOptSize,
  462. OptionEnd
  463. );
  464. option = DhcpAppendOption( option, OPTION_END, NULL, 0, OptionEnd );
  465. size = (DWORD)((PBYTE)option - (PBYTE)DhcpContext->MessageBuffer);
  466. return SendDhcpMessage( // finally send the message and return
  467. DhcpContext,
  468. size,
  469. pdwXid
  470. );
  471. }
  472. DWORD
  473. InitializeDhcpSocket(
  474. SOCKET *Socket,
  475. DHCP_IP_ADDRESS IpAddress
  476. )
  477. /*++
  478. Routine Description:
  479. This function initializes and binds a socket to the specified IP address.
  480. Arguments:
  481. Socket - Returns a pointer to the initialized socket.
  482. IpAddress - The IP address to bind the socket to. It is legitimate
  483. to bind a socket to 0.0.0.0 if the card has no current IP address.
  484. Return Value:
  485. The status of the operation.
  486. --*/
  487. {
  488. DWORD error;
  489. DWORD closeError;
  490. DWORD value;
  491. struct sockaddr_in socketName;
  492. DWORD i;
  493. SOCKET sock;
  494. //
  495. // Sockets initialization
  496. //
  497. sock = _I_socket( PF_INET, SOCK_DGRAM, IPPROTO_UDP );
  498. if ( sock == INVALID_SOCKET ) {
  499. error = _I_WSAGetLastError();
  500. DhcpPrint(("socket failed, error = %ld\n", error ));
  501. return( error );
  502. }
  503. //
  504. // Make the socket share-able
  505. //
  506. value = 1;
  507. error = _I_setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (char FAR *)&value, sizeof(value) );
  508. if ( error != 0 ) {
  509. error = _I_WSAGetLastError();
  510. DhcpPrint(("setsockopt failed, err = %ld\n", error ));
  511. closeError = _I_closesocket( sock );
  512. if ( closeError != 0 ) {
  513. DhcpPrint(("closesocket failed, err = %d\n", closeError ));
  514. }
  515. return( error );
  516. }
  517. error = _I_setsockopt( sock, SOL_SOCKET, SO_BROADCAST, (char FAR *)&value, sizeof(value) );
  518. if ( error != 0 ) {
  519. error = _I_WSAGetLastError();
  520. DhcpPrint(("setsockopt failed, err = %ld\n", error ));
  521. closeError = _I_closesocket( sock );
  522. if ( closeError != 0 ) {
  523. DhcpPrint(("closesocket failed, err = %d\n", closeError ));
  524. }
  525. return( error );
  526. }
  527. //
  528. // If the IpAddress is zero, set the special socket option to make
  529. // stack work with zero address.
  530. //
  531. if( IpAddress == 0 ) {
  532. value = 1234;
  533. error = _I_setsockopt( sock, SOL_SOCKET, 0x8000, (char FAR *)&value, sizeof(value) );
  534. if ( error != 0 ) {
  535. error = _I_WSAGetLastError();
  536. DhcpPrint(("setsockopt failed, err = %ld\n", error ));
  537. closeError = _I_closesocket( sock );
  538. if ( closeError != 0 ) {
  539. DhcpPrint(("closesocket failed, err = %d\n", closeError ));
  540. }
  541. return( error );
  542. }
  543. }
  544. socketName.sin_family = PF_INET;
  545. socketName.sin_port = _I_htons( DHCP_CLIENT_PORT );
  546. socketName.sin_addr.s_addr = IpAddress;
  547. for ( i = 0; i < 8 ; i++ ) {
  548. socketName.sin_zero[i] = 0;
  549. }
  550. //
  551. // Bind this socket to the DHCP server port
  552. //
  553. error = _I_bind(
  554. sock,
  555. (struct sockaddr FAR *)&socketName,
  556. sizeof( socketName )
  557. );
  558. if ( error != 0 ) {
  559. error = _I_WSAGetLastError();
  560. DhcpPrint(("bind failed (address 0x%lx), err = %ld\n", IpAddress, error ));
  561. closeError = _I_closesocket( sock );
  562. if ( closeError != 0 ) {
  563. DhcpPrint(("closesocket failed, err = %d\n", closeError ));
  564. }
  565. return( error );
  566. }
  567. *Socket = sock;
  568. return( NO_ERROR );
  569. }
  570. DWORD // status
  571. SendInformAndGetReplies( // send an inform packet and collect replies
  572. IN PDHCP_CONTEXT DhcpContext, // the context to send out of
  573. IN DWORD nInformsToSend,// how many informs to send?
  574. IN DWORD MaxAcksToWait, // how many acks to wait for
  575. OUT DHCP_EXPECTED_OPTIONS *pExpectedOptions // list of things parsed out of request
  576. ) {
  577. time_t StartTime;
  578. time_t TimeNow;
  579. DWORD TimeToWait;
  580. DWORD Error;
  581. DWORD Xid;
  582. DWORD MessageSize;
  583. DWORD RoundNum;
  584. DWORD MessageCount;
  585. DWORD LeaseExpirationTime;
  586. DHCP_FULL_OPTIONS FullOptions;
  587. DhcpPrint(("SendInformAndGetReplies entered\n"));
  588. if((Error = OpenDhcpSocket(DhcpContext)) != ERROR_SUCCESS) {
  589. DhcpPrint(("Could not open socket for this interface! (%ld)\n", Error));
  590. return Error;
  591. }
  592. Xid = 0; // Will be generated by first SendDhcpPacket
  593. MessageCount = 0; // total # of messages we have got
  594. DhcpContext->SecondsSinceBoot = 0; // start at zero..
  595. for( RoundNum = 0; RoundNum < nInformsToSend; RoundNum ++ ) {
  596. Error = SendDhcpInform(DhcpContext, &Xid);
  597. if( ERROR_SUCCESS != Error ) {
  598. DhcpPrint(("SendDhcpInform: %ld\n", Error));
  599. goto Cleanup;
  600. } else {
  601. DhcpPrint(("Sent DhcpInform\n"));
  602. }
  603. TimeToWait = DhcpCalculateWaitTime(RoundNum, NULL);
  604. DhcpContext->SecondsSinceBoot += TimeToWait; // do this so that next time thru it can go thru relays..
  605. StartTime = time(NULL);
  606. while ( TRUE ) { // wiat for the specified wait time
  607. MessageSize = DHCP_MESSAGE_SIZE;
  608. DhcpPrint(("Waiting for ACK[Xid=%x]: %ld seconds\n",Xid, TimeToWait));
  609. Error = GetSpecifiedDhcpMessage( // try to receive an ACK
  610. DhcpContext,
  611. &MessageSize,
  612. Xid,
  613. (DWORD)TimeToWait
  614. );
  615. if ( Error == ERROR_SEM_TIMEOUT ) break;
  616. if( Error != ERROR_SUCCESS ) {
  617. DhcpPrint(("GetSpecifiedDhcpMessage: %ld\n", Error));
  618. goto Cleanup;
  619. }
  620. DhcpExtractFullOrLiteOptions( // Need to see if this is an ACK
  621. DhcpContext,
  622. (LPBYTE)&DhcpContext->MessageBuffer->Option,
  623. MessageSize - DHCP_MESSAGE_FIXED_PART_SIZE,
  624. TRUE, // do lite extract only
  625. pExpectedOptions, // check for only expected options
  626. NULL, // unused
  627. &LeaseExpirationTime,
  628. NULL, // unused
  629. 0 // unused
  630. );
  631. if( NULL == pExpectedOptions->MessageType ) {
  632. DhcpPrint(("Received no message type!\n"));
  633. } else if( DHCP_ACK_MESSAGE != *(pExpectedOptions->MessageType) ) {
  634. DhcpPrint(("Received unexpected message type: %ld\n", *(pExpectedOptions->MessageType)));
  635. } else if( NULL == pExpectedOptions->ServerIdentifier ) {
  636. DhcpPrint(("Received no server identifier, dropping inform ACK\n"));
  637. } else {
  638. MessageCount ++;
  639. DhcpPrint(("Received %ld ACKS so far\n", MessageCount));
  640. DhcpExtractFullOrLiteOptions( // do FULL options..
  641. DhcpContext,
  642. (LPBYTE)&DhcpContext->MessageBuffer->Option,
  643. MessageSize - DHCP_MESSAGE_FIXED_PART_SIZE,
  644. FALSE,
  645. &FullOptions,
  646. &(DhcpContext->RecdOptionsList),
  647. &LeaseExpirationTime,
  648. DhcpContext->ClassId,
  649. DhcpContext->ClassIdLength
  650. );
  651. if( MessageCount >= MaxAcksToWait ) goto Cleanup;
  652. } // if( it is an ACK and ServerId present )
  653. TimeNow = time(NULL); // Reset the time values to reflect new time
  654. if( TimeToWait < (DWORD) (TimeNow - StartTime) ) {
  655. break; // no more time left to wait..
  656. }
  657. TimeToWait -= (DWORD)(TimeNow - StartTime); // recalculate time now
  658. StartTime = TimeNow; // reset start time also
  659. } // end of while ( TimeToWait > 0)
  660. } // for (RoundNum = 0; RoundNum < nInformsToSend ; RoundNum ++ )
  661. Cleanup:
  662. CloseDhcpSocket(DhcpContext);
  663. if( MessageCount ) Error = ERROR_SUCCESS;
  664. DhcpPrint(("SendInformAndGetReplies: got %d ACKS (returning %ld)\n", MessageCount,Error));
  665. return Error;
  666. }
  667. //--------------------------------------------------------------------------------
  668. // This function gets the options from the server using DHCP_INFORM message.
  669. // It picks the first ACK and then processes it.
  670. // It ignores any errors caused by TIME_OUTS as that only means there is no
  671. // server, or the server does not have this functionality. No point giving up
  672. // because of that.
  673. //--------------------------------------------------------------------------------
  674. BOOL // win32 status
  675. DhcpDoInform( // send an inform packet if necessary
  676. IN CAdapterInterface * pAdapterInterface,
  677. IN BOOL fBroadcast, // Do we broadcast this inform, or unicast to server?
  678. OUT LPSTR * ppszAutoProxyUrl
  679. ) {
  680. DHCP_CONTEXT StackDhcpContext; // input context to do inform on
  681. PDHCP_CONTEXT DhcpContext = &StackDhcpContext;
  682. DWORD Error;
  683. DWORD LocalError;
  684. BOOL WasPlumbedBefore;
  685. time_t OldT2Time;
  686. DHCP_EXPECTED_OPTIONS ExpectedOptions;
  687. if ( ! pAdapterInterface->IsDhcp() ) {
  688. return FALSE;
  689. }
  690. if (! pAdapterInterface->CopyAdapterInfoToDhcpContext(DhcpContext) ) {
  691. return FALSE;
  692. }
  693. // mdhcp uses INADDR_ANY so it does not have to have an ipaddress.
  694. if( 0 == DhcpContext->IpAddress && !IS_MDHCP_CTX( DhcpContext) ) {
  695. DhcpPrint(("Cannot do DhcpInform on an adapter without ip address!\n"));
  696. return FALSE;
  697. }
  698. // Open the socket ahead... so that things work. Tricky, else does not work!!!
  699. if((Error = OpenDhcpSocket(DhcpContext)) != ERROR_SUCCESS ) {
  700. DhcpPrint(("Could not open socket (%ld)\n", Error));
  701. return FALSE;
  702. }
  703. // If you always need to broadcast this message, the KLUDGE is to
  704. // set pContext->T2Time = 0; and pContext->fFlags &= ~DHCP_CONTEXT_FLAGS_PLUMBED
  705. // and that should do the trick! Safe to change the struct as it was cloned.
  706. OldT2Time = DhcpContext->T2Time;
  707. WasPlumbedBefore = IS_ADDRESS_PLUMBED(DhcpContext);
  708. if(fBroadcast) {
  709. DhcpContext->T2Time = 0; // !!!! KLUDGE.. look at SendDhcpMessage to understand this ..
  710. ADDRESS_UNPLUMBED(DhcpContext);
  711. CONNECTION_BROADCAST(DhcpContext);
  712. } else {
  713. DhcpContext->T2Time = (-1);
  714. }
  715. memset((void *) &ExpectedOptions, 0, sizeof(DHCP_EXPECTED_OPTIONS));
  716. Error = SendInformAndGetReplies( // get replies on this
  717. DhcpContext, // context to send on
  718. 2, // send atmost 2 informs
  719. 1, // wait for as many as 4 packets..
  720. &ExpectedOptions
  721. );
  722. DhcpContext->LastInformSent = time(NULL); // record when the last inform was sent
  723. DhcpContext->T2Time = OldT2Time;
  724. if( WasPlumbedBefore ) ADDRESS_PLUMBED(DhcpContext);
  725. LocalError = CloseDhcpSocket(DhcpContext);
  726. DhcpAssert(ERROR_SUCCESS == LocalError);
  727. if( ERROR_SUCCESS != Error ) {
  728. DhcpPrint(("DhcpDoInform:return [0x%lx]\n", Error));
  729. }
  730. else
  731. {
  732. //
  733. // Did we actually get a response with an URL that can be used ?
  734. //
  735. if (ExpectedOptions.WpadUrl && ExpectedOptions.WpadUrlSize > 0)
  736. {
  737. LPSTR lpszAutoProxyUrl = NewString(NULL, ExpectedOptions.WpadUrlSize);
  738. if (lpszAutoProxyUrl)
  739. {
  740. memcpy(lpszAutoProxyUrl, ExpectedOptions.WpadUrl, ExpectedOptions.WpadUrlSize);
  741. *ppszAutoProxyUrl = lpszAutoProxyUrl;
  742. }
  743. return (lpszAutoProxyUrl != NULL);
  744. }
  745. }
  746. return FALSE;
  747. }
  748. DWORD
  749. SendDhcpMessage(
  750. PDHCP_CONTEXT DhcpContext,
  751. DWORD MessageLength,
  752. PDWORD TransactionId
  753. )
  754. /*++
  755. Routine Description:
  756. This function sends a UDP message to the DHCP server specified
  757. in the DhcpContext.
  758. Arguments:
  759. DhcpContext - A pointer to a DHCP context block.
  760. MessageLength - The length of the message to send.
  761. TransactionID - The transaction ID for this message. If 0, the
  762. function generates a random ID, and returns it.
  763. Return Value:
  764. The status of the operation.
  765. --*/
  766. {
  767. DWORD error;
  768. int i;
  769. struct sockaddr_in socketName;
  770. time_t TimeNow;
  771. BOOL LockedInterface = FALSE;
  772. if ( *TransactionId == 0 ) {
  773. *TransactionId = (rand() << 16) + rand();
  774. }
  775. DhcpContext->MessageBuffer->TransactionID = *TransactionId;
  776. //
  777. // Initialize the outgoing address.
  778. //
  779. socketName.sin_family = PF_INET;
  780. socketName.sin_port = _I_htons( DHCP_SERVR_PORT );
  781. if ( IS_MDHCP_CTX(DhcpContext) ) {
  782. socketName.sin_addr.s_addr = DhcpContext->DhcpServerAddress;
  783. if ( CLASSD_NET_ADDR( DhcpContext->DhcpServerAddress ) ) {
  784. int TTL = 16;
  785. //
  786. // Set TTL
  787. // MBUG: we need to read this from the registry.
  788. //
  789. if (_I_setsockopt(
  790. DhcpContext->Socket,
  791. IPPROTO_IP,
  792. IP_MULTICAST_TTL,
  793. (char *)&TTL,
  794. sizeof((int)TTL)) == SOCKET_ERROR){
  795. error = _I_WSAGetLastError();
  796. DhcpPrint(("could not set MCast TTL %ld\n",error ));
  797. return error;
  798. }
  799. }
  800. } else if( IS_ADDRESS_PLUMBED(DhcpContext) &&
  801. !IS_MEDIA_RECONNECTED(DhcpContext) && // media reconnect - braodcast
  802. !IS_POWER_RESUMED(DhcpContext) ) { // power resumed - broadcast
  803. //
  804. // If we are past T2, use the broadcast address; otherwise,
  805. // direct this to the server.
  806. //
  807. TimeNow = time( NULL );
  808. // BUGBUG why did we broadcast here before ?
  809. if ( TimeNow > DhcpContext->T2Time && IS_CONNECTION_BROADCAST(DhcpContext)) {
  810. socketName.sin_addr.s_addr = (DHCP_IP_ADDRESS)(INADDR_BROADCAST);
  811. } else {
  812. socketName.sin_addr.s_addr = DhcpContext->DhcpServerAddress;
  813. }
  814. }
  815. else {
  816. socketName.sin_addr.s_addr = (DHCP_IP_ADDRESS)(INADDR_BROADCAST);
  817. INET_ASSERT(FALSE);
  818. }
  819. for ( i = 0; i < 8 ; i++ ) {
  820. socketName.sin_zero[i] = 0;
  821. }
  822. if( socketName.sin_addr.s_addr ==
  823. (DHCP_IP_ADDRESS)(INADDR_BROADCAST) ) {
  824. DWORD Error = ERROR_SUCCESS;
  825. //
  826. // BUGBUG TODO [arthurbi] This code below is needed for
  827. // Broadcasts to work. We need to make some fancy driver
  828. // calls to work...
  829. //
  830. //
  831. // if we broadcast a message, inform IP stack - the adapter we
  832. // like to send this broadcast on, otherwise it will pick up the
  833. // first uninitialized adapter.
  834. //
  835. // InterfaceId = DhcpContext->IpInterfaceContext;
  836. //
  837. // if( !IPSetInterface( InterfaceId ) ) {
  838. // // DhcpAssert( FALSE );
  839. // Error = ERROR_GEN_FAILURE;
  840. // }
  841. // InterfaceId = ((PLOCAL_CONTEXT_INFO)
  842. // DhcpContext->LocalInformation)->IpInterfaceContext;
  843. //
  844. // LOCK_INTERFACE();
  845. // LockedInterface = TRUE;
  846. // Error = IPSetInterface( InterfaceId );
  847. // DhcpAssert( Error == ERROR_SUCCESS );
  848. if( ERROR_SUCCESS != Error ) {
  849. DhcpPrint(("IPSetInterface failed with %lx error\n", Error));
  850. UNLOCK_INTERFACE();
  851. return Error;
  852. }
  853. }
  854. //
  855. // send minimum DHCP_MIN_SEND_RECV_PK_SIZE (300) bytes, otherwise
  856. // bootp relay agents don't like the packet.
  857. //
  858. MessageLength = (DWORD)((MessageLength > DHCP_MIN_SEND_RECV_PK_SIZE) ?
  859. MessageLength : DHCP_MIN_SEND_RECV_PK_SIZE);
  860. error = _I_sendto(
  861. DhcpContext->Socket,
  862. (PCHAR)DhcpContext->MessageBuffer,
  863. MessageLength,
  864. 0,
  865. (struct sockaddr *)&socketName,
  866. sizeof( struct sockaddr )
  867. );
  868. #ifndef VXD
  869. if( LockedInterface ) { UNLOCK_INTERFACE(); }
  870. #endif VXD
  871. if ( error == SOCKET_ERROR ) {
  872. error = _I_WSAGetLastError();
  873. DhcpPrint(("Send failed, error = %ld\n", error ));
  874. } else {
  875. IF_DEBUG( PROTOCOL ) {
  876. DhcpPrint(("Sent message to %s: \n", _I_inet_ntoa( socketName.sin_addr )));
  877. }
  878. DhcpDumpMessage( DEBUG_PROTOCOL_DUMP, DhcpContext->MessageBuffer );
  879. error = NO_ERROR;
  880. }
  881. return( error );
  882. }
  883. DWORD
  884. OpenDhcpSocket(
  885. PDHCP_CONTEXT DhcpContext
  886. )
  887. {
  888. DWORD Error;
  889. if ( DhcpContext->Socket != INVALID_SOCKET ) {
  890. return ( ERROR_SUCCESS );
  891. }
  892. //
  893. // create a socket for the dhcp protocol. it's important to bind the
  894. // socket to the correct ip address. There are currently three cases:
  895. //
  896. // 1. If the interface has been autoconfigured, it already has an address,
  897. // say, IP1. If the client receives a unicast offer from a dhcp server
  898. // the offer will be addressed to IP2, which is the client's new dhcp
  899. // address. If we bind the dhcp socket to IP1, the client won't be able
  900. // to receive unicast responses. So, we bind the socket to 0.0.0.0.
  901. // This will allow the socket to receive a unicast datagram addressed to
  902. // any address.
  903. //
  904. // 2. If the interface in not plumbed (i.e. doesn't have an address) bind
  905. // the socket to 0.0.0.0
  906. //
  907. // 3. If the interface has been plumbed has in *not* autoconfigured, then
  908. // bind to the current address.
  909. Error = InitializeDhcpSocket(
  910. &DhcpContext->Socket,
  911. DhcpContext->IpAddress
  912. );
  913. if( Error != ERROR_SUCCESS ) {
  914. DhcpContext->Socket = INVALID_SOCKET;
  915. DhcpPrint((" Socket Open failed, %ld\n", Error ));
  916. }
  917. return(Error);
  918. }
  919. DWORD
  920. CloseDhcpSocket(
  921. PDHCP_CONTEXT DhcpContext
  922. )
  923. {
  924. DWORD Error = ERROR_SUCCESS;
  925. if( DhcpContext->Socket != INVALID_SOCKET ) {
  926. Error = _I_closesocket( DhcpContext->Socket );
  927. if( Error != ERROR_SUCCESS ) {
  928. DhcpPrint((" Socket close failed, %ld\n", Error ));
  929. }
  930. DhcpContext->Socket = INVALID_SOCKET;
  931. //
  932. // Reset the IP stack to send DHCP broadcast to first
  933. // uninitialized stack.
  934. //
  935. //Bool = IPResetInterface();
  936. //DhcpAssert( Bool == TRUE );
  937. }
  938. return( Error );
  939. }
  940. typedef struct /* anonymous */ { // structure to hold waiting recvfroms
  941. LIST_ENTRY RecvList; // other elements in this list
  942. PDHCP_CONTEXT Ctxt; // which context is this wait for?
  943. DWORD InBufLen; // what was the buffer size to recv in?
  944. PDWORD BufLen; // how many bytes did we recvd?
  945. DWORD Xid; // what xid is this wait for?
  946. time_t ExpTime; // wait until what time?
  947. HANDLE WaitEvent; // event for waiting on..
  948. BOOL Recd; // was a packet received..?
  949. } RECV_CTXT, *PRECV_CTXT; // ctxt used to recv on..
  950. VOID
  951. InsertInPriorityList( // insert in priority list according to Secs
  952. IN OUT PRECV_CTXT Ctxt, // Secs field changed to hold offset
  953. IN PLIST_ENTRY List,
  954. OUT PBOOL First // adding in first location?
  955. )
  956. {
  957. if( IsListEmpty(List) ) { // no element in list? add this and quit
  958. *First = TRUE; // adding at head
  959. } else {
  960. *First = FALSE; // adding at tail..
  961. }
  962. InsertTailList( List, &Ctxt->RecvList); // insert element..
  963. //LeaveCriticalSection( &DhcpGlobalRecvFromCritSect );
  964. }
  965. DWORD
  966. TryReceive( // try to recv pkt on 0.0.0.0 socket
  967. IN SOCKET Socket, // socket to recv on
  968. IN LPBYTE Buffer, // buffer to fill
  969. OUT PDWORD BufLen, // # of bytes filled in buffer
  970. OUT PDWORD Xid, // Xid of recd pkt
  971. IN DWORD Secs // # of secs to spend waiting?
  972. )
  973. {
  974. DWORD Error;
  975. struct timeval timeout;
  976. fd_set SockSet;
  977. struct sockaddr SockName;
  978. int SockNameSize;
  979. FD_ZERO(&SockSet);
  980. FD_SET(Socket,&SockSet);
  981. SockNameSize = sizeof( SockName );
  982. timeout.tv_sec = Secs;
  983. timeout.tv_usec = 0;
  984. DhcpPrint(("Select: waiting for: %ld seconds\n", Secs));
  985. Error = _I_select( 0, &SockSet, NULL, NULL, &timeout );
  986. if( ERROR_SUCCESS == Error ) { // timed out..
  987. DhcpPrint(("Recv timed out..\n"));
  988. return ERROR_SEM_TIMEOUT;
  989. }
  990. Error = _I_recvfrom(Socket,(char *)Buffer,*BufLen, 0, &SockName, &SockNameSize);
  991. if( SOCKET_ERROR == Error ) {
  992. Error = _I_WSAGetLastError();
  993. DhcpPrint(("Recv failed 0x%lx\n",Error));
  994. } else {
  995. *BufLen = Error;
  996. Error = ERROR_SUCCESS;
  997. *Xid = ((PDHCP_MESSAGE)Buffer)->TransactionID;
  998. DhcpPrint(("Recd msg XID: 0x%lx [Mdhcp? %s]\n", *Xid,
  999. IS_MDHCP_MESSAGE(((PDHCP_MESSAGE)Buffer))?"yes":"no" ));
  1000. }
  1001. return Error;
  1002. }
  1003. VOID
  1004. DispatchPkt( // find out any takers for Xid
  1005. IN OUT PRECV_CTXT Ctxt, // ctxt that has buffer and buflen
  1006. IN DWORD Xid // recd Xid
  1007. )
  1008. {
  1009. do { // not a loop, just for ease of use
  1010. LPBYTE Tmp;
  1011. PLIST_ENTRY Entry;
  1012. PRECV_CTXT ThisCtxt;
  1013. Entry = DhcpGlobalRecvFromList.Flink;
  1014. while(Entry != &DhcpGlobalRecvFromList ) {
  1015. ThisCtxt = CONTAINING_RECORD(Entry, RECV_CTXT, RecvList);
  1016. Entry = Entry->Flink;
  1017. if(Xid != ThisCtxt->Xid ) continue; // mismatch.. nothing more todo
  1018. // now check for same type of message and ctxt...
  1019. if( (unsigned)IS_MDHCP_MESSAGE((Ctxt->Ctxt->MessageBuffer))
  1020. !=
  1021. IS_MDHCP_CTX( (ThisCtxt->Ctxt) )
  1022. ) {
  1023. //
  1024. // The contexts dont match.. give up
  1025. //
  1026. continue;
  1027. }
  1028. //
  1029. // check for same hardware address..
  1030. //
  1031. if( ThisCtxt->Ctxt->HardwareAddressLength != Ctxt->Ctxt->MessageBuffer->HardwareAddressLength ) {
  1032. continue;
  1033. }
  1034. if( 0 != memcmp(ThisCtxt->Ctxt->HardwareAddress,
  1035. Ctxt->Ctxt->MessageBuffer->HardwareAddress,
  1036. ThisCtxt->Ctxt->HardwareAddressLength
  1037. ) ) {
  1038. continue;
  1039. }
  1040. // matched.. switch buffers to give this guy this due..
  1041. DhcpDumpMessage(DEBUG_PROTOCOL_DUMP, (PDHCP_MESSAGE)(Ctxt->Ctxt->MessageBuffer) );
  1042. *(ThisCtxt->BufLen) = *(Ctxt->BufLen);
  1043. Tmp = (LPBYTE)(Ctxt->Ctxt)->MessageBuffer;
  1044. (Ctxt->Ctxt)->MessageBuffer = (ThisCtxt->Ctxt)->MessageBuffer;
  1045. (ThisCtxt->Ctxt)->MessageBuffer = (PDHCP_MESSAGE)Tmp;
  1046. RemoveEntryList(&ThisCtxt->RecvList);
  1047. InitializeListHead(&ThisCtxt->RecvList);
  1048. DhcpAssert(FALSE == ThisCtxt->Recd);
  1049. ThisCtxt->Recd = TRUE;
  1050. if( 0 == SetEvent(ThisCtxt->WaitEvent) ) {
  1051. DhcpAssert(FALSE);
  1052. }
  1053. break;
  1054. }
  1055. } while (FALSE);
  1056. //LeaveCriticalSection(&DhcpGlobalRecvFromCritSect);
  1057. }
  1058. DWORD
  1059. ProcessRecvFromSocket( // wait using select and process incoming pkts
  1060. IN OUT PRECV_CTXT Ctxt // ctxt to use
  1061. )
  1062. {
  1063. time_t TimeNow;
  1064. SOCKET Socket;
  1065. LPBYTE Buffer;
  1066. DWORD Xid;
  1067. DWORD Error;
  1068. PLIST_ENTRY Entry;
  1069. Socket = (Ctxt->Ctxt)->Socket;
  1070. TimeNow = time(NULL);
  1071. Xid = 0;
  1072. Error = ERROR_SEM_TIMEOUT;
  1073. while(TimeNow <= Ctxt->ExpTime ) { // while required to wait
  1074. Buffer = (LPBYTE)((Ctxt->Ctxt)->MessageBuffer);
  1075. *(Ctxt->BufLen) = Ctxt->InBufLen;
  1076. Error = TryReceive(Socket, Buffer, Ctxt->BufLen, &Xid, (DWORD)(Ctxt->ExpTime - TimeNow));
  1077. if( ERROR_SUCCESS != Error ) { // did not recv?
  1078. if( WSAECONNRESET != Error ) break; // ignore possibly spurious conn-resets..
  1079. else { TimeNow = time(NULL); continue; }
  1080. }
  1081. if( Xid == Ctxt->Xid ) break; // this was destined for this ctxt only..
  1082. DispatchPkt(Ctxt, Xid);
  1083. TimeNow = time(NULL);
  1084. }
  1085. if( TimeNow > Ctxt->ExpTime ) { // we timed out.
  1086. Error = ERROR_SEM_TIMEOUT;
  1087. }
  1088. // now done.. so we must remove this ctxt from the list and signal first guy
  1089. //EnterCriticalSection(&DhcpGlobalRecvFromCritSect);
  1090. RemoveEntryList(&Ctxt->RecvList);
  1091. CloseHandle(Ctxt->WaitEvent);
  1092. if( !IsListEmpty(&DhcpGlobalRecvFromList)) { // ok got an elt.. signal this.
  1093. Entry = DhcpGlobalRecvFromList.Flink;
  1094. Ctxt = CONTAINING_RECORD(Entry, RECV_CTXT, RecvList);
  1095. if( 0 == SetEvent(Ctxt->WaitEvent) ) {
  1096. DhcpAssert(FALSE);
  1097. }
  1098. }
  1099. //LeaveCriticalSection(&DhcpGlobalRecvFromCritSect);
  1100. return Error;
  1101. }
  1102. //================================================================================
  1103. // get dhcp message with requested transaction id, but also make sure only one
  1104. // socket is used at any given time (one socket bound to 0.0.0.0), and also
  1105. // re-distribute message for some other thread if that is also required..
  1106. //================================================================================
  1107. DWORD
  1108. GetSpecifiedDhcpMessageEx(
  1109. IN OUT PDHCP_CONTEXT DhcpContext, // which context to recv for
  1110. OUT PDWORD BufferLength, // how big a buffer was read?
  1111. IN DWORD Xid, // which xid to look for?
  1112. IN DWORD TimeToWait // how many seconds to sleep?
  1113. )
  1114. {
  1115. RECV_CTXT Ctxt; // element in list for this call to getspe..
  1116. BOOL First; // is this the first element in list?
  1117. DWORD Result;
  1118. Ctxt.Ctxt = DhcpContext; // fill in the context
  1119. Ctxt.InBufLen = *BufferLength;
  1120. Ctxt.BufLen = BufferLength;
  1121. Ctxt.Xid = Xid;
  1122. Ctxt.ExpTime = time(NULL) + TimeToWait;
  1123. Ctxt.WaitEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
  1124. Ctxt.Recd = FALSE;
  1125. if( NULL == Ctxt.WaitEvent ) {
  1126. DhcpAssert(NULL != Ctxt.WaitEvent);
  1127. return GetLastError();
  1128. }
  1129. First = FALSE;
  1130. InsertInPriorityList(&Ctxt, &DhcpGlobalRecvFromList, &First);
  1131. if( First ) { // this *is* the first call to GetSpec..
  1132. Result = ProcessRecvFromSocket(&Ctxt);
  1133. } else { // we wait for other calls to go thru..
  1134. Result = WaitForSingleObject(Ctxt.WaitEvent, TimeToWait * 1000);
  1135. //EnterCriticalSection(&DhcpGlobalRecvFromCritSect);
  1136. if( Ctxt.Recd || WAIT_FAILED == Result || WAIT_TIMEOUT == Result ) {
  1137. if( WAIT_FAILED == Result ) Result = GetLastError();
  1138. else if (WAIT_TIMEOUT == Result ) Result = ERROR_SEM_TIMEOUT;
  1139. else Result = ERROR_SUCCESS;
  1140. RemoveEntryList(&Ctxt.RecvList); // remove it from list
  1141. //LeaveCriticalSection(&DhcpGlobalRecvFromCritSect);
  1142. CloseHandle(Ctxt.WaitEvent);
  1143. return Result;
  1144. } else {
  1145. DhcpAssert(WAIT_OBJECT_0 == Result && Ctxt.Recd == FALSE );
  1146. // have not received a packet but have been woken up? must be first in line now..
  1147. //LeaveCriticalSection(&DhcpGlobalRecvFromCritSect);
  1148. Result = ProcessRecvFromSocket(&Ctxt);
  1149. }
  1150. }
  1151. return Result;
  1152. }
  1153. #define RATIO 1
  1154. DWORD
  1155. GetSpecifiedDhcpMessage(
  1156. PDHCP_CONTEXT DhcpContext,
  1157. PDWORD BufferLength,
  1158. DWORD TransactionId,
  1159. DWORD TimeToWait
  1160. )
  1161. /*++
  1162. Routine Description:
  1163. This function waits TimeToWait seconds to receives the specified
  1164. DHCP response.
  1165. Arguments:
  1166. DhcpContext - A pointer to a DHCP context block.
  1167. BufferLength - Returns the size of the input buffer.
  1168. TransactionID - A filter. Wait for a message with this TID.
  1169. TimeToWait - Time, in milli seconds, to wait for the message.
  1170. Return Value:
  1171. The status of the operation. If the specified message has been
  1172. been returned, the status is ERROR_TIMEOUT.
  1173. --*/
  1174. {
  1175. struct sockaddr socketName;
  1176. int socketNameSize = sizeof( socketName );
  1177. struct timeval timeout;
  1178. time_t startTime, now;
  1179. DWORD error;
  1180. DWORD actualTimeToWait;
  1181. SOCKET clientSocket;
  1182. fd_set readSocketSet;
  1183. if( !IS_ADDRESS_PLUMBED(DhcpContext) ) {
  1184. //
  1185. // For RAS server Lease API this call won't happen as we don't have to do this nonsense
  1186. //
  1187. error = GetSpecifiedDhcpMessageEx(
  1188. DhcpContext,
  1189. BufferLength,
  1190. TransactionId,
  1191. TimeToWait
  1192. );
  1193. if( ERROR_SUCCESS == error ) {
  1194. // received a message frm the dhcp server..
  1195. SERVER_REACHED(DhcpContext);
  1196. }
  1197. return error;
  1198. }
  1199. startTime = time( NULL );
  1200. actualTimeToWait = TimeToWait;
  1201. //
  1202. // Setup the file descriptor set for select.
  1203. //
  1204. clientSocket = DhcpContext->Socket;
  1205. FD_ZERO( &readSocketSet );
  1206. FD_SET( clientSocket, &readSocketSet );
  1207. while ( 1 ) {
  1208. timeout.tv_sec = actualTimeToWait / RATIO;
  1209. timeout.tv_usec = actualTimeToWait % RATIO;
  1210. DhcpPrint(("Select: waiting for: %ld seconds\n", actualTimeToWait));
  1211. error = _I_select( 0, &readSocketSet, NULL, NULL, &timeout );
  1212. if ( error == 0 ) {
  1213. //
  1214. // Timeout before read data is available.
  1215. //
  1216. DhcpPrint(("Recv timed out\n", 0 ));
  1217. error = ERROR_SEM_TIMEOUT;
  1218. break;
  1219. }
  1220. error = _I_recvfrom(
  1221. clientSocket,
  1222. (PCHAR)DhcpContext->MessageBuffer,
  1223. *BufferLength,
  1224. 0,
  1225. &socketName,
  1226. &socketNameSize
  1227. );
  1228. if ( error == SOCKET_ERROR ) {
  1229. error = _I_WSAGetLastError();
  1230. DhcpPrint(("Recv failed, error = %ld\n", error ));
  1231. if( WSAECONNRESET != error ) break;
  1232. //
  1233. // ignore connreset -- this could be caused by someone sending random ICMP port unreachable.
  1234. //
  1235. } else if (DhcpContext->MessageBuffer->TransactionID == TransactionId ) {
  1236. DhcpPrint(( "Received Message, XID = %lx, MDhcp = %d.\n",
  1237. TransactionId,
  1238. IS_MDHCP_MESSAGE( DhcpContext->MessageBuffer) ));
  1239. if (((unsigned)IS_MDHCP_MESSAGE( DhcpContext->MessageBuffer) == IS_MDHCP_CTX( DhcpContext))) {
  1240. DhcpDumpMessage(DEBUG_PROTOCOL_DUMP, DhcpContext->MessageBuffer );
  1241. *BufferLength = error;
  1242. error = NO_ERROR;
  1243. if( DhcpContext->MessageBuffer->HardwareAddressLength == DhcpContext->HardwareAddressLength
  1244. && 0 == memcmp(DhcpContext->MessageBuffer->HardwareAddress,
  1245. DhcpContext->HardwareAddress,
  1246. DhcpContext->HardwareAddressLength
  1247. )) {
  1248. //
  1249. // Transction IDs match, same type (MDHCP/DHCP), Hardware addresses match!
  1250. //
  1251. break;
  1252. }
  1253. }
  1254. } else {
  1255. DhcpPrint(( "Received a buffer with unknown XID = %lx\n",
  1256. DhcpContext->MessageBuffer->TransactionID ));
  1257. }
  1258. //
  1259. // We received a message, but not the one we're interested in.
  1260. // Reset the timeout to reflect elapsed time, and wait for
  1261. // another message.
  1262. //
  1263. now = time( NULL );
  1264. actualTimeToWait = (DWORD)(TimeToWait - RATIO * (now - startTime));
  1265. if ( (LONG)actualTimeToWait < 0 ) {
  1266. error = ERROR_SEM_TIMEOUT;
  1267. break;
  1268. }
  1269. }
  1270. if ( ERROR_SEM_TIMEOUT != error )
  1271. {
  1272. //
  1273. // a message was received from a DHCP server. disable IP autoconfiguration.
  1274. //
  1275. SERVER_REACHED(DhcpContext);
  1276. }
  1277. return( error );
  1278. }
  1279. DWORD
  1280. QueryWellKnownDnsName(
  1281. OUT LPSTR * ppszAutoProxyUrl
  1282. )
  1283. /*++
  1284. Routine Description:
  1285. This function walks a list of standard DNS names trying to find
  1286. an entry for "wpad.some-domain-here.org" If it does, it constructs
  1287. an URL that is suitable for use in auto-proxy.
  1288. Arguments:
  1289. lpszAutoProxyUrl - Url used to return a successful auto-proxy discover
  1290. dwAutoProxyUrlLength - length of buffer passed in above
  1291. Return Value:
  1292. ERROR_SUCCESS - if we found a URL/DNS name
  1293. ERROR_NOT_FOUND - on error
  1294. revised: joshco 7-oct-1998
  1295. if we dont get a valid domain back, be sure and try
  1296. the netbios name ("wpad") no trailing dot.
  1297. revised: joshco 7-oct-1998
  1298. use the define PROXY_AUTO_DETECT_PATH instead
  1299. of hardcoding "wpad.dat"
  1300. --*/
  1301. {
  1302. #define WORK_BUFFER_SIZE 356
  1303. DEBUG_ENTER((DBG_SOCKETS,
  1304. Dword,
  1305. "QueryWellKnownDnsName",
  1306. "%x",
  1307. ppszAutoProxyUrl
  1308. ));
  1309. char szHostDomain[WORK_BUFFER_SIZE + 2];
  1310. char * pszTemp = szHostDomain ;
  1311. char *pszDot1 = NULL;
  1312. char *pszDot2 = NULL;
  1313. DWORD error = ERROR_NOT_FOUND;
  1314. DWORD dwMinDomain = 2; // By default, assume domain is of the form: .domain-name.org
  1315. lstrcpy(szHostDomain, "wpad.");
  1316. pszTemp += (sizeof("wpad.") - 1);
  1317. if ( SockGetSingleValue(CONFIG_DOMAIN,
  1318. (LPBYTE)pszTemp,
  1319. WORK_BUFFER_SIZE - sizeof("wpad.")
  1320. ) != ERROR_SUCCESS )
  1321. {
  1322. lstrcpy(szHostDomain, "wpad.");
  1323. pszTemp = szHostDomain ;
  1324. pszTemp += (sizeof("wpad.") - 1);
  1325. }
  1326. if (*pszTemp == '\0')
  1327. {
  1328. // if the debug setting for no domain (netbios) or
  1329. // we didnt get back a valid domain, then just do the
  1330. // netbios name.
  1331. // XXBUG sockgetsinglevalue returns true even if there is no domain
  1332. INET_ASSERT(*(pszTemp - 1 ) == '.');
  1333. *(pszTemp - 1) = '\0';
  1334. }
  1335. // Now determine which form the domain name follows:
  1336. // domain-name.org
  1337. // domain-name.co.uk
  1338. pszDot1 = &szHostDomain[lstrlen(szHostDomain)-1];
  1339. while (pszDot1 >= szHostDomain && *pszDot1 != '.')
  1340. pszDot1--;
  1341. // Only check .?? endings
  1342. if (pszDot1 >= szHostDomain && (pszDot1 + 3 == &szHostDomain[lstrlen(szHostDomain)]) )
  1343. {
  1344. pszDot2 = pszDot1 - 1;
  1345. while (pszDot2 >= szHostDomain && *pszDot2 != '.')
  1346. pszDot2--;
  1347. if (pszDot2 >= szHostDomain && pszDot2 + 3 >= pszDot1)
  1348. {
  1349. // Domain ended in something of the form: .co.uk
  1350. // This requires at least 3 pieces then to be considered a domain
  1351. dwMinDomain = 3;
  1352. }
  1353. else if ((pszDot2 + 4) == pszDot1)
  1354. {
  1355. // Check domain endings of the form ending in .com.uk
  1356. // These special 3-letter pieces also need 3 dots to be classified
  1357. // as a domain. Unfortunately, we can't leverage the equivalent
  1358. // code used by cookies because there, the strings are reversed.
  1359. static const char *s_pachSpecialDomains[] = {"COM", "EDU", "NET", "ORG", "GOV", "MIL", "INT" };
  1360. for (int i=0; i < ARRAY_ELEMENTS(s_pachSpecialDomains); i++)
  1361. {
  1362. if (StrCmpNIC(pszDot2+1, s_pachSpecialDomains[i], 3) == 0)
  1363. {
  1364. dwMinDomain = 3;
  1365. break;
  1366. }
  1367. }
  1368. }
  1369. }
  1370. // Append a "." suffix to the domain name in order to suppress
  1371. // the DNS suffix search list.
  1372. if (lstrlen(szHostDomain)+1 < ARRAY_ELEMENTS(szHostDomain))
  1373. {
  1374. lstrcat(szHostDomain, ".");
  1375. dwMinDomain++;
  1376. }
  1377. while (TRUE)
  1378. {
  1379. PHOSTENT lpHostent = _I_gethostbyname(szHostDomain);
  1380. if ( lpHostent != NULL )
  1381. {
  1382. //
  1383. // Found a host, extract the IP address and form an URL to use.
  1384. //
  1385. char *pszAddressStr;
  1386. LPBYTE * addressList;
  1387. struct in_addr sin_addr;
  1388. LPSTR lpszAutoProxyUrl;
  1389. addressList = (LPBYTE *)lpHostent->h_addr_list;
  1390. *(LPDWORD)&sin_addr = *(LPDWORD)addressList[0] ;
  1391. pszAddressStr = _I_inet_ntoa (sin_addr);
  1392. INET_ASSERT(pszAddressStr);
  1393. lpszAutoProxyUrl = NewString(NULL,
  1394. lstrlen(pszAddressStr)
  1395. + sizeof("http:///")
  1396. + sizeof(PROXY_AUTO_DETECT_PATH));
  1397. if (lpszAutoProxyUrl)
  1398. {
  1399. wsprintf(lpszAutoProxyUrl, "http://%s/%s", pszAddressStr, PROXY_AUTO_DETECT_PATH );
  1400. *ppszAutoProxyUrl = lpszAutoProxyUrl;
  1401. error = ERROR_SUCCESS;
  1402. }
  1403. else
  1404. {
  1405. error = ERROR_NOT_ENOUGH_MEMORY;
  1406. }
  1407. goto quit;
  1408. }
  1409. else
  1410. {
  1411. //
  1412. // Did not find anything yet, reduce the domain level,
  1413. // and if we're in the root domain stop and return error
  1414. //
  1415. DWORD dwPeriodCnt = 0, dwNewEndLength = 0;
  1416. LPSTR lpszPeriod1 = NULL, lpszPeriod2 = NULL;
  1417. for (pszTemp = szHostDomain; *pszTemp; pszTemp++ )
  1418. {
  1419. if ( *pszTemp == '.' ) {
  1420. dwPeriodCnt ++;
  1421. if ( lpszPeriod1 == NULL ) {
  1422. lpszPeriod1 = pszTemp;
  1423. }
  1424. else if ( lpszPeriod2 == NULL ) {
  1425. lpszPeriod2 = pszTemp;
  1426. }
  1427. }
  1428. }
  1429. if ( dwPeriodCnt <= dwMinDomain)
  1430. {
  1431. error = ERROR_NOT_FOUND;
  1432. goto quit;
  1433. }
  1434. dwNewEndLength = lstrlen(lpszPeriod2);
  1435. MoveMemory(lpszPeriod1, lpszPeriod2, dwNewEndLength);
  1436. *(lpszPeriod1 + dwNewEndLength) = '\0';
  1437. }
  1438. }
  1439. quit:
  1440. DEBUG_LEAVE(error);
  1441. return error;
  1442. }
  1443. //================================================================================
  1444. // End of file
  1445. //================================================================================