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.

4111 lines
130 KiB

  1. // Copyright (c) 1998-1999 Microsoft Corporation
  2. /*******************************************************************************
  3. *
  4. * utildll.c
  5. *
  6. * UTILDLL multi-user utility support functions
  7. *
  8. *
  9. *******************************************************************************/
  10. /*
  11. * include files
  12. */
  13. #include <nt.h>
  14. #include <ntrtl.h>
  15. #include <nturtl.h>
  16. #include <ntddkbd.h>
  17. #include <ntddmou.h>
  18. #include <ntcsrsrv.h>
  19. #include <ntlsa.h>
  20. #include <ntsam.h>
  21. #include <windows.h>
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <nb30.h>
  25. #include <tapi.h>
  26. #include <raserror.h>
  27. #include <lmerr.h>
  28. #include <lmcons.h>
  29. #include <lmaccess.h>
  30. #include <lmserver.h>
  31. #include <lmwksta.h>
  32. #include <lmremutl.h>
  33. #include <lmapibuf.h>
  34. #include <shlwapi.h>
  35. #define INITGUID
  36. #include "objbase.h"
  37. #include "initguid.h"
  38. //#include "basetyps.h"
  39. #include "devguid.h"
  40. #include "setupapi.h"
  41. #include <winsta.h>
  42. #include <utildll.h>
  43. #include "..\inc\utilsub.h"
  44. #include "..\inc\ansiuni.h"
  45. #include "resource.h"
  46. /*
  47. * Hydrix helpers function internal defines
  48. */
  49. #define INITIAL_ENUMERATION_COUNT 16
  50. #define REGISTRY_NETCARDS TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards")
  51. #define REGISTRY_TITLE TEXT("Title")
  52. #define REGISTRY_SERVICE_NAME TEXT("ServiceName")
  53. #define REGISTRY_HIDDEN TEXT("Hidden")
  54. #define REGISTRY_ROUTE TEXT("Route")
  55. #define REGISTRY_NETBLINKAGE TEXT("SYSTEM\\CurrentControlSet\\Services\\NetBIOS\\Linkage")
  56. #define REGISTRY_NETBLINKAGE_LANAMAP TEXT("LanaMap")
  57. #define REGISTRY_SERVICES TEXT("SYSTEM\\CurrentControlSet\\Services")
  58. #define REGISTRY_DISPLAY_NAME TEXT("DisplayName")
  59. /*
  60. * TAPI defines.
  61. */
  62. #define LOW_MAJOR_VERSION 0x0001
  63. #define LOW_MINOR_VERSION 0x0003
  64. #define HIGH_MAJOR_VERSION 0x0002
  65. #define HIGH_MINOR_VERSION 0x0000
  66. #define LOW_VERSION ((LOW_MAJOR_VERSION << 16) | LOW_MINOR_VERSION)
  67. #define HIGH_VERSION ((HIGH_MAJOR_VERSION << 16) | HIGH_MINOR_VERSION)
  68. /*=============================================================================
  69. == Local Functions Defined
  70. =============================================================================*/
  71. BOOL CheckForComDevice( LPTSTR );
  72. int NetBiosLanaEnum( LANA_ENUM * pLanaEnum );
  73. DWORD EnumerateTapiPorts( PPDPARAMS pPdParams, ULONG Count, ULONG **ppEntries );
  74. VOID CALLBACK DummyTapiCallback(HANDLE, DWORD, DWORD, DWORD, DWORD, DWORD);
  75. BOOL GetAssociatedPortName(char *szKeyName, WCHAR *wszPortName);
  76. BOOL _UserInGroup( LPWSTR pwszUsername, LPWSTR pwszDomain, LPWSTR pwszGroup );
  77. /*******************************************************************************
  78. *
  79. * StandardErrorMessage - Hydrix helper function
  80. *
  81. * Output an error message with optional additional arguments like the
  82. * ErrorMessagexxx routines. Additionally, a standard error line will
  83. * also be output containing the error code and error message associated
  84. * with that code.
  85. *
  86. * ENTRY:
  87. * pszAppName (input)
  88. * Application name for error message box title.
  89. * hwndApp (input)
  90. * Owner window for error message box.
  91. * hinstApp (input)
  92. * Instance handle of application.
  93. * LogonId (input)
  94. * Optional WinStation LogonId for querying special error strings
  95. * from WinStation via WinStationGetInformation API. If this value
  96. * is LOGONID_NONE then no special error message code checking will
  97. * be done.
  98. * nId (input)
  99. * System message code to get standard error string for.
  100. * nErrorResourceID (input)
  101. * Resource ID of the format string to use in the error message.
  102. * ... (input)
  103. * Optional additional arguments to be used with format string.
  104. *
  105. * EXIT:
  106. *
  107. ******************************************************************************/
  108. void WINAPI
  109. StandardErrorMessage( LPCTSTR pszAppName,
  110. HWND hwndApp,
  111. HINSTANCE hinstApp,
  112. ULONG LogonId,
  113. UINT nId,
  114. int nErrorMessageLength,
  115. int nArgumentListLength,
  116. int nErrorResourceID, ...)
  117. {
  118. TCHAR* szClientErrorMessage = NULL;
  119. TCHAR* szClientResourceString = NULL;
  120. TCHAR* szError = NULL;
  121. TCHAR* szFormattedErrorMessage = NULL;
  122. TCHAR* szMessage = NULL;
  123. TCHAR szStandardErrorMessage[STANDARD_ERROR_TEXT_LENGTH + 1];
  124. va_list args;
  125. va_start( args, nErrorResourceID );
  126. szClientErrorMessage = (TCHAR*)malloc((nErrorMessageLength + 1) * sizeof(TCHAR));
  127. if (szClientErrorMessage)
  128. {
  129. LoadString( hinstApp, nErrorResourceID, szClientErrorMessage, nErrorMessageLength );
  130. szClientResourceString = (TCHAR*)malloc((wcslen(szClientErrorMessage) + nArgumentListLength + 1) * sizeof(TCHAR));
  131. if (szClientResourceString != NULL)
  132. {
  133. wvsprintf( szClientResourceString, szClientErrorMessage, args );
  134. LoadString( GetModuleHandle( UTILDLL_NAME ),
  135. IDS_STANDARD_ERROR_FORMAT, szStandardErrorMessage, STANDARD_ERROR_TEXT_LENGTH );
  136. szError = GetSystemMessage( LogonId, nId);
  137. if (szError != NULL)
  138. {
  139. szFormattedErrorMessage = (TCHAR*)malloc((wcslen(szStandardErrorMessage) + 10 + wcslen(szError) + 1) * sizeof(TCHAR));
  140. if (szFormattedErrorMessage != NULL)
  141. {
  142. wsprintf( szFormattedErrorMessage, szStandardErrorMessage, nId, szError);
  143. //lstrcpy(sz1, pszAppName);
  144. szMessage = (TCHAR*)malloc((wcslen(szClientResourceString) + wcslen(szFormattedErrorMessage) + 1) * sizeof(TCHAR));
  145. if (szMessage != NULL)
  146. {
  147. wcscpy(szMessage, szClientResourceString);
  148. wcscat(szMessage, szFormattedErrorMessage);
  149. MessageBox( hwndApp, szMessage, pszAppName, MB_OK | MB_ICONEXCLAMATION );
  150. free(szMessage);
  151. }
  152. free(szFormattedErrorMessage);
  153. }
  154. free (szError);
  155. }
  156. free(szClientResourceString);
  157. }
  158. free (szClientErrorMessage);
  159. }
  160. va_end(args);
  161. } // end StandardErrorMessage
  162. /*******************************************************************************
  163. *
  164. * GetSystemMessageA - Hydrix helper function (ANSI stub)
  165. *
  166. * Return the string associated with the specified system message.
  167. *
  168. * ENTRY:
  169. * (refer to GetSystemMessageW)
  170. * EXIT:
  171. * (refer to GetSystemMessageW)
  172. * If cannot allocate temporary UNICODE buffer to call GetSystemMessageW
  173. * with, the ntents of chBuffer will be set to the "(no error text
  174. * available)" string.
  175. *
  176. ******************************************************************************/
  177. LPSTR WINAPI
  178. GetSystemMessageA( ULONG LogonId,
  179. UINT nId
  180. /*LPSTR chBuffer,
  181. int cbBuffSize*/ )
  182. {
  183. LPWSTR uBuffer = NULL;
  184. LPSTR aBuffer = NULL;
  185. int length;
  186. //Call the GetSystemMessageW function
  187. uBuffer = GetSystemMessageW(LogonId, nId);
  188. if (uBuffer == NULL)
  189. {
  190. //If no message was returned from the GetSystemMessageW
  191. //function just return a generic error message
  192. aBuffer = malloc((NO_ERROR_TEXT_LENGTH + 1) * sizeof(char));
  193. if (aBuffer == NULL)
  194. return NULL;
  195. length = LoadStringA( GetModuleHandle( UTILDLL_NAME ),
  196. IDS_NO_ERROR_TEXT_AVAILABLE,
  197. aBuffer, NO_ERROR_TEXT_LENGTH );
  198. ASSERT(length);
  199. }
  200. else
  201. {
  202. length = wcslen(uBuffer) + 1;
  203. //Convert the result into ANSI in caller supplied buffer.
  204. aBuffer = malloc(length * sizeof(char));
  205. if (aBuffer != NULL)
  206. WideCharToMultiByte(CP_ACP, 0, uBuffer, length - 1, aBuffer, length, 0, 0);
  207. //Free the temporary buffer.
  208. free (uBuffer);
  209. }
  210. //Return message.
  211. return(aBuffer);
  212. } // end GetSystemMessageA
  213. /*******************************************************************************
  214. *
  215. * GetSystemMessageW - Hydrix helper function (UNICODE version)
  216. *
  217. * Return the string associated with the specified system message.
  218. *
  219. * ENTRY:
  220. * LogonId (input)
  221. * Optional WinStation LogonId for querying special error strings
  222. * from WinStation via WinStationGetInformation API. If this value
  223. * is LOGONID_NONE then no special error message code checking will
  224. * be done.
  225. * nId (input)
  226. * System message code to get string for.
  227. * chBuffer (input)
  228. * Points to buffer to fill with system message string.
  229. * cbBuffSize (input)
  230. * Maximum number of characters that can be placed in chBuffer.
  231. *
  232. * EXIT:
  233. * Returns chBuffer. Contents of chBuffer will always be set; to
  234. * the "(no error text available)" string if error.
  235. *
  236. * Note: the total length of chBuffer (including terminating NULL) will
  237. * not exceed the size of the internal temporary buffer (Buffer).
  238. *
  239. ******************************************************************************/
  240. //NA 3/9/01 IMPORTANT: Behavior has changed. Instead of expecting a buffer long
  241. //enough to accomodate the message, it now allocates the memory dynamically, so
  242. //it's up to the calling procedure to deallocate it.
  243. LPWSTR WINAPI
  244. GetSystemMessageW( ULONG LogonId,
  245. UINT nId
  246. /*LPWSTR chBuffer,
  247. int cbBuffSize*/ )
  248. {
  249. LPWSTR chBuffer = NULL;
  250. WCHAR StackBuffer[512];
  251. WCHAR* SpecialBuffer = NULL;
  252. WCHAR* Buffer = NULL;
  253. BOOL bSpecialCitrixError = FALSE;
  254. HINSTANCE cxerror = LoadLibraryW(L"cxerror.dll");
  255. int length = 0;
  256. StackBuffer[0]=0;
  257. //If we have a valid LogonId passed in, determine if the error
  258. //is a special code requiring that the specific error string be
  259. //queried from the WinStation.
  260. if ( LogonId != LOGONID_NONE )
  261. {
  262. switch ( nId )
  263. {
  264. case ERROR_CTX_TD_ERROR:
  265. length = LoadStringW( GetModuleHandle( UTILDLL_NAME ),
  266. IDS_NO_ADDITIONAL_ERROR_INFO,
  267. StackBuffer,
  268. sizeof(StackBuffer)/sizeof(WCHAR) );
  269. ASSERT(length);
  270. SpecialBuffer = malloc((length + 1) * sizeof(WCHAR));
  271. if (SpecialBuffer != NULL)
  272. {
  273. wcscpy(SpecialBuffer, StackBuffer);
  274. bSpecialCitrixError = TRUE;
  275. }
  276. break;
  277. default:
  278. break;
  279. }
  280. }
  281. //See if this is a Citrix error message first...
  282. if ( !cxerror ||
  283. !FormatMessageW( FORMAT_MESSAGE_IGNORE_INSERTS |
  284. FORMAT_MESSAGE_MAX_WIDTH_MASK |
  285. FORMAT_MESSAGE_FROM_HMODULE |
  286. FORMAT_MESSAGE_ALLOCATE_BUFFER,
  287. (LPCVOID)cxerror,
  288. nId,
  289. 0,
  290. (LPWSTR)&Buffer,
  291. 0,
  292. NULL ) )
  293. {
  294. //It's not a Citrix error message; fetch system message.
  295. if ( !FormatMessageW( FORMAT_MESSAGE_IGNORE_INSERTS |
  296. FORMAT_MESSAGE_MAX_WIDTH_MASK |
  297. FORMAT_MESSAGE_FROM_SYSTEM |
  298. FORMAT_MESSAGE_ALLOCATE_BUFFER,
  299. NULL,
  300. nId,
  301. 0,
  302. (LPWSTR)&Buffer,
  303. 0,
  304. NULL ) )
  305. {
  306. //It's not a system message; don't know what the message is...
  307. length = LoadStringW( GetModuleHandle( UTILDLL_NAME ),
  308. IDS_NO_ERROR_TEXT_AVAILABLE,
  309. StackBuffer,
  310. sizeof(StackBuffer)/sizeof(WCHAR) );
  311. ASSERT(length);
  312. Buffer = LocalAlloc(0,(length + 1) * sizeof(WCHAR));
  313. if (Buffer == NULL)
  314. {
  315. if (SpecialBuffer != NULL)
  316. free (SpecialBuffer);
  317. return NULL;
  318. }
  319. wcscpy(Buffer, StackBuffer);
  320. }
  321. }
  322. if ( cxerror )
  323. FreeLibrary(cxerror);
  324. length = wcslen(Buffer);
  325. if ( bSpecialCitrixError )
  326. length += wcslen(SpecialBuffer) + 2;
  327. chBuffer = malloc((length + 1) * sizeof(WCHAR));
  328. if (chBuffer != NULL)
  329. {
  330. wcscpy(chBuffer, Buffer);
  331. //If we fetched a special Citrix error string, tack it onto the end
  332. //of whatever we've buffered already.
  333. if ( bSpecialCitrixError )
  334. {
  335. lstrcatW(chBuffer, L" ");
  336. lstrcatW(chBuffer, SpecialBuffer);
  337. }
  338. }
  339. if (Buffer != NULL)
  340. LocalFree (Buffer);
  341. if (( bSpecialCitrixError ) && (SpecialBuffer != NULL))
  342. free (SpecialBuffer);
  343. return(chBuffer);
  344. } // end GetSystemMessageW
  345. /*******************************************************************************
  346. *
  347. * WinEnumerateDevices - Hydrix helper function
  348. *
  349. * Perform PD device enumeration for the specified PD.
  350. *
  351. * ENTRY:
  352. * hWnd (input)
  353. * Parent window for error message, if needed.
  354. * pPdConfig (input)
  355. * Points to PDCONFIG3 structure of the PD.
  356. * pEntries (output)
  357. * Points to variable to return number of devices that were enumerated.
  358. * bInSetup (input)
  359. * TRUE if we're operating in Setup; FALSE otherwise.
  360. *
  361. * EXIT:
  362. * (PPDPARAMS) Points to the PDPARAMS array containing the enumeration
  363. * results if sucessful. The caller must perform a LocalFree
  364. * of this array when done. NULL if error; error set for
  365. * GetLastError();
  366. * If the returned error code is anything other than
  367. * ERROR_NOT_ENOUGH_MEMORY, the caller can assume that none of the
  368. * requested devices were available to be enumerated.
  369. *
  370. ******************************************************************************/
  371. typedef BOOL (WINAPI * PPDENUMERATE)( PPDCONFIG3, PULONG, PPDPARAMS, PULONG, BOOL );
  372. PPDPARAMS WINAPI
  373. WinEnumerateDevices( HWND hWnd,
  374. PPDCONFIG3 pPdConfig,
  375. PULONG pEntries,
  376. BOOL bInSetup )
  377. {
  378. PPDENUMERATE pPdEnumerate;
  379. ULONG ByteCount;
  380. DWORD Error;
  381. int i;
  382. PPDPARAMS pPdParams = NULL;
  383. /*
  384. * Enumerate according to class.
  385. */
  386. switch ( pPdConfig->Data.SdClass ) {
  387. case SdAsync:
  388. pPdEnumerate = AsyncDeviceEnumerate;
  389. break;
  390. case SdNetwork:
  391. if ( pPdConfig->Data.PdFlag & PD_LANA ) {
  392. /*
  393. * This is a LANA based network PD (ie, NetBIOS). Perform
  394. * NetBIOS enumerate.
  395. */
  396. pPdEnumerate = NetBIOSDeviceEnumerate;
  397. }
  398. else {
  399. /*
  400. * This is a physical lan adapter based network (TCP/IP,
  401. * IPX, SPX, etc). Enumerate based on the associated network
  402. * protocol service name.
  403. */
  404. pPdEnumerate = NetworkDeviceEnumerate;
  405. }
  406. break;
  407. default:
  408. return(NULL);
  409. }
  410. /*
  411. * Call enumerate in loop till we hit enough buffer entries to handle
  412. * a complete enumeration. NOTE: some enumeration routines will return
  413. * the necessary ByteCount on 'insufficient buffer' status; others won't.
  414. */
  415. for ( ByteCount = 0, i = INITIAL_ENUMERATION_COUNT; ; i *= 2 ) {
  416. if ( pPdParams != NULL )
  417. LocalFree(pPdParams);
  418. pPdParams = (PPDPARAMS)LocalAlloc(
  419. LPTR,
  420. ByteCount ?
  421. ByteCount :
  422. (ByteCount = sizeof(PDPARAMS) * i) );
  423. if ( pPdParams == NULL ) {
  424. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  425. goto OutOfMemory;
  426. }
  427. /*
  428. * Perform enumeration and break loop if successful.
  429. */
  430. if ( (*pPdEnumerate)( pPdConfig,
  431. pEntries,
  432. pPdParams,
  433. &ByteCount,
  434. bInSetup ) )
  435. break;
  436. /*
  437. * If we received any other error other than 'insufficient buffer',
  438. * quit (quietly).
  439. */
  440. if ( (Error = GetLastError()) != ERROR_INSUFFICIENT_BUFFER )
  441. goto BadEnumerate;
  442. }
  443. /*
  444. * Success: return the PDPARAMS pointer.
  445. */
  446. return(pPdParams);
  447. /*==============================================================================
  448. * Error returns
  449. *============================================================================*/
  450. BadEnumerate:
  451. LocalFree(pPdParams);
  452. OutOfMemory:
  453. return(NULL);
  454. } // end WinEnumerateDevices
  455. /*******************************************************************************
  456. *
  457. * NetworkDeviceEnumerate - Hydrix helper function
  458. *
  459. * Returns a list of Lan Adapter indexes of network cards bound to the the
  460. * specified protocol. The Lan Adapter is returned in the LanAdapter field
  461. * of each PDPARAMS array. A LanAdapter value of 0 indicates 'any configured
  462. * network card'. Indexes >=1 indicate 1-based index into the specific
  463. * protocol's "servicename"\Linkage\Route registry entry to specify the
  464. * particular network card.
  465. *
  466. * ENTRY:
  467. * pPdConfig (input)
  468. * Points to PDCONFIG3 structure of the PD.
  469. * pEntries (output)
  470. * When the function finishes successfully, the variable pointed to
  471. * by the pEntries parameter contains the number of entries actually
  472. * returned.
  473. * pPdParams (output)
  474. * Points to the buffer to receive the enumeration results, which are
  475. * returned as an array of PDPARAMS structures.
  476. * pByteCount (input/output)
  477. * Points to a variable that specifies the size, in bytes, of the
  478. * pPdParams parameter. If the buffer is too small to receive all the
  479. * entries, on output this variable receives the required size of the
  480. * buffer.
  481. * bInSetup (input)
  482. * TRUE if we're operating in Setup; FALSE otherwise.
  483. *
  484. * EXIT:
  485. * TRUE: enumeration was sucessful; FALSE otherwise.
  486. *
  487. * The error code can be retrieved via GetLastError(), and are the
  488. * following possible values:
  489. * ERROR_INSUFFICIENT_BUFFER
  490. * enumeration failed because of an insufficient pPdParams
  491. * buffer size to contain all devices
  492. * ERROR_DEV_NOT_EXIST
  493. * The specified network's service was not found, indicating that
  494. * the protocol was not configured. This error code can be
  495. * interpreted as 'no devices are configured for the xxx protocol'
  496. * for reporting purposes.
  497. * ERROR_xxxx
  498. * Registry error code.
  499. *
  500. ******************************************************************************/
  501. BOOL WINAPI
  502. NetworkDeviceEnumerate( PPDCONFIG3 pPdConfig,
  503. PULONG pEntries,
  504. PPDPARAMS pPdParams,
  505. PULONG pByteCount,
  506. BOOL bInSetup )
  507. {
  508. ULONG i, Count;
  509. LPTSTR szRoute, szRouteStr;
  510. LONG Status;
  511. DWORD ValueSize, Type;
  512. TCHAR szKey[256];
  513. HKEY Handle;
  514. /*
  515. * Get maximum number of LanAdapter indexes that can be returned.
  516. */
  517. Count = *pByteCount / sizeof(PDPARAMS);
  518. /*
  519. * Form key for service name associated with this PD and fetch
  520. * the Linkage\Route strings.
  521. */
  522. _snwprintf( szKey, sizeof(szKey)/sizeof(TCHAR),
  523. TEXT("%s\\%s\\Linkage"), REGISTRY_SERVICES,
  524. pPdConfig->ServiceName );
  525. szKey[sizeof(szKey)/sizeof(TCHAR) - 1] = TEXT('\0');
  526. if ( (Status = RegOpenKeyEx( HKEY_LOCAL_MACHINE, szKey, 0, KEY_READ, &Handle ))
  527. != ERROR_SUCCESS ) {
  528. Status = ERROR_DEV_NOT_EXIST;
  529. goto BadRegistryOpen;
  530. }
  531. /*
  532. * Alloc and read in the linkage route multi-string.
  533. */
  534. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_ROUTE,
  535. NULL, &Type,
  536. NULL, &ValueSize ))
  537. != ERROR_SUCCESS) || (Type != REG_MULTI_SZ) )
  538. goto BadQuery1;
  539. if ( !(szRoute = (LPTSTR)LocalAlloc(LPTR, ValueSize)) ) {
  540. Status = ERROR_NOT_ENOUGH_MEMORY;
  541. goto BadAlloc;
  542. }
  543. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_ROUTE,
  544. NULL, &Type,
  545. (LPBYTE)szRoute, &ValueSize ))
  546. != ERROR_SUCCESS) )
  547. goto BadQuery2;
  548. /*
  549. * Close the registry key handle and count the route strings to obtain
  550. * the number of entries to report in the enumeration.
  551. */
  552. RegCloseKey(Handle);
  553. for ( i = 1, szRouteStr = szRoute; lstrlen(szRouteStr); i++ )
  554. szRouteStr += (lstrlen(szRouteStr) + 1);
  555. LocalFree(szRoute);
  556. /*
  557. * If we don't have enough PDPARAMS structures to report all of the
  558. * LanAdapter indexes, return error.
  559. */
  560. if ( i > Count ) {
  561. Status = ERROR_INSUFFICIENT_BUFFER;
  562. *pByteCount = (i * sizeof(PDPARAMS));
  563. goto BadBufferSize;
  564. }
  565. /*
  566. * Set the LanAdapter fields of the first 'i' PDPARAMS structures to
  567. * the indexes (0-based), set total number of entries, and return success.
  568. */
  569. for ( Count = 0, *pEntries = i; Count < i; pPdParams++, Count++ )
  570. pPdParams->Network.LanAdapter = (LONG)Count;
  571. return(TRUE);
  572. /*==============================================================================
  573. * Error returns
  574. *============================================================================*/
  575. BadQuery2:
  576. LocalFree(szRoute);
  577. BadAlloc:
  578. BadQuery1:
  579. RegCloseKey(Handle);
  580. BadBufferSize:
  581. BadRegistryOpen:
  582. SetLastError(Status);
  583. return(FALSE);
  584. } // end NetworkDeviceEnumerate
  585. /*******************************************************************************
  586. *
  587. * QueryCurrentWinStation - Hydrix helper function
  588. *
  589. * Query the currently logged-on WinStation information.
  590. *
  591. * ENTRY:
  592. * pWSName (output)
  593. * Points to string to place current WinStation name.
  594. * pUserName (output)
  595. * Points to string to place current User name.
  596. * pLogonId (output)
  597. * Points to ULONG to place current LogonId.
  598. * pFlags (output)
  599. * Points to ULONG to place current WinStation's flags.
  600. *
  601. * EXIT:
  602. * (BOOL) TRUE if the user's current WinStation information was queried
  603. * sucessfully; FALSE otherwise. The error code is set for
  604. * GetLastError() to retrieve.
  605. *
  606. ******************************************************************************/
  607. BOOL WINAPI
  608. QueryCurrentWinStation( PWINSTATIONNAME pWSName,
  609. LPTSTR pUserName,
  610. PULONG pLogonId,
  611. PULONG pFlags )
  612. {
  613. ULONG Flags = 0;
  614. WINSTATIONINFORMATION WSInfo;
  615. #ifdef WINSTA
  616. ULONG ReturnLength;
  617. #endif // WINSTA
  618. #ifdef WINSTA
  619. /*
  620. * Fetch the WinStation's basic information.
  621. */
  622. if ( !WinStationQueryInformation( SERVERNAME_CURRENT,
  623. LOGONID_CURRENT,
  624. WinStationInformation,
  625. &WSInfo,
  626. sizeof(WSInfo),
  627. &ReturnLength ) )
  628. goto BadQuery;
  629. /*
  630. * Check for shadow capability if WinStation is connected. If the
  631. * WinStation is not connected, we can't shadow.
  632. */
  633. if ( WSInfo.ConnectState != State_Disconnected ) {
  634. WDCONFIG WdConfig;
  635. /*
  636. * Query Wd config stuff.
  637. */
  638. if ( !WinStationQueryInformation( SERVERNAME_CURRENT,
  639. LOGONID_CURRENT,
  640. WinStationWd,
  641. &WdConfig,
  642. sizeof(WdConfig),
  643. &ReturnLength ) )
  644. goto BadQuery;
  645. /*
  646. * Set WinStation's Wd flags.
  647. */
  648. Flags = WdConfig.WdFlag;
  649. }
  650. #else
  651. lstrcpy(WSInfo.WinStationName, TEXT("console"));
  652. lstrcpy(WSInfo.UserName, TEXT("bonzo"));
  653. WSInfo.LogonId = 0;
  654. #endif // WINSTA
  655. /*
  656. * Set WinStation information into caller's variables, and return success.
  657. */
  658. lstrcpy( pWSName, WSInfo.WinStationName );
  659. lstrlwr(pWSName);
  660. lstrcpy( pUserName, WSInfo.UserName );
  661. lstrlwr(pUserName);
  662. *pLogonId = WSInfo.LogonId;
  663. *pFlags = Flags;
  664. return(TRUE);
  665. /*==============================================================================
  666. * Error returns
  667. *============================================================================*/
  668. #ifdef WINSTA
  669. BadQuery:
  670. #endif // WINSTA
  671. return(FALSE);
  672. } // end QueryCurrentWinStation
  673. /*******************************************************************************
  674. *
  675. * RegGetNetworkDeviceName - Hydrix helper function
  676. *
  677. * Obtain the network device name associated with the given WinStation PD.
  678. *
  679. * ENTRY:
  680. * hServer (input)
  681. * Handle to Hydrix Server
  682. * pPdConfig (input)
  683. * Points to the PDCONFIG3 structure for the WinStation's PD.
  684. * pPdParams (input)
  685. * Points to the PDPARAMS structure for the WinStation's PD.
  686. * szDeviceName (output)
  687. * Points to buffer to return the network device name.
  688. * nDeviceName (input)
  689. * Specifies the maxmum number of characters that can be stored in
  690. * szDeviceName.
  691. *
  692. * EXIT:
  693. * No return. Will always place a string representation of
  694. * pPdParams->Network.LanAdapter along with an appropriate error string
  695. * in pDeviceName if the network device name could not be read from the
  696. * registry.
  697. *
  698. ******************************************************************************/
  699. typedef struct _LANAMAP {
  700. BYTE enabled;
  701. BYTE lana;
  702. } LANAMAP, *PLANAMAP;
  703. LONG WINAPI
  704. RegGetNetworkDeviceName( HANDLE hServer,
  705. PPDCONFIG3 pPdConfig,
  706. PPDPARAMS pPdParams,
  707. LPTSTR szDeviceName,
  708. int nDeviceName )
  709. {
  710. int i, length;
  711. LPTSTR szRoute, szRouteStr, p;
  712. LONG Status = ERROR_SUCCESS;
  713. DWORD ValueSize, Type;
  714. TCHAR szKey[256];
  715. HKEY Handle;
  716. HKEY hkey_local_machine;
  717. PLANAMAP pLanaMap, pLana;
  718. if ( hServer == NULL)
  719. hkey_local_machine = HKEY_LOCAL_MACHINE;
  720. else
  721. hkey_local_machine = hServer;
  722. /*
  723. * Check for NetBIOS (PD_LANA) mapping or other mapping.
  724. */
  725. if ( !(pPdConfig->Data.PdFlag & PD_LANA) ) {
  726. LPTSTR szRoute, szRouteStr;
  727. /*
  728. * Non-LANA mapping. If the LanAdapter is 0, treat this as the
  729. * special 'all configured network cards' value and return that
  730. * string as the device name.
  731. */
  732. if ( pPdParams->Network.LanAdapter == 0 ) {
  733. TCHAR szString[256];
  734. length = LoadString( GetModuleHandle( UTILDLL_NAME ),
  735. IDS_ALL_LAN_ADAPTERS, szString, 256 );
  736. ASSERT(length);
  737. lstrncpy(szDeviceName, szString, nDeviceName);
  738. szDeviceName[nDeviceName-1] = TEXT('\0');
  739. return Status;
  740. }
  741. /*
  742. * Form key for service name associated with this PD and fetch
  743. * the Linkage\Route strings.
  744. */
  745. _snwprintf( szKey, sizeof(szKey)/sizeof(TCHAR),
  746. TEXT("%s\\%s\\Linkage"), REGISTRY_SERVICES,
  747. pPdConfig->ServiceName );
  748. szKey[sizeof(szKey)/sizeof(TCHAR) - 1] = TEXT('\0');
  749. if ( (Status = RegOpenKeyEx( hkey_local_machine, szKey, 0,
  750. KEY_READ, &Handle ))
  751. != ERROR_SUCCESS )
  752. goto Error;
  753. /*
  754. * Alloc and read in the linkage route multi-string.
  755. */
  756. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_ROUTE,
  757. NULL, &Type,
  758. NULL, &ValueSize ))
  759. != ERROR_SUCCESS) || (Type != REG_MULTI_SZ) )
  760. goto Error;
  761. if ( !(szRoute = (LPTSTR)LocalAlloc(LPTR, ValueSize)) ) {
  762. Status = ERROR_NOT_ENOUGH_MEMORY;
  763. goto Error;
  764. }
  765. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_ROUTE,
  766. NULL, &Type,
  767. (LPBYTE)szRoute, &ValueSize ))
  768. != ERROR_SUCCESS) ) {
  769. LocalFree(szRoute);
  770. goto Error;
  771. }
  772. /*
  773. * Close the registry key handle and point to the route string
  774. * associated with this LanAdapter index.
  775. */
  776. RegCloseKey(Handle);
  777. for ( i = 1, szRouteStr = szRoute;
  778. i < pPdParams->Network.LanAdapter; i++ ) {
  779. szRouteStr += (lstrlen(szRouteStr) + 1);
  780. if ( !lstrlen(szRouteStr) ) {
  781. /*
  782. * Error: Index past end of route multi-string.
  783. */
  784. LocalFree(szRoute);
  785. Status = ERROR_DEV_NOT_EXIST;
  786. goto Error;
  787. }
  788. }
  789. /*
  790. * Isolate the service string representing the lowest binding
  791. * in the route and convert it to its display name.
  792. */
  793. *(p = (szRouteStr + lstrlen(szRouteStr) - 1)) = TEXT('\0');
  794. for ( ; *p != TEXT('\"'); p-- );
  795. p++;
  796. if ( (Status = RegGetNetworkServiceName( hServer, p, szDeviceName, nDeviceName ))
  797. != ERROR_SUCCESS ) {
  798. LocalFree(szRoute);
  799. goto Error;
  800. }
  801. /*
  802. * Clean up and return.
  803. */
  804. LocalFree(szRoute);
  805. return Status;
  806. }
  807. else {
  808. /*
  809. * NetBIOS LANA #: see which LanaMap entry corresponds to the specified
  810. * Lan Adapter.
  811. */
  812. if ( (Status = RegOpenKeyEx( hkey_local_machine, REGISTRY_NETBLINKAGE, 0,
  813. KEY_READ, &Handle ))
  814. != ERROR_SUCCESS )
  815. goto Error;
  816. /*
  817. * Alloc and read the LanaMap
  818. */
  819. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_NETBLINKAGE_LANAMAP,
  820. NULL, &Type,
  821. NULL, &ValueSize))
  822. != ERROR_SUCCESS) || (Type != REG_BINARY) ) {
  823. RegCloseKey(Handle);
  824. goto Error;
  825. }
  826. if ( !(pLanaMap = (PLANAMAP)LocalAlloc(LPTR, ValueSize)) ) {
  827. Status = ERROR_NOT_ENOUGH_MEMORY;
  828. goto Error;
  829. }
  830. if ( (Status = RegQueryValueEx( Handle, REGISTRY_NETBLINKAGE_LANAMAP,
  831. NULL, &Type,
  832. (LPBYTE)pLanaMap, &ValueSize))
  833. != ERROR_SUCCESS ) {
  834. LocalFree(pLanaMap);
  835. RegCloseKey(Handle);
  836. goto Error;
  837. }
  838. /*
  839. * Loop through LanaMap to check for match with the specified Lan
  840. * Adapter #.
  841. */
  842. for ( pLana = pLanaMap, i = 0;
  843. i < (int)(ValueSize / sizeof(LANAMAP));
  844. i++, pLana++ ) {
  845. if ( pLana->lana == (BYTE)(pPdParams->Network.LanAdapter) ) {
  846. TCHAR szHighestBinding[256], szLowestBinding[256];
  847. LocalFree(pLanaMap);
  848. /*
  849. * Match found. Alloc and fetch the Route multi-string
  850. */
  851. if ( ((Status = RegQueryValueEx( Handle,
  852. REGISTRY_ROUTE,
  853. NULL, &Type,
  854. NULL, &ValueSize))
  855. != ERROR_SUCCESS) || (Type != REG_MULTI_SZ) ) {
  856. RegCloseKey(Handle);
  857. goto Error;
  858. }
  859. if ( !(szRoute = (LPTSTR)LocalAlloc(LPTR, ValueSize)) ) {
  860. Status = ERROR_NOT_ENOUGH_MEMORY;
  861. goto Error;
  862. }
  863. if ( (Status = RegQueryValueEx( Handle,
  864. REGISTRY_ROUTE,
  865. NULL, &Type,
  866. (LPBYTE)szRoute, &ValueSize))
  867. != ERROR_SUCCESS ) {
  868. LocalFree(szRoute);
  869. RegCloseKey(Handle);
  870. goto Error;
  871. }
  872. /*
  873. * Free the registry key handle and make a local copy of the
  874. * 'i'th multi string, which is the binding route for this lana.
  875. */
  876. RegCloseKey(Handle);
  877. for ( szRouteStr = szRoute; i > 0; i-- )
  878. szRouteStr += (lstrlen(szRouteStr) + 1);
  879. lstrncpy(szDeviceName, szRouteStr, nDeviceName);
  880. szDeviceName[nDeviceName-1] = TEXT('\0');
  881. LocalFree(szRoute);
  882. /*
  883. * Isolate the service string representing the highest binding
  884. * in the route and convert it to its display name.
  885. */
  886. szRouteStr = szDeviceName + 1; // skip first "
  887. for ( p = szRouteStr; *p && *p != TEXT('\"'); p++ );
  888. if ( !(*p) )
  889. goto Error;
  890. *p = TEXT('\0');
  891. if ( (Status = RegGetNetworkServiceName(
  892. hServer,
  893. szRouteStr,
  894. szHighestBinding,
  895. sizeof(szHighestBinding)/sizeof(TCHAR) ))
  896. != ERROR_SUCCESS )
  897. goto Error;
  898. /*
  899. * Isolate the service string representing the lowest binding
  900. * in the route and convert it to its display name.
  901. */
  902. if ( !(*(szRouteStr = p+1)) ) {
  903. *szLowestBinding = TEXT('\0');
  904. }
  905. else {
  906. *(p = (szRouteStr + lstrlen(szRouteStr) - 1)) = TEXT('\0');
  907. for ( ; *p != TEXT('\"'); p-- );
  908. p++;
  909. if ( (Status = RegGetNetworkServiceName(
  910. hServer,
  911. p,
  912. szLowestBinding,
  913. sizeof(szLowestBinding)/sizeof(TCHAR) ))
  914. != ERROR_SUCCESS )
  915. goto Error;
  916. }
  917. /*
  918. * Build the complete name string.
  919. */
  920. _snwprintf( szDeviceName, nDeviceName, TEXT("%s => %s"),
  921. szHighestBinding, szLowestBinding );
  922. /*
  923. * Return.
  924. */
  925. return ERROR_SUCCESS;
  926. }
  927. }
  928. /*
  929. * No match found.
  930. */
  931. LocalFree(pLanaMap);
  932. RegCloseKey(Handle);
  933. goto Error;
  934. }
  935. /*==============================================================================
  936. * Error returns
  937. *============================================================================*/
  938. Error:
  939. {
  940. TCHAR sz1[256], sz2[1024];
  941. int length;
  942. length = LoadString( GetModuleHandle( UTILDLL_NAME ),
  943. (pPdConfig->Data.PdFlag & PD_LANA) ?
  944. IDP_ERROR_REGLANA :
  945. IDP_ERROR_REGNETCARD,
  946. sz1, 256 );
  947. wsprintf( sz2, sz1, pPdParams->Network.LanAdapter, Status );
  948. lstrncpy(szDeviceName, sz2, nDeviceName);
  949. szDeviceName[nDeviceName-1] = TEXT('\0');
  950. }
  951. return Status;
  952. } // end RegGetNetworkDeviceName
  953. /*******************************************************************************
  954. *
  955. * RegGetNetworkServiceName - Hydrix helper function
  956. *
  957. * Obtain the display name associated with a given network service name.
  958. * If the service is a reference to a physical network card, will return
  959. * the title of the card as obtained from the LOCAL_MACHINE\Software\
  960. * Microsoft\Windows NT\NetworkCards registry.
  961. *
  962. * ENTRY:
  963. * hServer (input)
  964. * Handle of the Hydrix Server
  965. * szServiceKey (input)
  966. * Key string into the LOCAL_MACHINE\System\CurrentControlSet\Services
  967. * registry.
  968. * szServiceName (output)
  969. * Points to buffer to return the service's display name.
  970. * nServiceName (input)
  971. * Specifies the maxmum number of characters that can be stored in
  972. * szServiceName.
  973. *
  974. * EXIT:
  975. * ERROR_SUCCESS if a service name was sucessfully found and returned;
  976. * error code otherwise.
  977. *
  978. * NOTE: If the service name is for an entry in the NetworkCards resistry
  979. * and the entry is flagged as 'hidden', the service name will be
  980. * blank. This will flag caller's logic to ignore the entry.
  981. *
  982. ******************************************************************************/
  983. LONG WINAPI
  984. RegGetNetworkServiceName( HANDLE hServer,
  985. LPTSTR szServiceKey,
  986. LPTSTR szServiceName,
  987. int nServiceName )
  988. {
  989. LONG Status;
  990. DWORD ValueSize, Type, dwValue;
  991. TCHAR szKey[256];
  992. LPTSTR szTemp;
  993. HKEY Handle;
  994. HKEY hkey_local_machine;
  995. if (hServer == NULL)
  996. hkey_local_machine = HKEY_LOCAL_MACHINE;
  997. else
  998. hkey_local_machine = hServer;
  999. lstrnprintf( szKey, sizeof(szKey)/sizeof(TCHAR),
  1000. TEXT("%s\\%s"), REGISTRY_SERVICES, szServiceKey );
  1001. szKey[sizeof(szKey)/sizeof(TCHAR) - 1] = TEXT('\0');
  1002. if ( (Status = RegOpenKeyEx( hkey_local_machine,
  1003. szKey, 0,
  1004. KEY_READ, &Handle ))
  1005. != ERROR_SUCCESS )
  1006. return(Status);
  1007. /*
  1008. * Alloc and read in the service's DisplayName value (if there).
  1009. */
  1010. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_DISPLAY_NAME,
  1011. NULL, &Type,
  1012. NULL, &ValueSize ))
  1013. != ERROR_SUCCESS) || (Type != REG_SZ) ) {
  1014. HKEY Subkey;
  1015. FILETIME KeyTime;
  1016. DWORD i;
  1017. /*
  1018. * The service doesn't have a DisplayName associated with it (it's a
  1019. * Network Card's service name). Traverse the NetworkCards registry
  1020. * entries and find the entry associated with this service name
  1021. * (if it exists).
  1022. */
  1023. RegCloseKey(Handle);
  1024. if ( (Status = RegOpenKeyEx( hkey_local_machine,
  1025. REGISTRY_NETCARDS, 0,
  1026. KEY_READ, &Handle ))
  1027. != ERROR_SUCCESS )
  1028. return(Status);
  1029. for ( i = 0, ValueSize = sizeof(szKey)/sizeof(TCHAR) ;
  1030. RegEnumKeyEx( Handle, i, szKey, &ValueSize,
  1031. NULL, NULL, NULL, &KeyTime ) == ERROR_SUCCESS ;
  1032. i++, ValueSize = sizeof(szKey)/sizeof(TCHAR) ) {
  1033. /*
  1034. * Open the Network Card's registry.
  1035. */
  1036. if ( (Status = RegOpenKeyEx( Handle,
  1037. szKey, 0,
  1038. KEY_READ, &Subkey ))
  1039. != ERROR_SUCCESS ) {
  1040. RegCloseKey(Handle);
  1041. return(Status);
  1042. }
  1043. /*
  1044. * Alloc and fetch the card's service name. Continue net card
  1045. * enumeration if service name not found.
  1046. */
  1047. if ( ((Status = RegQueryValueEx( Subkey,
  1048. REGISTRY_SERVICE_NAME,
  1049. NULL, &Type,
  1050. NULL, &ValueSize))
  1051. != ERROR_SUCCESS) || (Type != REG_SZ) ) {
  1052. RegCloseKey(Subkey);
  1053. continue;
  1054. }
  1055. szTemp = (LPTSTR)LocalAlloc(LPTR, ValueSize);
  1056. if(NULL == szTemp)
  1057. {
  1058. RegCloseKey(Subkey);
  1059. RegCloseKey(Handle);
  1060. return ERROR_NOT_ENOUGH_MEMORY;
  1061. }
  1062. if ( (Status = RegQueryValueEx( Subkey,
  1063. REGISTRY_SERVICE_NAME,
  1064. NULL, &Type,
  1065. (LPBYTE)szTemp, &ValueSize))
  1066. != ERROR_SUCCESS ) {
  1067. LocalFree(szTemp);
  1068. RegCloseKey(Subkey);
  1069. continue;
  1070. }
  1071. /*
  1072. * If the current Network Card's service name matches the service
  1073. * name that we're looking for, fetch the card's title.
  1074. */
  1075. if ( !lstrcmpi(szServiceKey, szTemp) ) {
  1076. LocalFree(szTemp);
  1077. ValueSize = sizeof(dwValue);
  1078. if ( (RegQueryValueEx( Subkey, REGISTRY_HIDDEN,
  1079. NULL, &Type,
  1080. (LPBYTE)&dwValue, &ValueSize )
  1081. == ERROR_SUCCESS) &&
  1082. (Type == REG_DWORD) &&
  1083. (dwValue == 1) ) {
  1084. /*
  1085. * Entry is hidden: return empty title.
  1086. */
  1087. *szServiceName = TEXT('\0');
  1088. }
  1089. else {
  1090. /*
  1091. * Entry is not hidden: Alloc for the card's title.
  1092. */
  1093. if ( ((Status = RegQueryValueEx( Subkey,
  1094. REGISTRY_TITLE,
  1095. NULL, &Type,
  1096. NULL, &ValueSize))
  1097. != ERROR_SUCCESS) || (Type != REG_SZ) ) {
  1098. RegCloseKey(Subkey);
  1099. RegCloseKey(Handle);
  1100. return(Status);
  1101. }
  1102. szTemp = (LPTSTR)LocalAlloc(LPTR, ValueSize);
  1103. if(NULL == szTemp)
  1104. {
  1105. RegCloseKey(Subkey);
  1106. RegCloseKey(Handle);
  1107. return ERROR_NOT_ENOUGH_MEMORY;
  1108. }
  1109. /*
  1110. * Fetch the title.
  1111. */
  1112. if ( (Status = RegQueryValueEx( Subkey,
  1113. REGISTRY_TITLE,
  1114. NULL, &Type,
  1115. (LPBYTE)szTemp, &ValueSize))
  1116. != ERROR_SUCCESS ) {
  1117. LocalFree(szTemp);
  1118. RegCloseKey(Subkey);
  1119. RegCloseKey(Handle);
  1120. return(Status);
  1121. }
  1122. /*
  1123. * Copy the card's title.
  1124. */
  1125. lstrncpy(szServiceName, szTemp, nServiceName);
  1126. szServiceName[nServiceName-1] = TEXT('\0');
  1127. LocalFree(szTemp);
  1128. }
  1129. /*
  1130. * Clean up and return success.
  1131. */
  1132. RegCloseKey(Subkey);
  1133. RegCloseKey(Handle);
  1134. return(ERROR_SUCCESS);
  1135. }
  1136. else {
  1137. /*
  1138. * This is not the Network Card that we're looking for. Close
  1139. * it's registry key, free the service name buffer, and continue
  1140. * enumeration loop.
  1141. */
  1142. LocalFree(szTemp);
  1143. RegCloseKey(Subkey);
  1144. }
  1145. }
  1146. /*
  1147. * Network Card not found with service name matching the one supplied.
  1148. * Close NetworkCards registry key and return failure,
  1149. */
  1150. RegCloseKey(Handle);
  1151. return(ERROR_DEV_NOT_EXIST);
  1152. }
  1153. else {
  1154. szTemp = (LPTSTR)LocalAlloc(LPTR, ValueSize);
  1155. if(NULL == szTemp)
  1156. {
  1157. RegCloseKey(Handle);
  1158. return ERROR_NOT_ENOUGH_MEMORY;
  1159. }
  1160. if ( ((Status = RegQueryValueEx( Handle, REGISTRY_DISPLAY_NAME,
  1161. NULL, &Type,
  1162. (LPBYTE)szTemp, &ValueSize ))
  1163. == ERROR_SUCCESS) )
  1164. lstrncpy(szServiceName, szTemp, nServiceName);
  1165. szServiceName[nServiceName-1] = TEXT('\0');
  1166. LocalFree(szTemp);
  1167. RegCloseKey(Handle);
  1168. return(Status);
  1169. }
  1170. } // end RegGetNetworkServiceName
  1171. /*******************************************************************************
  1172. *
  1173. * AsyncDeviceEnumerate - Hydrix helper function
  1174. *
  1175. * Returns a list of async device names. This will return both 'COM' devices
  1176. * and TAPI configured modems.
  1177. *
  1178. * ENTRY:
  1179. * pPdConfig (input)
  1180. * Points to PDCONFIG3 structure of the PD.
  1181. * pEntries (output)
  1182. * When the function finishes successfully, the variable pointed to
  1183. * by the pEntries parameter contains the number of entries actually
  1184. * returned.
  1185. * pPdParams (output)
  1186. * Points to the buffer to receive the enumeration results, which are
  1187. * returned as an array of PDPARAMS structures.
  1188. * pByteCount (input/output)
  1189. * Points to a variable that specifies the size, in bytes, of the
  1190. * pPdParams parameter. If the buffer is too small to receive all the
  1191. * entries, on output this variable is set to 0 (caller should double
  1192. * the input buffer and try again).
  1193. * bInSetup (input)
  1194. * TRUE if we're operating in Setup; FALSE otherwise.
  1195. * EXIT:
  1196. * TRUE: enumeration was sucessful; FALSE otherwise.
  1197. *
  1198. * The error code can be retrieved via GetLastError(), and are the
  1199. * following possible values:
  1200. * ERROR_NOT_ENOUGH_MEMORY
  1201. * not enough memory to allocate working buffer(s)
  1202. * ERROR_INSUFFICIENT_BUFFER
  1203. * enumeration failed because of an insufficient pPdParams
  1204. * buffer size to contain all devices
  1205. * ERROR_DEV_NOT_EXIST
  1206. * the QueryDosDevice call failed. This error code can be
  1207. * interpreted as 'no async devices are configured' for reporting
  1208. * purposes.
  1209. *
  1210. ******************************************************************************/
  1211. #define MAX_QUERY_BUFFER (1024*16)
  1212. BOOL WINAPI
  1213. AsyncDeviceEnumerate( PPDCONFIG3 pPdConfig,
  1214. PULONG pEntries,
  1215. PPDPARAMS pPdParams,
  1216. PULONG pByteCount,
  1217. BOOL bInSetup )
  1218. {
  1219. DWORD Error = ERROR_SUCCESS;
  1220. ULONG Count;
  1221. HKEY hRoot = NULL;
  1222. DWORD BufSize, NameSize, Type, Index, SaveBufSize, SaveNameSize;
  1223. LONG Result = 0;
  1224. LONG nDosDevice = 0;
  1225. LPTSTR pBuffer = NULL, pBufferEnd = NULL;
  1226. LPTSTR pNameBuffer = NULL, pName;
  1227. BOOLEAN bRetVal = FALSE;
  1228. /*
  1229. * Get maximum number of names that can be returned
  1230. */
  1231. Count = *pByteCount / sizeof(PDPARAMS);
  1232. *pByteCount = 0;
  1233. *pEntries = 0;
  1234. /*
  1235. * Allocate buffer
  1236. */
  1237. SaveBufSize = MAX_QUERY_BUFFER;
  1238. SaveNameSize = MAX_QUERY_BUFFER;
  1239. BufSize = SaveBufSize;
  1240. NameSize = SaveNameSize;
  1241. if ( !(pBuffer = (LPTSTR)LocalAlloc(LPTR, BufSize * sizeof(TCHAR))) ) {
  1242. Error = ERROR_NOT_ENOUGH_MEMORY;
  1243. goto Cleanup;
  1244. }
  1245. if ( !(pNameBuffer = (LPTSTR)LocalAlloc(LPTR, NameSize)) ) {
  1246. Error = ERROR_NOT_ENOUGH_MEMORY;
  1247. goto Cleanup;
  1248. }
  1249. /*
  1250. * If we're in Setup, obtain devices from the SERIALCOMM section in
  1251. * LOCAL MACHINE registry, since the serial device driver(s) are most
  1252. * likely not running. Otherwise, we'll query all DosDevices and
  1253. * return those that are COM devices and are not currently in use.
  1254. */
  1255. if ( bInSetup ) {
  1256. Result = RegOpenKeyEx( HKEY_LOCAL_MACHINE,
  1257. TEXT("HARDWARE\\DEVICEMAP\\SERIALCOMM"),
  1258. 0, // Reserved
  1259. KEY_ENUMERATE_SUB_KEYS|KEY_QUERY_VALUE,
  1260. &hRoot );
  1261. if ( Result != ERROR_SUCCESS ) {
  1262. //
  1263. // This is usually the result of having no ports, so the key
  1264. // SERIALCOMM does not exist.
  1265. //
  1266. goto Cleanup;
  1267. }
  1268. for ( Index=0; ; Index++ ) {
  1269. // Each enumerate stomps on our buffer sizes
  1270. BufSize = SaveBufSize;
  1271. NameSize = SaveNameSize;
  1272. Result = RegEnumValue( hRoot,
  1273. Index,
  1274. pBuffer,
  1275. &BufSize,
  1276. NULL, // Reserved
  1277. &Type,
  1278. (LPBYTE)pNameBuffer,
  1279. &NameSize );
  1280. if ( Result == ERROR_INSUFFICIENT_BUFFER ) {
  1281. // Reallocate the buffer
  1282. LocalFree( pBuffer );
  1283. pBuffer = (LPTSTR)LocalAlloc(LPTR, BufSize * sizeof(TCHAR));
  1284. if ( pBuffer == NULL ) {
  1285. // Try and reallocate next key
  1286. SaveBufSize = BufSize = 0;
  1287. continue;
  1288. }
  1289. else {
  1290. SaveBufSize = BufSize;
  1291. }
  1292. // Reallocate the name buffer
  1293. LocalFree( pNameBuffer );
  1294. pNameBuffer = (LPTSTR)LocalAlloc(LPTR, NameSize);
  1295. if ( pNameBuffer == NULL ) {
  1296. // Try and reallocate next key
  1297. SaveNameSize = NameSize = 0;
  1298. continue;
  1299. }
  1300. else {
  1301. SaveNameSize = NameSize;
  1302. }
  1303. Result = RegEnumValue( hRoot,
  1304. Index,
  1305. pBuffer,
  1306. &BufSize,
  1307. NULL, // Reserved
  1308. &Type,
  1309. (LPBYTE)pNameBuffer,
  1310. &NameSize );
  1311. }
  1312. // We are done
  1313. if ( Result == ERROR_NO_MORE_ITEMS ) {
  1314. bRetVal = TRUE;
  1315. Result = 0;
  1316. goto Cleanup;
  1317. }
  1318. if ( Result != ERROR_SUCCESS ) {
  1319. goto Cleanup;
  1320. }
  1321. if ( Count > 0 ) {
  1322. if ( Type != REG_SZ ) {
  1323. continue;
  1324. }
  1325. pPdParams->SdClass = SdAsync;
  1326. lstrcpy( pPdParams->Async.DeviceName, pNameBuffer );
  1327. pPdParams++;
  1328. Count--;
  1329. (*pEntries)++;
  1330. }
  1331. else {
  1332. Error = ERROR_INSUFFICIENT_BUFFER;
  1333. goto Cleanup;
  1334. }
  1335. }
  1336. }
  1337. else { // not in Setup
  1338. /*
  1339. * Get complete device list
  1340. */
  1341. nDosDevice = QueryDosDevice( NULL, pBuffer, MAX_QUERY_BUFFER );
  1342. if ( !nDosDevice)
  1343. {
  1344. Error = ERROR_DEV_NOT_EXIST;
  1345. goto Cleanup;
  1346. }
  1347. /*
  1348. * Find each device name in list
  1349. */
  1350. pName = pBuffer;
  1351. pBufferEnd = pBuffer + nDosDevice;
  1352. while ( *pName && (pName < pBufferEnd) ) {
  1353. if ( CheckForComDevice( pName ) ) {
  1354. if ( Count > 0 ) {
  1355. pPdParams->SdClass = SdAsync;
  1356. lstrcpy( pPdParams->Async.DeviceName, pName );
  1357. pPdParams++;
  1358. Count--;
  1359. (*pEntries)++;
  1360. }
  1361. else {
  1362. Error = ERROR_INSUFFICIENT_BUFFER;
  1363. goto Cleanup;
  1364. }
  1365. }
  1366. pName += (lstrlen(pName) + 1);
  1367. }
  1368. bRetVal = TRUE; // sucessful enumeration
  1369. }
  1370. Cleanup:
  1371. /*
  1372. * If no errors yet, perform TAPI device enumeration.
  1373. */
  1374. if ( bRetVal ) {
  1375. if ( (Error = EnumerateTapiPorts( pPdParams,
  1376. Count,
  1377. &pEntries ))
  1378. != ERROR_SUCCESS ) {
  1379. bRetVal = FALSE;
  1380. }
  1381. }
  1382. if ( pBuffer ) {
  1383. LocalFree( pBuffer );
  1384. }
  1385. if ( pNameBuffer ) {
  1386. LocalFree( pNameBuffer );
  1387. }
  1388. if ( hRoot ) {
  1389. CloseHandle( hRoot );
  1390. }
  1391. SetLastError(Error);
  1392. return(bRetVal);
  1393. } // AsyncDeviceEnumerate
  1394. /*******************************************************************************
  1395. *
  1396. * NetBIOSDeviceEnumerate - Hydrix helper function
  1397. *
  1398. * Returns a list of NetBIOS lana adapter numbers.
  1399. *
  1400. * ENTRY:
  1401. * pPdConfig (input)
  1402. * Points to PDCONFIG3 structure of the PD.
  1403. * pEntries (output)
  1404. * When the function finishes successfully, the variable pointed to
  1405. * by the pEntries parameter contains the number of entries actually
  1406. * returned.
  1407. * pPdParams (output)
  1408. * Points to the buffer to receive the enumeration results, which are
  1409. * returned as an array of PDPARAMS structures.
  1410. * pByteCount (input/output)
  1411. * Points to a variable that specifies the size, in bytes, of the
  1412. * pPdParams parameter. If the buffer is too small to receive all the
  1413. * entries, on output this variable receives the required size of the
  1414. * buffer.
  1415. * bInSetup (input)
  1416. * TRUE if we're operating in Setup; FALSE otherwise.
  1417. *
  1418. * EXIT:
  1419. * TRUE: enumeration was sucessful; FALSE otherwise.
  1420. *
  1421. * The error code can be retrieved via GetLastError(), and are the
  1422. * following possible values:
  1423. * v ERROR_INSUFFICIENT_BUFFER
  1424. * enumeration failed because of an insufficient pPdParams
  1425. * buffer size to contain all devices
  1426. * ERROR_DEV_NOT_EXIST
  1427. * the NetBiosLanaEnum call failed. This error code can be
  1428. * interpreted as 'no netbios devices are configured' for reporting
  1429. * purposes.
  1430. *
  1431. ******************************************************************************/
  1432. BOOL WINAPI
  1433. NetBIOSDeviceEnumerate( PPDCONFIG3 pPdConfig,
  1434. PULONG pEntries,
  1435. PPDPARAMS pPdParams,
  1436. PULONG pByteCount,
  1437. BOOL bInSetup )
  1438. {
  1439. LANA_ENUM LanaEnum;
  1440. NTSTATUS Status;
  1441. int i;
  1442. /*
  1443. * Issue netbios enum command
  1444. */
  1445. if ( Status = NetBiosLanaEnum( &LanaEnum ) ) {
  1446. SetLastError(ERROR_DEV_NOT_EXIST);
  1447. return(FALSE);
  1448. }
  1449. /*
  1450. * Make sure user's buffer is big enough
  1451. */
  1452. if ( LanaEnum.length > (*pByteCount / sizeof(PDPARAMS)) ) {
  1453. *pByteCount = LanaEnum.length * sizeof(PDPARAMS);
  1454. SetLastError(ERROR_INSUFFICIENT_BUFFER);
  1455. return(FALSE);
  1456. }
  1457. /*
  1458. * Return number of entries
  1459. */
  1460. *pEntries = (ULONG) LanaEnum.length;
  1461. /*
  1462. * Return lana numbers
  1463. */
  1464. for ( i=0; i < (int)LanaEnum.length; i++, pPdParams++ ) {
  1465. pPdParams->SdClass = SdNetwork;
  1466. pPdParams->Network.LanAdapter = LanaEnum.lana[i];
  1467. }
  1468. return(TRUE);
  1469. } // NetBIOSDeviceEnumerate
  1470. /*******************************************************************************
  1471. *
  1472. * FormDecoratedAsyncDeviceName - Hydrix helper function
  1473. *
  1474. * Format a decorated async device name if a modem is defined.
  1475. *
  1476. * ENTRY:
  1477. * pDeviceName (output)
  1478. * Points to buffer that will contain the decorated name (or undecorated
  1479. * name if no modem).
  1480. * pPdParams (input)
  1481. * Points to the ASYNCCONFIG structure to be used in forming the
  1482. * decorated name.
  1483. *
  1484. * EXIT:
  1485. *
  1486. ******************************************************************************/
  1487. void WINAPI
  1488. FormDecoratedAsyncDeviceName( LPTSTR pDeviceName,
  1489. PASYNCCONFIG pAsyncConfig )
  1490. {
  1491. if ( *(pAsyncConfig->ModemName) )
  1492. wsprintf( pDeviceName, TEXT("%s - %s"),
  1493. pAsyncConfig->DeviceName,
  1494. pAsyncConfig->ModemName );
  1495. else
  1496. lstrcpy( pDeviceName,
  1497. pAsyncConfig->DeviceName );
  1498. } // end FormDecoratedAsyncDeviceName
  1499. /*******************************************************************************
  1500. *
  1501. * ParseDecoratedAsyncDeviceName - Hydrix helper function
  1502. *
  1503. * Given a decorated async device name, form it's component device and
  1504. * modem name portions.
  1505. *
  1506. * ENTRY:
  1507. * pDeviceName (input)
  1508. * Points to buffer that contain the decorated async device name.
  1509. * pAsyncConfig (output)
  1510. * Points to the ASYNCCONFIG structure to save the device (in
  1511. * ->DeviceName) and modem (in ->ModemName).
  1512. * EXIT:
  1513. *
  1514. ******************************************************************************/
  1515. void WINAPI
  1516. ParseDecoratedAsyncDeviceName( LPCTSTR pDeviceName,
  1517. PASYNCCONFIG pAsyncConfig )
  1518. {
  1519. int i;
  1520. /*
  1521. * Form DeviceName portion up to the first blank.
  1522. */
  1523. for ( i=0; *pDeviceName && (*pDeviceName != TEXT(' ')); i++ )
  1524. (pAsyncConfig->DeviceName)[i] = *pDeviceName++;
  1525. (pAsyncConfig->DeviceName)[i] = TEXT('\0');
  1526. /*
  1527. * Skip the ' - ' decoration (to the next space).
  1528. */
  1529. if ( *pDeviceName ) {
  1530. for ( pDeviceName++;
  1531. *pDeviceName && (*pDeviceName != TEXT(' '));
  1532. pDeviceName++ );
  1533. }
  1534. /*
  1535. * Form the ModemName from the remainder of the string.
  1536. */
  1537. i = 0;
  1538. if ( *pDeviceName ) {
  1539. for ( pDeviceName++; *pDeviceName ; i++ )
  1540. (pAsyncConfig->ModemName)[i] = *pDeviceName++;
  1541. }
  1542. (pAsyncConfig->ModemName)[i] = TEXT('\0');
  1543. } // end ParseDecoratedAsyncDeviceName
  1544. /*******************************************************************************
  1545. *
  1546. * SetupAsyncCdConfig - Hydrix helper function
  1547. *
  1548. * Given a properly configured ASYNCCONFIG structure, set up a given
  1549. * CDCONFIG structure.
  1550. *
  1551. * ENTRY:
  1552. * pAsyncConfig (input)
  1553. * Points properly configured ASYNCCONFIG structure.
  1554. * pCdConfig (output)
  1555. * Points to the CDCONFIG structure to setup.
  1556. * EXIT:
  1557. *
  1558. ******************************************************************************/
  1559. void WINAPI
  1560. SetupAsyncCdConfig( PASYNCCONFIG pAsyncConfig,
  1561. PCDCONFIG pCdConfig )
  1562. {
  1563. memset(pCdConfig, 0, sizeof(CDCONFIG));
  1564. if ( *(pAsyncConfig->ModemName) ) {
  1565. pCdConfig->CdClass = CdModem;
  1566. lstrcpy( pCdConfig->CdName, TEXT("cdmodem") );
  1567. lstrcpy( pCdConfig->CdDLL, TEXT("cdmodem.dll") );
  1568. }
  1569. } // end SetupAsyncCdConfig
  1570. /*******************************************************************************
  1571. *
  1572. * InstallModem - Hydrix helper function
  1573. *
  1574. * Install UNIMODEM modem(s).
  1575. *
  1576. * ENTRY:
  1577. * hwndOwner
  1578. * Window handle that owns the installation dialog.
  1579. * EXIT:
  1580. * TRUE: installation completed; FALSE: error or user canceled.
  1581. *
  1582. * If an error, the error code can be retrieved via GetLastError().
  1583. *
  1584. ******************************************************************************/
  1585. BOOL WINAPI
  1586. InstallModem( HWND hwndOwner )
  1587. {
  1588. HDEVINFO hdi;
  1589. BOOL bStatus = FALSE;
  1590. HCURSOR hcur = SetCursor(LoadCursor(NULL, IDC_WAIT));
  1591. /*
  1592. * Create a modem DeviceInfoSet
  1593. */
  1594. if ( (hdi = SetupDiCreateDeviceInfoList( (LPGUID)&GUID_DEVCLASS_MODEM,
  1595. hwndOwner )) ) {
  1596. SP_INSTALLWIZARD_DATA iwd;
  1597. /*
  1598. * Initialize the InstallWizardData
  1599. */
  1600. memset(&iwd, 0, sizeof(iwd));
  1601. iwd.ClassInstallHeader.cbSize = sizeof(SP_CLASSINSTALL_HEADER);
  1602. iwd.ClassInstallHeader.InstallFunction = DIF_INSTALLWIZARD;
  1603. iwd.hwndWizardDlg = hwndOwner;
  1604. /*
  1605. * Set the InstallWizardData as the ClassInstallParams
  1606. */
  1607. if ( SetupDiSetClassInstallParams( hdi,
  1608. NULL,
  1609. (PSP_CLASSINSTALL_HEADER)&iwd,
  1610. sizeof(iwd)) ) {
  1611. /*
  1612. * Call the class installer to invoke the installation
  1613. * wizard.
  1614. */
  1615. SetCursor(hcur);
  1616. hcur = NULL;
  1617. if ( SetupDiCallClassInstaller( DIF_INSTALLWIZARD,
  1618. hdi,
  1619. NULL) ) {
  1620. /*
  1621. * Success. The wizard was invoked and finished.
  1622. */
  1623. SetupDiCallClassInstaller( DIF_DESTROYWIZARDDATA,
  1624. hdi,
  1625. NULL );
  1626. bStatus = TRUE;
  1627. }
  1628. }
  1629. /*
  1630. * Clean up
  1631. */
  1632. SetupDiDestroyDeviceInfoList( hdi );
  1633. }
  1634. if (hcur)
  1635. SetCursor(hcur);
  1636. return(bStatus);
  1637. } // end InstallModem
  1638. /*******************************************************************************
  1639. *
  1640. * ConfigureModem - Hydrix helper function
  1641. *
  1642. * Configure the specified UNIMODEM modem.
  1643. *
  1644. * ENTRY:
  1645. * pModemName
  1646. * Name of UNIMODEM modem to configure.
  1647. * hwndOwner
  1648. * Window handle that owns the configuration dialog.
  1649. * EXIT:
  1650. * TRUE: configuration was sucessful; FALSE otherwise.
  1651. *
  1652. * The error code can be retrieved via GetLastError().
  1653. *
  1654. ******************************************************************************/
  1655. BOOL WINAPI
  1656. ConfigureModem( LPCTSTR pModemName,
  1657. HWND hwndOwner )
  1658. {
  1659. BOOL bStatus = FALSE;
  1660. COMMCONFIG ccDummy;
  1661. COMMCONFIG * pcc;
  1662. DWORD dwSize;
  1663. HCURSOR hcur = SetCursor(LoadCursor(NULL, IDC_WAIT));
  1664. ccDummy.dwProviderSubType = PST_MODEM;
  1665. dwSize = sizeof(COMMCONFIG);
  1666. GetDefaultCommConfig(pModemName, &ccDummy, &dwSize);
  1667. pcc = (COMMCONFIG *)LocalAlloc(LPTR, (UINT)dwSize);
  1668. if ( pcc ) {
  1669. pcc->dwProviderSubType = PST_MODEM;
  1670. if ( GetDefaultCommConfig(pModemName, pcc, &dwSize) ) {
  1671. COMMCONFIG *pccOld = (COMMCONFIG *)LocalAlloc(LPTR, (UINT)dwSize);
  1672. if ( pccOld ) {
  1673. memcpy(pccOld, pcc, dwSize);
  1674. }
  1675. SetCursor(hcur);
  1676. hcur = NULL;
  1677. bStatus = TRUE;
  1678. if ( CommConfigDialog(pModemName, hwndOwner, pcc) ) {
  1679. if ( !SetDefaultCommConfig(pModemName, pcc, dwSize) )
  1680. bStatus = FALSE;
  1681. }
  1682. LocalFree((HLOCAL)pcc);
  1683. }
  1684. }
  1685. else
  1686. {
  1687. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1688. }
  1689. if (hcur)
  1690. SetCursor(hcur);
  1691. return(bStatus);
  1692. } // end ConfigureModem
  1693. ///////////////////////////////////////////////////////////////////////////////
  1694. // Static Helper Functions
  1695. /*******************************************************************************
  1696. *
  1697. * CheckForComDevice - local helper function
  1698. *
  1699. * check if device name is a serial com device
  1700. *
  1701. * ENTRY:
  1702. * pName (input)
  1703. * device name
  1704. *
  1705. * EXIT:
  1706. * TRUE - serial device
  1707. * FALSE - not a serial device
  1708. *
  1709. ******************************************************************************/
  1710. static BOOL
  1711. CheckForComDevice( LPTSTR pName )
  1712. {
  1713. FILE_FS_DEVICE_INFORMATION DeviceInformation;
  1714. IO_STATUS_BLOCK IoStatus;
  1715. HANDLE Handle;
  1716. DEVICENAME Name;
  1717. NTSTATUS Status;
  1718. if ( (lstrlen(pName) == 2 && pName[1] == TEXT(':')) ||
  1719. !lstrcmpi(pName, TEXT("aux")) ||
  1720. !lstrnicmp(pName, TEXT("lpt"), 3) ||
  1721. !lstrnicmp(pName, TEXT("prn"), 3) ||
  1722. !lstrnicmp(pName, TEXT("display"), 7) ||
  1723. !lstrnicmp(pName, TEXT("$VDMLPT"), 7))
  1724. return(FALSE);
  1725. lstrcpy( Name, TEXT("\\\\.\\") );
  1726. lstrcat( Name, pName );
  1727. try
  1728. {
  1729. Handle = CreateFile( Name,
  1730. GENERIC_READ | GENERIC_WRITE,
  1731. 0, // exclusive access
  1732. NULL, // no security attr
  1733. OPEN_EXISTING, // must exist
  1734. 0,
  1735. NULL // no template
  1736. );
  1737. }
  1738. __except (1)
  1739. {
  1740. if ( Handle != INVALID_HANDLE_VALUE )
  1741. {
  1742. CloseHandle( Handle );
  1743. Handle = INVALID_HANDLE_VALUE;
  1744. }
  1745. }
  1746. if ( Handle == INVALID_HANDLE_VALUE )
  1747. return(FALSE);
  1748. Status = NtQueryVolumeInformationFile( (HANDLE) Handle,
  1749. &IoStatus,
  1750. &DeviceInformation,
  1751. sizeof(DeviceInformation),
  1752. FileFsDeviceInformation );
  1753. CloseHandle( Handle );
  1754. if ( (Status != STATUS_SUCCESS) ||
  1755. (DeviceInformation.DeviceType != FILE_DEVICE_SERIAL_PORT) )
  1756. return(FALSE);
  1757. return(TRUE);
  1758. } // end CheckForComDevice
  1759. /*******************************************************************************
  1760. *
  1761. * NetBiosLanaEnum - local helper function
  1762. *
  1763. * enumerate lana numbers
  1764. *
  1765. * ENTRY:
  1766. * pLanaEnum (input)
  1767. * pointer to receive LAN_ENUM structure
  1768. * EXIT:
  1769. * NO_ERROR - succesful
  1770. *
  1771. ******************************************************************************/
  1772. typedef struct _LANA_MAP {
  1773. BOOLEAN Enum;
  1774. UCHAR Lana;
  1775. } LANA_MAP, *PLANA_MAP;
  1776. static int
  1777. NetBiosLanaEnum( LANA_ENUM * pLanaEnum )
  1778. {
  1779. int ProviderCount;
  1780. void * pProviderNames = NULL;
  1781. PLANA_MAP pLanaMap = NULL;
  1782. HKEY netbiosKey = NULL;
  1783. ULONG providerListLength;
  1784. ULONG lanaMapLength;
  1785. ULONG type;
  1786. int i;
  1787. LPTSTR currentProviderName;
  1788. int rc;
  1789. //
  1790. // Read the registry for information on all Netbios providers,
  1791. // including Lana numbers, protocol numbers, and provider device
  1792. // names. First, open the Netbios key in the registry.
  1793. //
  1794. rc = RegOpenKeyEx( HKEY_LOCAL_MACHINE, REGISTRY_NETBLINKAGE, 0,
  1795. MAXIMUM_ALLOWED, &netbiosKey );
  1796. if ( rc != NO_ERROR ) {
  1797. goto error_exit;
  1798. }
  1799. //
  1800. // Determine the size of the provider names. We need this so
  1801. // that we can allocate enough memory to hold it.
  1802. //
  1803. providerListLength = 0;
  1804. rc = RegQueryValueEx(
  1805. netbiosKey,
  1806. TEXT("Bind"),
  1807. NULL,
  1808. &type,
  1809. NULL,
  1810. &providerListLength
  1811. );
  1812. if ( rc != ERROR_MORE_DATA && rc != NO_ERROR ) {
  1813. goto error_exit;
  1814. }
  1815. //
  1816. // Allocate enough memory to hold the mapping.
  1817. //
  1818. if ( (pProviderNames = LocalAlloc(LPTR,providerListLength)) == NULL ) {
  1819. rc = ERROR_NOT_ENOUGH_MEMORY;
  1820. goto error_exit;
  1821. }
  1822. //
  1823. // Get the list of transports from the registry.
  1824. //
  1825. rc = RegQueryValueEx(
  1826. netbiosKey,
  1827. TEXT("Bind"),
  1828. NULL,
  1829. &type,
  1830. (PVOID)pProviderNames,
  1831. &providerListLength
  1832. );
  1833. if ( rc != NO_ERROR ) {
  1834. goto error_exit;
  1835. }
  1836. //
  1837. // Determine the size of the Lana map. We need this so that we
  1838. // can allocate enough memory to hold it.
  1839. //
  1840. providerListLength = 0;
  1841. rc = RegQueryValueEx(
  1842. netbiosKey,
  1843. TEXT("LanaMap"),
  1844. NULL,
  1845. &type,
  1846. NULL,
  1847. &lanaMapLength
  1848. );
  1849. if ( rc != ERROR_MORE_DATA && rc != NO_ERROR ) {
  1850. goto error_exit;
  1851. }
  1852. //
  1853. // Allocate enough memory to hold the Lana map.
  1854. //
  1855. if ( (pLanaMap = LocalAlloc(LPTR,lanaMapLength)) == NULL ) {
  1856. rc = ERROR_NOT_ENOUGH_MEMORY;
  1857. goto error_exit;
  1858. }
  1859. //
  1860. // Get the list of transports from the registry.
  1861. //
  1862. rc = RegQueryValueEx(
  1863. netbiosKey,
  1864. TEXT("LanaMap"),
  1865. NULL,
  1866. &type,
  1867. (PVOID)pLanaMap,
  1868. &lanaMapLength
  1869. );
  1870. if ( rc != NO_ERROR ) {
  1871. goto error_exit;
  1872. }
  1873. //
  1874. // Determine the number of Netbios providers loaded on the system.
  1875. //
  1876. ProviderCount = (int) (lanaMapLength / sizeof(LANA_MAP));
  1877. //
  1878. // Fill in the lana array
  1879. //
  1880. pLanaEnum->length = 0;
  1881. for ( currentProviderName = pProviderNames, i = 0;
  1882. *currentProviderName != UNICODE_NULL && i < ProviderCount;
  1883. currentProviderName += lstrlen( currentProviderName ) + 1, i++ ) {
  1884. if ( pLanaMap[i].Enum &&
  1885. lstrstr( currentProviderName, TEXT("Nbf_") ) ) {
  1886. pLanaEnum->lana[ pLanaEnum->length++ ] = pLanaMap[i].Lana;
  1887. }
  1888. }
  1889. error_exit:
  1890. if ( netbiosKey != NULL )
  1891. RegCloseKey( netbiosKey );
  1892. if ( pProviderNames != NULL )
  1893. LocalFree( pProviderNames );
  1894. if ( pLanaMap != NULL )
  1895. LocalFree( pLanaMap );
  1896. return( rc );
  1897. }
  1898. //
  1899. // NOTE: Butchd 9-26-96
  1900. // all of this following TAPI-related code is from various
  1901. // \nt\private\net\ras\src\ui\setup\src\ files
  1902. //
  1903. /******************************************************************************
  1904. *
  1905. * EnumerateTapiPorts - local helper function
  1906. *
  1907. * Determine all TAPI configured modems.
  1908. *
  1909. * ENTRY
  1910. * pPdParams (output)
  1911. * Points to array of PDPARAMS structures to save enumerated TAPI
  1912. * modems into.
  1913. * Count (input)
  1914. * Specifies number of entries in the pPdParams array.
  1915. * ppEntries (input/output)
  1916. * Points to pointer to variable containing the existing number of
  1917. * PDPARAMS entries already stored at addresses prior to pPdParams.
  1918. * The referenced variable will be incremented by the number of
  1919. * TAPI modems found and stored in the pPdParams array.
  1920. * EXIT
  1921. * Returns ERROR_SUCCESS if successful, error code if not.
  1922. *
  1923. *****************************************************************************/
  1924. DWORD
  1925. EnumerateTapiPorts( PPDPARAMS pPdParams,
  1926. ULONG Count,
  1927. ULONG **ppEntries )
  1928. {
  1929. LINEINITIALIZEEXPARAMS params;
  1930. LINEDEVCAPS *linedevcaps ;
  1931. LINEEXTENSIONID extensionid ;
  1932. HLINEAPP TapiLine = (HLINEAPP)0;
  1933. DWORD NegotiatedApiVersion ;
  1934. DWORD NegotiatedExtVersion = 0;
  1935. WORD i;
  1936. DWORD lines = 0 ;
  1937. BYTE buffer[1000] ;
  1938. CHAR szregkey[512];
  1939. WCHAR wszDeviceName[DEVICENAME_LENGTH+1];
  1940. WCHAR wszModemName[DEVICENAME_LENGTH+1];
  1941. CHAR szModemName[DEVICENAME_LENGTH+1];
  1942. LONG lerr;
  1943. DWORD Status = ERROR_TAPI_CONFIGURATION;
  1944. DWORD dwApiVersion = HIGH_VERSION;
  1945. BOOL fSuccess = FALSE;
  1946. ULONG RASIsUsingPort = 0;
  1947. HKEY CurKey, CurKey2;
  1948. DWORD KeyCount=0, KeySize, CurSize, DataType;
  1949. TCHAR szSubKey[255], CurRASDev[1024], szMainKey[255], *pCurRASDev;
  1950. /*
  1951. * Un-comment / edit the following line if time needed to allow newly
  1952. * added modem to appear in TAPI's enumeration list.
  1953. */
  1954. // Sleep(4000L);
  1955. /*
  1956. * Initialize TAPI.
  1957. */
  1958. memset(&params, 0, sizeof(params));
  1959. params.dwTotalSize = sizeof(params);
  1960. params.dwOptions = LINEINITIALIZEEXOPTION_USEEVENT;
  1961. if ( lerr = lineInitializeExA( &TapiLine,
  1962. GetModuleHandle( UTILDLL_NAME ),
  1963. (LINECALLBACK)DummyTapiCallback,
  1964. NULL,
  1965. &lines,
  1966. &dwApiVersion,
  1967. &params ) )
  1968. goto error;
  1969. /*
  1970. * Get configured TAPI modems on all lines.
  1971. */
  1972. for ( i = 0; i < lines; i++ ) {
  1973. if ( lineNegotiateAPIVersion( TapiLine, i,
  1974. LOW_VERSION, HIGH_VERSION,
  1975. &NegotiatedApiVersion,
  1976. &extensionid ) ) {
  1977. continue ;
  1978. }
  1979. memset( buffer, 0, sizeof(buffer) );
  1980. linedevcaps = (LINEDEVCAPS *)buffer;
  1981. linedevcaps->dwTotalSize = sizeof(buffer);
  1982. /*
  1983. * Get this line's dev caps (ANSI).
  1984. */
  1985. if ( lineGetDevCapsA( TapiLine, i,
  1986. NegotiatedApiVersion,
  1987. NegotiatedExtVersion,
  1988. linedevcaps ) ) {
  1989. continue ;
  1990. }
  1991. /*
  1992. li * Only process modems.
  1993. */
  1994. if ( linedevcaps->dwMediaModes & LINEMEDIAMODE_DATAMODEM ) {
  1995. /*
  1996. * The linedevcaps stuff is in ASCII.
  1997. */
  1998. DWORD j;
  1999. char *temp;
  2000. /*
  2001. * Convert all nulls in the device class string to non nulls.
  2002. */
  2003. for ( j = 0, temp = (char *)((BYTE *)linedevcaps+linedevcaps->dwDeviceClassesOffset);
  2004. j < linedevcaps->dwDeviceClassesSize;
  2005. j++, temp++ ) {
  2006. if ( *temp == '\0' )
  2007. *temp = ' ';
  2008. }
  2009. /*
  2010. * Select only those devices that have comm/datamodem as a
  2011. * device class.
  2012. */
  2013. if ( strstr( (char*)((BYTE *)linedevcaps+linedevcaps->dwDeviceClassesOffset),
  2014. "comm/datamodem" ) == NULL ) {
  2015. continue;
  2016. }
  2017. /*
  2018. * Fetch modem name (line name).
  2019. */
  2020. strncpy( szModemName,
  2021. (char *)((BYTE *)linedevcaps+linedevcaps->dwLineNameOffset),
  2022. DEVICENAME_LENGTH );
  2023. szModemName[DEVICENAME_LENGTH] = '\0';
  2024. MultiByteToWideChar(CP_ACP, 0, szModemName, -1, wszModemName, DEVICENAME_LENGTH + 1);
  2025. /*
  2026. * The registry key name where the modem specific information is
  2027. * stored is at dwDevSpecificOffset + 2 * DWORDS
  2028. *
  2029. * The device specifc string is not unicode so copy that as
  2030. * an ansii string
  2031. */
  2032. strncpy( szregkey,
  2033. (char *)linedevcaps+linedevcaps->dwDevSpecificOffset+(2*sizeof(DWORD)),
  2034. linedevcaps->dwDevSpecificSize );
  2035. szregkey[linedevcaps->dwDevSpecificSize] = '\0';
  2036. if ( !GetAssociatedPortName( szregkey, wszDeviceName ) ) {
  2037. goto error;
  2038. }
  2039. /*
  2040. * If RAS is installed and is using the port configured with this
  2041. * modem, we will return the modem, but the Parity field will be
  2042. * set to 1, indicating that RAS is using the port. This is done
  2043. * so that WinCfg (or other caller) can filter out the raw port
  2044. * (device name) as well as the TAPI modem from the list.
  2045. */
  2046. RASIsUsingPort = 0;
  2047. //See if the RAS Key even exists
  2048. if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, TEXT("SOFTWARE\\Microsoft\\RAS\\TAPI DEVICES"), 0, KEY_ALL_ACCESS, &CurKey) == ERROR_SUCCESS) {
  2049. KeySize = sizeof(szSubKey) / sizeof( TCHAR );
  2050. KeyCount = 0;
  2051. while (RegEnumKeyEx( CurKey,
  2052. KeyCount++,
  2053. szSubKey,
  2054. &KeySize,
  2055. NULL,
  2056. NULL,
  2057. NULL,
  2058. NULL
  2059. ) != ERROR_NO_MORE_ITEMS) {
  2060. wcscpy(szMainKey,TEXT("SOFTWARE\\Microsoft\\RAS\\TAPI DEVICES"));
  2061. wcscat(szMainKey,TEXT("\\"));
  2062. wcscat(szMainKey,szSubKey);
  2063. if (RegOpenKeyEx( HKEY_LOCAL_MACHINE, szMainKey, 0, KEY_ALL_ACCESS, &CurKey2) == ERROR_SUCCESS) {
  2064. CurSize = sizeof(CurRASDev);
  2065. if (RegQueryValueEx(
  2066. CurKey2,
  2067. TEXT("Address"),
  2068. NULL,
  2069. &DataType,
  2070. (LPBYTE)CurRASDev,
  2071. &CurSize
  2072. ) == ERROR_SUCCESS) {
  2073. for ( pCurRASDev = CurRASDev;
  2074. *pCurRASDev && !RASIsUsingPort; ) {
  2075. if ( lstrcmpi(pCurRASDev, wszDeviceName) == 0 )
  2076. RASIsUsingPort = 1;
  2077. else
  2078. pCurRASDev += (wcslen(pCurRASDev) + 1);
  2079. }
  2080. }
  2081. RegCloseKey(CurKey2);
  2082. }
  2083. KeySize = sizeof(szSubKey) / sizeof( TCHAR );
  2084. }
  2085. RegCloseKey(CurKey);
  2086. }
  2087. /*
  2088. * Save DeviceName and ModemName to PDPARAMS
  2089. * structure and bump counts. Also, set the BaudRate
  2090. * element to the TAPI line index so that the caller can
  2091. * determine the most recently added line, and set the Parity
  2092. * field to 0 if RAS is not using the line, 1 if RAS is
  2093. * using the line (so caller can filter properly).
  2094. */
  2095. if ( Count > 0 ) {
  2096. pPdParams->SdClass = SdAsync;
  2097. lstrcpy( pPdParams->Async.DeviceName, wszDeviceName );
  2098. lstrcpy( pPdParams->Async.ModemName, wszModemName );
  2099. pPdParams->Async.BaudRate = (ULONG)i;
  2100. pPdParams->Async.Parity = RASIsUsingPort;
  2101. pPdParams++;
  2102. Count--;
  2103. (**ppEntries)++;
  2104. }
  2105. else {
  2106. Status = ERROR_INSUFFICIENT_BUFFER;
  2107. goto error;
  2108. }
  2109. }
  2110. }
  2111. Status = ERROR_SUCCESS;
  2112. error:
  2113. if ( TapiLine )
  2114. lineShutdown(TapiLine);
  2115. return( Status );
  2116. } // end EnumerateTapiPorts
  2117. /******************************************************************************
  2118. *
  2119. * DummyTapiCallback - local helper function
  2120. *
  2121. * A dummy callback routine to satisfy TAPI initialization.
  2122. *
  2123. * ENTRY
  2124. * (see TAPI lineInitialize documentation)
  2125. * EXIT
  2126. *
  2127. *****************************************************************************/
  2128. VOID CALLBACK
  2129. DummyTapiCallback (HANDLE context, DWORD msg, DWORD instance, DWORD param1, DWORD param2, DWORD param3)
  2130. {
  2131. } // end DummyTapiCallback
  2132. /******************************************************************************
  2133. *
  2134. * GetAssociatedPortName - local helper function
  2135. *
  2136. * Determine the 'attached to' (port) for the given modem via it's device
  2137. * specific registry key (szKeyName).
  2138. *
  2139. * ENTRY
  2140. * (see TAPI lineInitialize documentation)
  2141. * EXIT
  2142. *
  2143. *****************************************************************************/
  2144. #define VALNAME_ATTACHEDTO "AttachedTo"
  2145. BOOL
  2146. GetAssociatedPortName( char *szKeyName,
  2147. WCHAR * wszPortName )
  2148. {
  2149. HKEY hKeyModem;
  2150. DWORD dwType;
  2151. DWORD cbValueBuf;
  2152. char szPortName[DEVICENAME_LENGTH+1];
  2153. if ( RegOpenKeyExA( HKEY_LOCAL_MACHINE,
  2154. szKeyName,
  2155. 0,
  2156. KEY_READ,
  2157. &hKeyModem ) ) {
  2158. return( FALSE );
  2159. }
  2160. cbValueBuf = sizeof( szPortName );
  2161. if ( RegQueryValueExA( hKeyModem,
  2162. VALNAME_ATTACHEDTO,
  2163. NULL,
  2164. &dwType,
  2165. (LPBYTE)&szPortName,
  2166. &cbValueBuf ) ) {
  2167. RegCloseKey(hKeyModem);
  2168. return ( FALSE );
  2169. }
  2170. RegCloseKey( hKeyModem );
  2171. MultiByteToWideChar(CP_ACP, 0, szPortName, -1, wszPortName, DEVICENAME_LENGTH + 1);
  2172. return( TRUE );
  2173. } // end GetAssociatedPortName
  2174. /*
  2175. * Defines and typedefs
  2176. */
  2177. typedef struct _userlist {
  2178. struct _userlist *pNext;
  2179. WCHAR UserName[USERNAME_LENGTH+1];
  2180. } USERLIST, *PUSERLIST;
  2181. #define MAX_DOMAINANDNAME ((DOMAIN_LENGTH+1+USERNAME_LENGTH+1)*sizeof(WCHAR))
  2182. #define MAX_BUFFER (10*MAX_DOMAINANDNAME)
  2183. /*
  2184. * Local variables
  2185. */
  2186. WCHAR *s_pszCompareList = NULL;
  2187. WCHAR s_szServer[256];
  2188. /*
  2189. * Local functions.
  2190. */
  2191. WCHAR *_ctxCreateAnonymousUserCompareList();
  2192. /*******************************************************************************
  2193. *
  2194. * InitializeAnonymousUserCompareList - helper routine
  2195. *
  2196. * Creates a list of all local users who currently belong to the local
  2197. * Anonymous group on the specified server, and saves the server name.
  2198. *
  2199. * ENTRY:
  2200. * pszServer (input)
  2201. * Name of server to query users for.
  2202. *
  2203. ******************************************************************************/
  2204. void WINAPI
  2205. InitializeAnonymousUserCompareList( const WCHAR *pszServer )
  2206. {
  2207. if ( s_pszCompareList )
  2208. free( s_pszCompareList );
  2209. wcscpy(s_szServer, pszServer);
  2210. s_pszCompareList = _ctxCreateAnonymousUserCompareList();
  2211. }
  2212. /*******************************************************************************
  2213. *
  2214. * HaveAnonymousUsersChanged - helper routine
  2215. *
  2216. * Using the saved server name, fetch current list of local users that
  2217. * belong to the local Anonymous group and compare with saved list.
  2218. *
  2219. * ENTRY:
  2220. * EXIT:
  2221. * On exit, the original compare list is freed and server name cleared.
  2222. *
  2223. ******************************************************************************/
  2224. BOOL WINAPI
  2225. HaveAnonymousUsersChanged()
  2226. {
  2227. BOOL bChanged = FALSE;
  2228. WCHAR *pszNewCompareList, *pszOldName, *pszNewName;
  2229. if ( s_pszCompareList && *s_szServer ) {
  2230. if ( pszNewCompareList = _ctxCreateAnonymousUserCompareList() ) {
  2231. bChanged = TRUE;
  2232. for ( pszOldName = s_pszCompareList, pszNewName = pszNewCompareList;
  2233. (*pszOldName != L'\0') && (*pszNewName != L'\0'); ) {
  2234. if ( wcscmp(pszOldName, pszNewName) )
  2235. break;
  2236. pszOldName += (wcslen(pszOldName) + 1);
  2237. pszNewName += (wcslen(pszNewName) + 1);
  2238. }
  2239. if ( (*pszOldName == L'\0') && (*pszNewName == L'\0') )
  2240. bChanged = FALSE;
  2241. free(pszNewCompareList);
  2242. }
  2243. }
  2244. if ( s_pszCompareList )
  2245. free( s_pszCompareList );
  2246. s_pszCompareList = NULL;
  2247. memset(s_szServer, 0, sizeof(s_szServer));
  2248. return(bChanged);
  2249. }
  2250. /*******************************************************************************
  2251. *
  2252. * _ctxCreateAnonymousUserCompareList - local routine
  2253. *
  2254. * Routine to get local anonymous users and place in sorted string list.
  2255. *
  2256. * ENTRY:
  2257. * EXIT:
  2258. * pszCompareList - Returns pointer to buffer containing sorted string
  2259. * list of local anonymous users, double null terminated.
  2260. * NULL if error.
  2261. *
  2262. ******************************************************************************/
  2263. WCHAR *
  2264. _ctxCreateAnonymousUserCompareList()
  2265. {
  2266. DWORD EntriesRead, EntriesLeft, ResumeHandle = 0;
  2267. NET_API_STATUS rc;
  2268. WCHAR DomainAndUsername[256], *pszCompareList = NULL;
  2269. DWORD i, TotalCharacters = 0;
  2270. LPWSTR p;
  2271. PLOCALGROUP_MEMBERS_INFO_3 plgrmi3 = NULL;
  2272. PUSERLIST pUserListBase = NULL, pNewUser;
  2273. /*
  2274. * Loop till all local anonymous users have been retrieved.
  2275. */
  2276. do {
  2277. /*
  2278. * Get first batch
  2279. */
  2280. if ( (rc = NetLocalGroupGetMembers( s_szServer,
  2281. PSZ_ANONYMOUS,
  2282. 3,
  2283. (LPBYTE *)&plgrmi3,
  2284. MAX_BUFFER,
  2285. &EntriesRead,
  2286. &EntriesLeft,
  2287. (PDWORD_PTR)(&ResumeHandle) )) &&
  2288. (rc != ERROR_MORE_DATA ) ) {
  2289. break;
  2290. }
  2291. /*
  2292. * Process first batch
  2293. */
  2294. for ( i = 0; i < EntriesRead; i++ ) {
  2295. /*
  2296. * Get DOMAIN/USERNAME
  2297. */
  2298. wcscpy( DomainAndUsername, plgrmi3[i].lgrmi3_domainandname );
  2299. /*
  2300. * Check that DOMAIN is actually LOCAL MACHINE NAME
  2301. */
  2302. if ( (p = wcsrchr( DomainAndUsername, L'\\' )) != NULL ) {
  2303. /*
  2304. * Make sure that this user belongs to specified
  2305. * server.
  2306. */
  2307. *p = L'\0';
  2308. if ( _wcsicmp( DomainAndUsername, &s_szServer[2] ) ) {
  2309. continue;
  2310. }
  2311. }
  2312. /*
  2313. * Allocate list element and insert this username into list.
  2314. */
  2315. if ( (pNewUser = (PUSERLIST)malloc(sizeof(USERLIST))) == NULL ) {
  2316. rc = ERROR_OUTOFMEMORY;
  2317. break;
  2318. }
  2319. pNewUser->pNext = NULL;
  2320. wcscpy(pNewUser->UserName, p+1);
  2321. TotalCharacters += wcslen(p+1) + 1;
  2322. if ( pUserListBase == NULL ) {
  2323. /*
  2324. * First item in list.
  2325. */
  2326. pUserListBase = pNewUser;
  2327. }
  2328. else {
  2329. PUSERLIST pPrevUserList, pUserList;
  2330. pPrevUserList = pUserList = pUserListBase;
  2331. for ( ; ; ) {
  2332. if ( wcscmp(pNewUser->UserName, pUserList->UserName) < 0 ) {
  2333. if ( pPrevUserList == pUserListBase ) {
  2334. /*
  2335. * Insert at beginning of list.
  2336. */
  2337. pUserListBase = pNewUser;
  2338. }
  2339. else {
  2340. /*
  2341. * Insert into middle or beginning of list.
  2342. */
  2343. pPrevUserList->pNext = pNewUser;
  2344. }
  2345. /*
  2346. * Link to next.
  2347. */
  2348. pNewUser->pNext = pUserList;
  2349. break;
  2350. }
  2351. else if ( pUserList->pNext == NULL ) {
  2352. /*
  2353. * Add to end of list.
  2354. */
  2355. pUserList->pNext = pNewUser;
  2356. break;
  2357. }
  2358. pPrevUserList = pUserList;
  2359. pUserList = pUserList->pNext;
  2360. }
  2361. }
  2362. }
  2363. /*
  2364. * Free memory
  2365. */
  2366. if ( plgrmi3 != NULL ) {
  2367. NetApiBufferFree( plgrmi3 );
  2368. }
  2369. } while ( rc == ERROR_MORE_DATA );
  2370. /*
  2371. * Allocate buffer for multi-string compare list if no error so far
  2372. * and terminate in case of empty list.
  2373. */
  2374. if ( rc == ERROR_SUCCESS ) {
  2375. pszCompareList = (WCHAR *)malloc( (++TotalCharacters) * 2 );
  2376. if( pszCompareList != NULL )
  2377. {
  2378. *pszCompareList = L'\0';
  2379. }
  2380. }
  2381. /*
  2382. * Traverse and free username list, creating the multi-string compare
  2383. * list if buffer is available (no error so far).
  2384. */
  2385. if ( pUserListBase ) {
  2386. PUSERLIST pUserList = pUserListBase,
  2387. pNext = NULL;
  2388. WCHAR *pBuffer = pszCompareList;
  2389. do {
  2390. pNext = pUserList->pNext;
  2391. if ( pBuffer ) {
  2392. wcscpy(pBuffer, pUserList->UserName);
  2393. pBuffer += (wcslen(pBuffer) + 1);
  2394. *pBuffer = L'\0'; // auto double-null terminate
  2395. }
  2396. free(pUserList);
  2397. pUserList = pNext;
  2398. } while ( pUserList );
  2399. }
  2400. return(pszCompareList);
  2401. }
  2402. /*******************************************************************************
  2403. *
  2404. * GetUserFromSid - Hydrix helper function
  2405. *
  2406. * Fetch the user name associated with the specified SID.
  2407. *
  2408. * ENTRY:
  2409. * pSid (input)
  2410. * Points to SID to match to user name.
  2411. * pUserName (output)
  2412. * Points to buffer to place the user name into.
  2413. * cbUserName (input)
  2414. * Specifies the size in bytes of the user name buffer. The returned
  2415. * user name will be truncated to fit this buffer (including NUL
  2416. * terminator) if necessary.
  2417. *
  2418. * EXIT:
  2419. *
  2420. * GetUserFromSid() will always return a user name. If the specified
  2421. * SID fails to match to a user name, then the user name "(unknown)" will
  2422. * be returned.
  2423. *
  2424. ******************************************************************************/
  2425. void WINAPI
  2426. GetUserFromSid( PSID pSid,
  2427. LPTSTR pUserName,
  2428. DWORD cbUserName )
  2429. {
  2430. TCHAR DomainBuffer[DOMAIN_LENGTH], UserBuffer[USERNAME_LENGTH];
  2431. DWORD cbDomainBuffer=sizeof(DomainBuffer), cbUserBuffer=sizeof(UserBuffer),
  2432. Error;
  2433. LPTSTR pDomainBuffer = NULL, pUserBuffer = NULL;
  2434. SID_NAME_USE SidNameUse;
  2435. /*
  2436. * Fetch user name from SID: try user lookup with a reasonable Domain and
  2437. * Sid buffer size first, before resorting to alloc.
  2438. */
  2439. if ( !LookupAccountSid( NULL, pSid,
  2440. UserBuffer, &cbUserBuffer,
  2441. DomainBuffer, &cbDomainBuffer, &SidNameUse ) ) {
  2442. if ( ((Error = GetLastError()) == ERROR_INSUFFICIENT_BUFFER) ) {
  2443. if ( cbDomainBuffer > sizeof(DomainBuffer) ) {
  2444. if ( !(pDomainBuffer =
  2445. (LPTSTR)LocalAlloc(
  2446. LPTR, cbDomainBuffer * sizeof(TCHAR))) ) {
  2447. Error = ERROR_NOT_ENOUGH_MEMORY;
  2448. goto BadDomainAlloc;
  2449. }
  2450. }
  2451. if ( cbUserBuffer > sizeof(UserBuffer) ) {
  2452. if ( !(pUserBuffer =
  2453. (LPTSTR)LocalAlloc(
  2454. LPTR, cbUserBuffer * sizeof(TCHAR))) ) {
  2455. Error = ERROR_NOT_ENOUGH_MEMORY;
  2456. goto BadUserAlloc;
  2457. }
  2458. }
  2459. if ( !LookupAccountSid( NULL, pSid,
  2460. pUserBuffer ?
  2461. pUserBuffer : UserBuffer,
  2462. &cbUserBuffer,
  2463. pDomainBuffer ?
  2464. pDomainBuffer : DomainBuffer,
  2465. &cbDomainBuffer,
  2466. &SidNameUse ) ) {
  2467. Error = GetLastError();
  2468. goto BadLookup;
  2469. }
  2470. }
  2471. else {
  2472. goto BadLookup;
  2473. }
  2474. }
  2475. /*
  2476. * Copy the user name into the specified buffer, truncating if necessary,
  2477. * and make lower case.
  2478. */
  2479. lstrncpy( pUserName, pUserBuffer ? pUserBuffer : UserBuffer,
  2480. cbUserName - 1 );
  2481. pUserName[cbUserName-1] = TEXT('\0');
  2482. lstrlwr(pUserName);
  2483. /*
  2484. * Free our local allocs (if any) and return.
  2485. */
  2486. if ( pDomainBuffer )
  2487. LocalFree(pDomainBuffer);
  2488. if ( pUserBuffer )
  2489. LocalFree(pUserBuffer);
  2490. return;
  2491. /*--------------------------------------
  2492. * Error clean-up and return...
  2493. */
  2494. BadLookup:
  2495. BadUserAlloc:
  2496. BadDomainAlloc:
  2497. if ( pDomainBuffer )
  2498. LocalFree(pDomainBuffer);
  2499. if ( pUserBuffer )
  2500. LocalFree(pUserBuffer);
  2501. LoadString( GetModuleHandle( UTILDLL_NAME ),
  2502. IDS_UNKNOWN, pUserName, cbUserName - 1 );
  2503. pUserName[cbUserName-1] = TEXT('\0');
  2504. return;
  2505. } // end GetUserFromSid
  2506. /*******************************************************************************
  2507. *
  2508. * CachedGetUserFromSid - Hydrix helper function
  2509. *
  2510. * Provides entry point for a direct call to the UTILSUB.LIB
  2511. * GetUserNameFromSid, which performs its own caching of usernames.
  2512. *
  2513. * ENTRY:
  2514. * See UTILSUB.LIB GetUserNameFromSid (procutil.c)
  2515. * EXIT:
  2516. * See UTILSUB.LIB GetUserNameFromSid (procutil.c)
  2517. *
  2518. ******************************************************************************/
  2519. void WINAPI
  2520. CachedGetUserFromSid( PSID pSid,
  2521. PWCHAR pUserName,
  2522. PULONG pcbUserName )
  2523. {
  2524. GetUserNameFromSid( pSid, pUserName, pcbUserName );
  2525. } // end CachedGetUserFromSid
  2526. /*****************************************************************************
  2527. *
  2528. * TestUserForAdmin - Hydrix helper function
  2529. *
  2530. * Returns whether the current thread is running under admin
  2531. * security.
  2532. *
  2533. * ENTRY:
  2534. * dom (input)
  2535. * TRUE/FALSE - whether we want DOMAIN admin (as compared to local admin)
  2536. *
  2537. * EXIT:
  2538. * TRUE/FALSE - whether user is specified admin
  2539. *
  2540. ****************************************************************************/
  2541. BOOL WINAPI
  2542. TestUserForAdmin( BOOL dom )
  2543. {
  2544. BOOL IsMember, IsAnAdmin;
  2545. SID_IDENTIFIER_AUTHORITY SystemSidAuthority = SECURITY_NT_AUTHORITY;
  2546. PSID AdminSid;
  2547. if (RtlAllocateAndInitializeSid(
  2548. &SystemSidAuthority,
  2549. 2,
  2550. SECURITY_BUILTIN_DOMAIN_RID,
  2551. DOMAIN_ALIAS_RID_ADMINS,
  2552. 0, 0, 0, 0, 0, 0,
  2553. &AdminSid
  2554. ) != STATUS_SUCCESS)
  2555. {
  2556. IsAnAdmin = FALSE;
  2557. }
  2558. else
  2559. {
  2560. if (!CheckTokenMembership( NULL,
  2561. AdminSid,
  2562. &IsMember))
  2563. {
  2564. RtlFreeSid(AdminSid);
  2565. IsAnAdmin = FALSE;
  2566. }
  2567. else
  2568. {
  2569. RtlFreeSid(AdminSid);
  2570. IsAnAdmin = IsMember;
  2571. }
  2572. }
  2573. return IsAnAdmin;
  2574. // UNUSED dom;
  2575. } // end of TestUserForAdmin
  2576. /*****************************************************************************
  2577. *
  2578. * IsPartOfDomain - Hydrix helper function
  2579. *
  2580. * Returns whether the current server participates in a domain.
  2581. *
  2582. * ENTRY:
  2583. *
  2584. * EXIT:
  2585. * TRUE or FALSE
  2586. *
  2587. ****************************************************************************/
  2588. BOOL WINAPI
  2589. IsPartOfDomain(VOID)
  2590. {
  2591. NTSTATUS Status;
  2592. LSA_HANDLE PolicyHandle;
  2593. PPOLICY_ACCOUNT_DOMAIN_INFO DomainInfo;
  2594. OBJECT_ATTRIBUTES ObjAttributes;
  2595. BOOL IsDomainName = FALSE;
  2596. //
  2597. // Open a handle to the local security policy. Initialize the
  2598. // objects attributes structure first.
  2599. //
  2600. InitializeObjectAttributes( &ObjAttributes, NULL, 0, NULL, NULL );
  2601. Status = LsaOpenPolicy( NULL,
  2602. &ObjAttributes,
  2603. POLICY_VIEW_LOCAL_INFORMATION,
  2604. &PolicyHandle );
  2605. if ( !NT_SUCCESS(Status) )
  2606. goto done;
  2607. //
  2608. // Get the name of the primary domain from LSA
  2609. //
  2610. Status = LsaQueryInformationPolicy( PolicyHandle,
  2611. PolicyPrimaryDomainInformation,
  2612. (PVOID *)&DomainInfo );
  2613. (void) LsaClose( PolicyHandle );
  2614. if ( !NT_SUCCESS(Status) )
  2615. goto done;
  2616. if ( DomainInfo->DomainSid )
  2617. IsDomainName = TRUE;
  2618. (void) LsaFreeMemory( DomainInfo );
  2619. done:
  2620. return( IsDomainName );
  2621. } // end IsPartOfDomain
  2622. /*******************************************************************************
  2623. *
  2624. * StrSdClass - Hydrix helper function
  2625. *
  2626. * Returns pointer to string representing the specified SdClass.
  2627. *
  2628. * ENTRY:
  2629. * SdClass (input)
  2630. * The SDCLASS to associate with a string.
  2631. *
  2632. * EXIT:
  2633. * (LPCTSTR) Points to string representing the SDCLASS.
  2634. *
  2635. ******************************************************************************/
  2636. LPTSTR SdClassStrings[9] = { NULL};
  2637. LPCTSTR WINAPI
  2638. StrSdClass( SDCLASS SdClass )
  2639. {
  2640. TCHAR buffer[256];
  2641. WORD wID = IDS_UNKNOWN_PROTOCOL;
  2642. switch ( SdClass ) {
  2643. case SdConsole:
  2644. wID = IDS_CONSOLE;
  2645. break;
  2646. case SdNetwork:
  2647. wID = IDS_NETWORK;
  2648. break;
  2649. case SdAsync:
  2650. wID = IDS_ASYNC;
  2651. break;
  2652. case SdFrame:
  2653. wID = IDS_FRAME;
  2654. break;
  2655. case SdReliable:
  2656. wID = IDS_RELIABLE;
  2657. break;
  2658. case SdCompress:
  2659. wID = IDS_COMPRESSION;
  2660. break;
  2661. case SdEncrypt:
  2662. wID = IDS_ENCRYPTION;
  2663. break;
  2664. case SdTelnet:
  2665. wID = IDS_TELNET;
  2666. break;
  2667. }
  2668. // If we haven't loaded the string yet, do it now
  2669. if (!SdClassStrings[wID - IDS_CONSOLE]) {
  2670. LoadString(GetModuleHandle( UTILDLL_NAME ),
  2671. wID, buffer, lengthof(buffer) );
  2672. SdClassStrings[wID - IDS_CONSOLE] = LocalAlloc(LPTR, 2*(wcslen(buffer)+1));
  2673. if(NULL == SdClassStrings[wID - IDS_CONSOLE])
  2674. {
  2675. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2676. return NULL;
  2677. }
  2678. lstrcpy(SdClassStrings[wID - IDS_CONSOLE], buffer);
  2679. }
  2680. return(SdClassStrings[wID]);
  2681. } // end StrSdClass
  2682. /*******************************************************************************
  2683. *
  2684. * StrConnectState - Hydrix helper function
  2685. *
  2686. * Returns pointer to string representing the specified WinStation
  2687. * connection state.
  2688. *
  2689. * ENTRY:
  2690. * ConnectState (input)
  2691. * The WinStation connect state to associate with a string.
  2692. * bShortString (input)
  2693. * If TRUE, returns a short(er) version of the string (if there is
  2694. * one); FALSE returns the full spelling.
  2695. *
  2696. * EXIT:
  2697. * (LPCTSTR) Points to string representing the connect state.
  2698. *
  2699. * Note: The short version of the string may be the same as the long version.
  2700. * (i.e. "active") However, there are two string resources in case
  2701. * the long version of the string is not short in a language other
  2702. * than English.
  2703. ******************************************************************************/
  2704. LPTSTR ConnectStateStrings[21] = { NULL};
  2705. LPCTSTR WINAPI
  2706. StrConnectState( WINSTATIONSTATECLASS ConnectState,
  2707. BOOL bShortString )
  2708. {
  2709. TCHAR buffer[256];
  2710. WORD wID = IDS_UNKNOWN;
  2711. switch ( ConnectState ) {
  2712. case State_Active:
  2713. wID = bShortString ? IDS_SHORT_ACTIVE : IDS_ACTIVE;
  2714. break;
  2715. case State_Connected:
  2716. wID = bShortString ? IDS_SHORT_CONNECTED : IDS_CONNECTED;
  2717. break;
  2718. case State_ConnectQuery:
  2719. wID = bShortString ? IDS_SHORT_CONNECT_QUERY : IDS_CONNECT_QUERY;
  2720. break;
  2721. case State_Shadow:
  2722. wID = bShortString ? IDS_SHORT_SHADOW : IDS_SHADOW;
  2723. break;
  2724. case State_Disconnected:
  2725. wID = bShortString ? IDS_SHORT_DISCONNECTED : IDS_DISCONNECTED;
  2726. break;
  2727. case State_Idle:
  2728. wID = bShortString ? IDS_SHORT_IDLE : IDS_IDLE;
  2729. break;
  2730. case State_Reset:
  2731. wID = bShortString ? IDS_SHORT_RESET : IDS_RESET;
  2732. break;
  2733. case State_Down:
  2734. wID = bShortString ? IDS_SHORT_DOWN : IDS_DOWN;
  2735. break;
  2736. case State_Init:
  2737. wID = bShortString ? IDS_SHORT_INIT : IDS_INIT;
  2738. break;
  2739. case State_Listen:
  2740. wID = bShortString ? IDS_SHORT_LISTEN : IDS_LISTEN;
  2741. break;
  2742. }
  2743. // If we haven't loaded the string yet, do it now
  2744. if (!ConnectStateStrings[wID - IDS_ACTIVE]) {
  2745. LoadString(GetModuleHandle( UTILDLL_NAME ),
  2746. wID, buffer, lengthof(buffer) );
  2747. ConnectStateStrings[wID - IDS_ACTIVE] = LocalAlloc(LPTR, 2*(wcslen(buffer)+1));
  2748. if(NULL == ConnectStateStrings[wID - IDS_ACTIVE])
  2749. {
  2750. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2751. return NULL;
  2752. }
  2753. lstrcpy(ConnectStateStrings[wID - IDS_ACTIVE], buffer);
  2754. }
  2755. return(ConnectStateStrings[wID - IDS_ACTIVE]);
  2756. } // end StrConnectState
  2757. /*******************************************************************************
  2758. *
  2759. * StrProcessState - Hydrix helper function
  2760. *
  2761. * Returns pointer to string representing the specified process state.
  2762. *
  2763. * ENTRY:
  2764. * State (input)
  2765. * The process state to associate with a string.
  2766. *
  2767. * EXIT:
  2768. * (LPCTSTR) Points to string representing the process state.
  2769. *
  2770. ******************************************************************************/
  2771. LPTSTR ProcessStateStrings[8] = { NULL};
  2772. WORD StateTable[] = {
  2773. IDS_INITED,
  2774. IDS_READY,
  2775. IDS_RUN,
  2776. IDS_STANDBY,
  2777. IDS_TERMINATE,
  2778. IDS_WAIT,
  2779. IDS_TRANSIT,
  2780. IDS_STATE_DASHES,
  2781. IDS_STATE_DASHES,
  2782. IDS_STATE_DASHES,
  2783. IDS_STATE_DASHES,
  2784. IDS_STATE_DASHES
  2785. };
  2786. LPCTSTR WINAPI
  2787. StrProcessState( ULONG State )
  2788. {
  2789. TCHAR buffer[256];
  2790. WORD wID = StateTable[State];
  2791. // If we haven't loaded the string yet, do it now
  2792. if (!ProcessStateStrings[wID - IDS_INITED]) {
  2793. LoadString(GetModuleHandle( UTILDLL_NAME ),
  2794. wID, buffer, lengthof(buffer) );
  2795. ProcessStateStrings[wID - IDS_INITED] = LocalAlloc(LPTR, 2*(wcslen(buffer)+1));
  2796. if(NULL == ProcessStateStrings[wID - IDS_INITED])
  2797. {
  2798. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2799. return NULL;
  2800. }
  2801. lstrcpy(ProcessStateStrings[wID - IDS_INITED], buffer);
  2802. }
  2803. return(ProcessStateStrings[wID - IDS_INITED]);
  2804. } // end StrProcessState
  2805. /*******************************************************************************
  2806. *
  2807. * StrSystemWaitReason - Hydrix helper function
  2808. *
  2809. * Returns pointer to string representing the specified 'system'
  2810. * wait reason code.
  2811. *
  2812. * ENTRY:
  2813. * WaitReason (input)
  2814. * The system wait reason code to associate with a string.
  2815. *
  2816. * EXIT:
  2817. * (LPCTSTR) Points to string representing the system wait reason.
  2818. *
  2819. ******************************************************************************/
  2820. LPTSTR SystemWaitStrings[31] = { NULL};
  2821. WORD SystemWaitReason[] = {
  2822. IDS_EXECUTIVE, // Executive
  2823. IDS_FREE_PAGE, // FreePage
  2824. IDS_PAGE_IN, // PageIn
  2825. IDS_POOL_ALLOC, // PoolAlloc
  2826. IDS_DELAY_EXECUTION, // DelayExecution
  2827. IDS_SUSPENDED, // Suspended
  2828. IDS_USER_REQUEST, // UserRequest
  2829. IDS_EXECUTIVE, // Executive
  2830. IDS_FREE_PAGE, // FreePage
  2831. IDS_PAGE_IN, // PageIn
  2832. IDS_POOL_ALLOC, // PoolAllocation
  2833. IDS_DELAY_EXECUTION, // DelayExecution
  2834. IDS_SUSPENDED, // Suspended
  2835. IDS_USER_REQUEST, // UserRequest
  2836. IDS_EVENT_PAIR_HIGH, // EventPairHigh
  2837. IDS_EVENT_PAIR_LOW, // EventPairLow
  2838. IDS_LPC_RECEIVE, // LpcReceive
  2839. IDS_LPC_REPLY, // LpcReply
  2840. IDS_VIRTUAL_MEMORY, // VirtualMemory
  2841. IDS_PAGE_OUT, // PageOut
  2842. IDS_WAIT1,
  2843. IDS_WAIT2,
  2844. IDS_WAIT3,
  2845. IDS_WAIT4,
  2846. IDS_WAIT5,
  2847. IDS_WAIT6,
  2848. IDS_WAIT7,
  2849. IDS_WAIT8,
  2850. IDS_WAIT9,
  2851. IDS_WAIT10
  2852. };
  2853. LPCTSTR WINAPI
  2854. StrSystemWaitReason( ULONG WaitReason )
  2855. {
  2856. TCHAR buffer[256];
  2857. WORD wID = SystemWaitReason[WaitReason];
  2858. // If we haven't loaded the string yet, do it now
  2859. if (!SystemWaitStrings[wID - IDS_EXECUTIVE]) {
  2860. LoadString(GetModuleHandle( UTILDLL_NAME ),
  2861. wID, buffer, lengthof(buffer) );
  2862. SystemWaitStrings[wID - IDS_EXECUTIVE] = LocalAlloc(LPTR, 2*(wcslen(buffer)+1));
  2863. if(NULL == SystemWaitStrings[wID - IDS_EXECUTIVE])
  2864. {
  2865. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2866. return NULL;
  2867. }
  2868. wcscpy(SystemWaitStrings[wID - IDS_EXECUTIVE], buffer);
  2869. }
  2870. return(SystemWaitStrings[wID - IDS_EXECUTIVE]);
  2871. } // end StrSystemWaitReason
  2872. /*******************************************************************************
  2873. *
  2874. * StrAsyncConnectState - Hydrix helper function
  2875. *
  2876. * Returns pointer to string representing the specified async connect state.
  2877. *
  2878. * ENTRY:
  2879. * State (input)
  2880. * The async connect state to associate with a string.
  2881. *
  2882. * EXIT:
  2883. * (LPCTSTR) Points to string representing the async connect state.
  2884. *
  2885. ******************************************************************************/
  2886. LPTSTR AsyncConnectStateStrings[6] = { NULL };
  2887. LPCTSTR WINAPI
  2888. StrAsyncConnectState( ASYNCCONNECTCLASS State )
  2889. {
  2890. TCHAR buffer[256];
  2891. WORD wID = State - Connect_CTS;
  2892. // If we haven't loaded the string yet, do it now
  2893. if (!AsyncConnectStateStrings[wID]) {
  2894. LoadString(GetModuleHandle( UTILDLL_NAME ),
  2895. wID + IDS_ASYNC_CONNECT_CTS, buffer, lengthof(buffer) );
  2896. AsyncConnectStateStrings[wID] = LocalAlloc(LPTR, 2*(wcslen(buffer)+1));
  2897. if(NULL == AsyncConnectStateStrings[wID])
  2898. {
  2899. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2900. return NULL;
  2901. }
  2902. lstrcpy(AsyncConnectStateStrings[wID], buffer);
  2903. }
  2904. return(AsyncConnectStateStrings[wID]);
  2905. } // end StrProcessState
  2906. /*******************************************************************************
  2907. *
  2908. * GetUnknownString - Hydrix helper function
  2909. *
  2910. * Returns pointer to the string representing an unknown
  2911. * Connect State or DateTimeString (IDS_UNKNOWN)
  2912. * This is primarily so that WinAdmin can compare against it
  2913. *
  2914. * ENTRY:
  2915. * None
  2916. *
  2917. * EXIT:
  2918. * (LPCTSTR) Points to string representing the unknown string
  2919. *
  2920. ******************************************************************************/
  2921. LPTSTR UnknownString = NULL;
  2922. LPCTSTR WINAPI
  2923. GetUnknownString()
  2924. {
  2925. TCHAR buffer[256];
  2926. // if we haven't loaded the string yet, do it now
  2927. if (!UnknownString) {
  2928. LoadString(GetModuleHandle( UTILDLL_NAME ),
  2929. IDS_UNKNOWN, buffer, lengthof(buffer) );
  2930. UnknownString = LocalAlloc(LPTR, 2*(wcslen(buffer)+1));
  2931. if(NULL == UnknownString)
  2932. {
  2933. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2934. return NULL;
  2935. }
  2936. lstrcpy(UnknownString, buffer);
  2937. }
  2938. return(UnknownString);
  2939. } // end GetUnknownString
  2940. /*******************************************************************************
  2941. *
  2942. * CalculateElapsedTime - Hydrix helper function
  2943. *
  2944. * Determines the difference between a specified LARGE_INTEGER time value
  2945. * and the current system time, saves this 'elapsed time' into the
  2946. * specified ELAPSEDTIME structure.
  2947. *
  2948. * ENTRY:
  2949. * pTime (input)
  2950. * Points to LARGE_INTEGER of time for difference calculation.
  2951. * pElapsedTime (output)
  2952. * Points to ELAPSEDTIME structure to save elapsed time.
  2953. *
  2954. * EXIT:
  2955. *
  2956. ******************************************************************************/
  2957. void WINAPI
  2958. CalculateElapsedTime( LARGE_INTEGER *pTime,
  2959. ELAPSEDTIME *pElapsedTime )
  2960. {
  2961. LARGE_INTEGER InputTime;
  2962. LARGE_INTEGER CurrentTime;
  2963. LARGE_INTEGER DiffTime;
  2964. SYSTEMTIME ltime;
  2965. ULONG d_time;
  2966. /*
  2967. * Fetch the current time and zero out the specified ELAPSEDTIME structure.
  2968. */
  2969. GetLocalTime( &ltime );
  2970. memset( pElapsedTime, 0, sizeof(ELAPSEDTIME) );
  2971. if ( (pTime->HighPart == 0 && pTime->LowPart == 0 ) ||
  2972. !FileTimeToLocalFileTime( (FILETIME*)pTime, (FILETIME*)&InputTime ) ||
  2973. !SystemTimeToFileTime( &ltime, (FILETIME *)&CurrentTime ) )
  2974. return;
  2975. /*
  2976. * Get the number of seconds since specified time.
  2977. */
  2978. DiffTime = CalculateDiffTime( InputTime, CurrentTime );
  2979. d_time = DiffTime.LowPart;
  2980. /*
  2981. * Calculate the days, hours, minutes, seconds since specified time.
  2982. */
  2983. pElapsedTime->days = (USHORT)(d_time / 86400L); // days since
  2984. d_time = d_time % 86400L; // seconds => partial day
  2985. pElapsedTime->hours = (USHORT)(d_time / 3600L); // hours since
  2986. d_time = d_time % 3600L; // seconds => partial hour
  2987. pElapsedTime->minutes = (USHORT)(d_time / 60L); // minutes since
  2988. pElapsedTime->seconds = (USHORT)(d_time % 60L); // seconds remaining
  2989. } // end CalculateElapsedTime
  2990. /*******************************************************************************
  2991. *
  2992. * CompareElapsedTime - Hydrix helper function
  2993. *
  2994. * Determines the difference between two ELAPSEDTIME values.
  2995. *
  2996. * ENTRY:
  2997. * pElapsedTime1 (input)
  2998. * Points to first ELAPSEDTIME
  2999. * pElapsedTime2 (input)
  3000. * Points to ELAPSEDTIME structure to save elapsed time.
  3001. * bCompareSeconds (input)
  3002. * TRUE to include the seconds member in comparison; false otherwise.
  3003. *
  3004. * EXIT:
  3005. * < 1 if first time is less than second time
  3006. * 0 if times are the same
  3007. * > 1 if first time is greater than second time
  3008. *
  3009. ******************************************************************************/
  3010. int WINAPI
  3011. CompareElapsedTime( ELAPSEDTIME *pElapsedTime1,
  3012. ELAPSEDTIME *pElapsedTime2,
  3013. BOOL bCompareSeconds )
  3014. {
  3015. int result;
  3016. if ( !(result = pElapsedTime1->days - pElapsedTime2->days) &&
  3017. !(result = pElapsedTime1->hours - pElapsedTime2->hours) &&
  3018. !(result = pElapsedTime1->minutes - pElapsedTime2->minutes) &&
  3019. (!bCompareSeconds ||
  3020. !(result = pElapsedTime1->seconds - pElapsedTime2->seconds) ) )
  3021. return(0);
  3022. else
  3023. return(result);
  3024. } // end CompareElapsedTime
  3025. /*******************************************************************************
  3026. *
  3027. * ElapsedTimeString - Hydrix helper function
  3028. *
  3029. * Converts the specified ELAPSEDTIME into a string of the form
  3030. * "ddd+hh:mm:ss" or, optionally "ddd+hh:mm" (suppress seconds).
  3031. *
  3032. * ENTRY:
  3033. * pElapsedTime (input)
  3034. * Points to ELAPSEDTIME structure to convert to string.
  3035. * bIncludeSeconds (input)
  3036. * If TRUE, will include seconds in string; FALSE will exclude.
  3037. * pString (output)
  3038. * Points to location to store elapsed time string.
  3039. * EXIT:
  3040. *
  3041. ******************************************************************************/
  3042. void WINAPI
  3043. ElapsedTimeString( ELAPSEDTIME *pElapsedTime,
  3044. BOOL bIncludeSeconds,
  3045. LPTSTR pString )
  3046. {
  3047. if ( bIncludeSeconds ) {
  3048. if ( pElapsedTime->days > 0 )
  3049. wnsprintf( pString,
  3050. MAX_ELAPSED_TIME_LENGTH,
  3051. TEXT("%u+%02u:%02u:%02u"),
  3052. pElapsedTime->days,
  3053. pElapsedTime->hours,
  3054. pElapsedTime->minutes,
  3055. pElapsedTime->seconds );
  3056. else if ( pElapsedTime->hours > 0 )
  3057. wnsprintf( pString,
  3058. MAX_ELAPSED_TIME_LENGTH,
  3059. TEXT("%u:%02u:%02u"),
  3060. pElapsedTime->hours,
  3061. pElapsedTime->minutes,
  3062. pElapsedTime->seconds );
  3063. else if ( pElapsedTime->minutes > 0 )
  3064. wnsprintf( pString,
  3065. MAX_ELAPSED_TIME_LENGTH,
  3066. TEXT("%u:%02u"),
  3067. pElapsedTime->minutes,
  3068. pElapsedTime->seconds );
  3069. else if ( pElapsedTime->seconds > 0 )
  3070. wnsprintf( pString,
  3071. MAX_ELAPSED_TIME_LENGTH,
  3072. TEXT("%u"),
  3073. pElapsedTime->seconds );
  3074. else
  3075. wnsprintf( pString,
  3076. MAX_ELAPSED_TIME_LENGTH,
  3077. TEXT(".") );
  3078. }
  3079. else {
  3080. if ( pElapsedTime->days > 0 )
  3081. wnsprintf( pString,
  3082. MAX_ELAPSED_TIME_LENGTH,
  3083. TEXT("%u+%02u:%02u"),
  3084. pElapsedTime->days,
  3085. pElapsedTime->hours,
  3086. pElapsedTime->minutes );
  3087. else if ( pElapsedTime->hours > 0 )
  3088. wnsprintf( pString,
  3089. MAX_ELAPSED_TIME_LENGTH,
  3090. TEXT("%u:%02u"),
  3091. pElapsedTime->hours,
  3092. pElapsedTime->minutes );
  3093. else if ( pElapsedTime->minutes > 0 )
  3094. wnsprintf( pString,
  3095. MAX_ELAPSED_TIME_LENGTH,
  3096. TEXT("%u"),
  3097. pElapsedTime->minutes );
  3098. else
  3099. wnsprintf( pString,
  3100. MAX_ELAPSED_TIME_LENGTH,
  3101. TEXT(".") );
  3102. }
  3103. } // end ElapsedTimeString
  3104. /*******************************************************************************
  3105. *
  3106. * DateTimeString - Hydrix helper function
  3107. *
  3108. * Converts the specified LARGE_INTEGER time value into a date/time string
  3109. * of the form "mm/dd/yy hh:mm".
  3110. *
  3111. * ENTRY:
  3112. * pTime (input)
  3113. * Points to LARGE_INTEGER of time to convert to string.
  3114. * pString (output)
  3115. * Points string to store converted date/time into.
  3116. *
  3117. * EXIT:
  3118. *
  3119. ******************************************************************************/
  3120. void WINAPI
  3121. DateTimeString( LARGE_INTEGER *pTime,
  3122. LPTSTR pString )
  3123. {
  3124. FILETIME LocalTime;
  3125. SYSTEMTIME stime;
  3126. LPTSTR lpTimeStr;
  3127. int nLen;
  3128. if ( FileTimeToLocalFileTime( (FILETIME *)pTime, &LocalTime ) &&
  3129. FileTimeToSystemTime( &LocalTime, &stime ) ) {
  3130. //Get Date Format
  3131. nLen = GetDateFormat(
  3132. LOCALE_USER_DEFAULT,
  3133. DATE_SHORTDATE,
  3134. &stime,
  3135. NULL,
  3136. NULL,
  3137. 0);
  3138. lpTimeStr = (LPTSTR) GlobalAlloc(GPTR, (nLen + 1) * sizeof(TCHAR));
  3139. if(NULL == lpTimeStr)
  3140. {
  3141. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3142. wcscpy(pString, L"");
  3143. return;
  3144. }
  3145. nLen = GetDateFormat(
  3146. LOCALE_USER_DEFAULT,
  3147. DATE_SHORTDATE,
  3148. &stime,
  3149. NULL,
  3150. lpTimeStr,
  3151. nLen);
  3152. wcscpy(pString, lpTimeStr);
  3153. wcscat(pString, L" ");
  3154. GlobalFree(lpTimeStr);
  3155. //Get Time Format
  3156. nLen = GetTimeFormat(
  3157. LOCALE_USER_DEFAULT,
  3158. TIME_NOSECONDS,
  3159. &stime,
  3160. NULL,
  3161. NULL,
  3162. 0);
  3163. lpTimeStr = (LPTSTR) GlobalAlloc(GPTR, (nLen + 1) * sizeof(TCHAR));
  3164. if(NULL == lpTimeStr)
  3165. {
  3166. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3167. wcscpy(pString, L"");
  3168. return;
  3169. }
  3170. nLen = GetTimeFormat(
  3171. LOCALE_USER_DEFAULT,
  3172. TIME_NOSECONDS,
  3173. &stime,
  3174. NULL,
  3175. lpTimeStr,
  3176. nLen);
  3177. wcscat(pString, lpTimeStr);
  3178. GlobalFree(lpTimeStr);
  3179. }
  3180. else
  3181. LoadString( GetModuleHandle( UTILDLL_NAME ),
  3182. IDS_UNKNOWN, pString, lengthof(pString) );
  3183. } // end DateTimeString
  3184. /*******************************************************************************
  3185. *
  3186. * CurrentDateTimeString - Hydrix helper function
  3187. *
  3188. * Converts the current system time into a date/time string of the form
  3189. * "mm/dd/yy hh:mm".
  3190. *
  3191. * ENTRY:
  3192. * pString (output)
  3193. * Points string to store converted date/time into.
  3194. * EXIT:
  3195. *
  3196. ******************************************************************************/
  3197. void WINAPI
  3198. CurrentDateTimeString( LPTSTR pString )
  3199. {
  3200. SYSTEMTIME stime;
  3201. LPTSTR lpTimeStr;
  3202. int nLen;
  3203. GetLocalTime(&stime);
  3204. //Get DateFormat
  3205. nLen = GetDateFormat(
  3206. LOCALE_USER_DEFAULT,
  3207. DATE_SHORTDATE,
  3208. &stime,
  3209. NULL,
  3210. NULL,
  3211. 0);
  3212. lpTimeStr = (LPTSTR) GlobalAlloc(GPTR, (nLen + 1) * sizeof(TCHAR));
  3213. if(NULL == lpTimeStr)
  3214. {
  3215. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3216. wcscpy(pString, L"");
  3217. return;
  3218. }
  3219. nLen = GetDateFormat(
  3220. LOCALE_USER_DEFAULT,
  3221. DATE_SHORTDATE,
  3222. &stime,
  3223. NULL,
  3224. lpTimeStr,
  3225. nLen);
  3226. wcscpy(pString, lpTimeStr);
  3227. wcscat(pString, L" ");
  3228. GlobalFree(lpTimeStr);
  3229. //Get Time Format
  3230. nLen = GetTimeFormat(
  3231. LOCALE_USER_DEFAULT,
  3232. TIME_NOSECONDS,
  3233. &stime,
  3234. NULL,
  3235. NULL,
  3236. 0);
  3237. lpTimeStr = (LPTSTR) GlobalAlloc(GPTR, (nLen + 1) * sizeof(TCHAR));
  3238. if(NULL == lpTimeStr)
  3239. {
  3240. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3241. wcscpy(pString, L"");
  3242. return;
  3243. }
  3244. nLen = GetTimeFormat(
  3245. LOCALE_USER_DEFAULT,
  3246. TIME_NOSECONDS,
  3247. &stime,
  3248. NULL,
  3249. lpTimeStr,
  3250. nLen);
  3251. wcscat(pString, lpTimeStr);
  3252. GlobalFree(lpTimeStr);
  3253. } // end CurrentDateTimeString
  3254. /*******************************************************************************
  3255. *
  3256. * CalculateDiffTime - Hydrix helper function
  3257. *
  3258. * Calculate the time difference between two LARGE_INTEGER time values.
  3259. *
  3260. * ENTRY:
  3261. * FirstTime (input)
  3262. * The first (lower) time value.
  3263. * SecondTime (input)
  3264. * The second (higher) time value.
  3265. *
  3266. * EXIT:
  3267. * LARGE_INTEGER - the time difference
  3268. *
  3269. ******************************************************************************/
  3270. LARGE_INTEGER WINAPI
  3271. CalculateDiffTime( LARGE_INTEGER FirstTime, LARGE_INTEGER SecondTime )
  3272. {
  3273. LARGE_INTEGER DiffTime;
  3274. DiffTime = RtlLargeIntegerSubtract( SecondTime, FirstTime );
  3275. DiffTime = RtlExtendedLargeIntegerDivide( DiffTime, 10000000, NULL );
  3276. return(DiffTime);
  3277. } // end CalculateDiffTime
  3278. /*******************************************************************************
  3279. *
  3280. * EnumerateMultiUserServers - Hydrix helper function
  3281. *
  3282. * Enumerate the Hydrix servers on the network by Domain
  3283. *
  3284. * ENTRY:
  3285. * pDomain (input)
  3286. * Specifies the domain to enumerate; NULL for current domain.
  3287. *
  3288. * EXIT:
  3289. * (LPTSTR) Points to LocalAlloced buffer containing results of the
  3290. * enumeration, in multi-string format, if sucessful; NULL if
  3291. * error. The caller must perform a LocalFree of this buffer
  3292. * when done. If error (NULL), the error code is set for
  3293. * retrieval by GetLastError();
  3294. *
  3295. ******************************************************************************/
  3296. LPWSTR WINAPI
  3297. EnumerateMultiUserServers( LPWSTR pDomain )
  3298. {
  3299. PSERVER_INFO_101 pInfo = NULL;
  3300. DWORD dwByteCount, dwIndex, TotalEntries;
  3301. DWORD AvailCount = 0;
  3302. LPWSTR pTemp, pBuffer = NULL;
  3303. /*
  3304. * Enumerate all WF servers on the specified domain.
  3305. */
  3306. if ( NetServerEnum ( NULL,
  3307. 101,
  3308. (LPBYTE *)&pInfo,
  3309. (DWORD) -1,
  3310. &AvailCount,
  3311. &TotalEntries,
  3312. SV_TYPE_TERMINALSERVER,
  3313. pDomain,
  3314. NULL ) ||
  3315. !AvailCount )
  3316. goto done;
  3317. /*
  3318. * Traverse list and calculate the total byte count for list of
  3319. * servers that will be returned.
  3320. */
  3321. for ( dwByteCount = dwIndex = 0; dwIndex < AvailCount; dwIndex++ ) {
  3322. dwByteCount += (wcslen(pInfo[dwIndex].sv101_name) + 1) * 2;
  3323. }
  3324. dwByteCount += 2; // for ending null
  3325. /*
  3326. * Allocate memory.
  3327. */
  3328. if ( (pBuffer = LocalAlloc(LPTR, dwByteCount)) == NULL ) {
  3329. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  3330. goto done;
  3331. }
  3332. /*
  3333. * Traverse list again and copy servers to buffer.
  3334. */
  3335. for ( pTemp = pBuffer, dwIndex = 0; dwIndex < AvailCount; dwIndex++ ) {
  3336. wcscpy(pTemp, pInfo[dwIndex].sv101_name);
  3337. pTemp += (wcslen(pInfo[dwIndex].sv101_name) + 1);
  3338. }
  3339. *pTemp = L'\0'; // ending null
  3340. done:
  3341. if ( AvailCount && pInfo )
  3342. NetApiBufferFree( pInfo );
  3343. return(pBuffer);
  3344. } // end EnumerateMultiUserServers
  3345. /******************************************************************************
  3346. *
  3347. * _UserInGroup
  3348. * Internal function, determines if a user is a member of any of the
  3349. * groups passed in
  3350. *
  3351. * ENTRY:
  3352. * pwszUsername (IN) - Username to test group membership of
  3353. *
  3354. * pwszDomain (IN) - Domain of the user passed in
  3355. *
  3356. * pwszGroup (IN) - String array of all the allowed groups
  3357. *
  3358. * EXIT:
  3359. * Returns BOOLEAN value if user is a member of one of the groups
  3360. * HISTORY:
  3361. *
  3362. *
  3363. *****************************************************************************/
  3364. BOOL _UserInGroup( LPWSTR pwszUsername, LPWSTR pwszDomain, LPWSTR pwszGroup )
  3365. {
  3366. DWORD EntriesRead;
  3367. DWORD EntriesLeft;
  3368. NET_API_STATUS rc;
  3369. PGROUP_USERS_INFO_0 pszGroups;
  3370. ULONG i;
  3371. PWCHAR pwcUser;
  3372. WCHAR szBuf[MAX_PATH];
  3373. LPWKSTA_INFO_100 pWorkstationInfo = NULL;
  3374. WCHAR szDomainController[50];
  3375. #if DBG
  3376. DbgPrint( "MSGINA: UserInGroup: look(%S\\%S) group(%S)\n",
  3377. pwszDomain, pwszUsername, pwszGroup );
  3378. #endif
  3379. // This call will return the domain of the computer, not the domain of the user
  3380. if (( NetWkstaGetInfo( NULL,
  3381. 100,
  3382. (LPBYTE *)&pWorkstationInfo )) == NERR_Success) {
  3383. if( !CtxGetAnyDCName( NULL,
  3384. pWorkstationInfo->wki100_langroup,
  3385. szDomainController ) ){
  3386. NetApiBufferFree((LPVOID)pWorkstationInfo);
  3387. return( FALSE );
  3388. }
  3389. }
  3390. else {
  3391. return (FALSE);
  3392. }
  3393. if ( wcscmp( pWorkstationInfo->wki100_langroup, pwszDomain ) != 0 ) {
  3394. // user is from a different domain than the machine (trusted domain)
  3395. // need to change username to reflect the domain
  3396. wcscpy( szBuf, pwszDomain );
  3397. wcscat( szBuf, L"\\" );
  3398. wcscat( szBuf, pwszUsername );
  3399. pwcUser = szBuf;
  3400. }
  3401. else {
  3402. pwcUser = pwszUsername;
  3403. }
  3404. rc = NetUserGetLocalGroups( szDomainController,
  3405. pwcUser,
  3406. 0, // level
  3407. LG_INCLUDE_INDIRECT, // flags
  3408. (LPBYTE*)&pszGroups,
  3409. MAX_BUFFER,
  3410. &EntriesRead,
  3411. &EntriesLeft );
  3412. if( pWorkstationInfo != NULL )
  3413. NetApiBufferFree((LPVOID)pWorkstationInfo);
  3414. if ( rc != NERR_Success ) {
  3415. return( FALSE );
  3416. }
  3417. for ( i=0; i < EntriesRead; i++ ) {
  3418. if ( wcscmp( pszGroups[i].grui0_name, pwszGroup ) == 0 ) {
  3419. NetApiBufferFree( pszGroups );
  3420. pszGroups = NULL;
  3421. return( TRUE );
  3422. }
  3423. }
  3424. NetApiBufferFree( pszGroups );
  3425. pszGroups = NULL;
  3426. return(FALSE);
  3427. }
  3428. /******************************************************************************
  3429. *
  3430. * CtxGetAnyDCName
  3431. * Function to find a any DC of a specified domain. The call
  3432. * NetGetAnyDCName does not work as needed in all occasions.
  3433. * ie. Trusted domains and the current server being a DC.
  3434. *
  3435. * ENTRY:
  3436. * pServer (IN) - Server on which to run the call (RPC)
  3437. *
  3438. * pDomain (IN) - Domain you are inquring about, does not need to be
  3439. * current domain
  3440. *
  3441. * pBuffer (OUT) - Pointer to a string containg a DC name, buffer must
  3442. * be passed in.
  3443. * EXIT:
  3444. * BOOL Success
  3445. *
  3446. * HISTORY:
  3447. *
  3448. *
  3449. *****************************************************************************/
  3450. BOOL
  3451. CtxGetAnyDCName ( PWCHAR pServer, PWCHAR pDomain, PWCHAR pBuffer )
  3452. {
  3453. PWCHAR pDomainController = NULL;
  3454. PWCHAR pLocalDomainDC = NULL;
  3455. SERVER_INFO_101* ServerBuf = NULL;
  3456. BOOLEAN rc = TRUE;
  3457. BOOLEAN bFoundDC = FALSE;
  3458. // This call will return the domain of the computer, not the domain of the user
  3459. if (( NetGetAnyDCName(NULL,
  3460. pDomain,
  3461. (LPBYTE *)&pDomainController)) != NERR_Success) {
  3462. //
  3463. // NetGetAnyDCName doesn't work in two situations
  3464. // 1. If the domain is a trusted domain, it must be run from a DC. So we find our local
  3465. // DC and have it run getanydcname for us.
  3466. // 2. If we are a DC it will fail. So a second check is made to see
  3467. // if in fact we are a DC or not
  3468. //
  3469. // find a local DC in which to RPC to
  3470. if( NetGetAnyDCName( NULL,
  3471. NULL,
  3472. (LPBYTE *) &pLocalDomainDC ) == NERR_Success ) {
  3473. // Make the call as an RPC and pass it the Domain name
  3474. if( NetGetAnyDCName( pLocalDomainDC,
  3475. pDomain,
  3476. (LPBYTE *) &pDomainController ) == NERR_Success){
  3477. bFoundDC = TRUE;
  3478. }
  3479. }
  3480. // if it wasn't a trusted domain, maybe we are a domain controller
  3481. if( !bFoundDC ) {
  3482. if( NetServerGetInfo( NULL,
  3483. 101,
  3484. (LPBYTE*)&ServerBuf ) == NERR_Success ) {
  3485. if( ServerBuf->sv101_type & (SV_TYPE_DOMAIN_CTRL | SV_TYPE_DOMAIN_BAKCTRL) ) {
  3486. pDomainController = NULL;
  3487. }
  3488. else {
  3489. rc = FALSE;
  3490. goto done;
  3491. }
  3492. }
  3493. else {
  3494. rc = FALSE;
  3495. goto done;
  3496. }
  3497. }
  3498. }
  3499. if( pDomainController )
  3500. wcscpy( pBuffer, pDomainController);
  3501. else
  3502. *pBuffer = '\0';
  3503. done:
  3504. if( pLocalDomainDC )
  3505. NetApiBufferFree( pLocalDomainDC );
  3506. if( pDomainController )
  3507. NetApiBufferFree( pDomainController );
  3508. if( ServerBuf )
  3509. NetApiBufferFree( ServerBuf );
  3510. return( rc );
  3511. }