// @pymethod <o PyHANDLE>|win32wnet|WNetOpenEnum|Opens an Enumeration Handle for Enumerating Resources with <om win32wnet.WNetEnumResource> static PyObject * PyWNetOpenEnum(PyObject *self, PyObject *args) { // @comm See the Microsoft SDK for complete information on WNetOpenEnum. PyObject * ob_nr; NETRESOURCE * p_nr; DWORD dwScope, dwType, dwUsage; // not the same as the ones in NETRESOURCE DWORD Errno; HANDLE hEnum; // @pyparm int|scope||Specifies the scope of the enumeration. // @pyparm int|type||Specifies the resource types to enumerate. // @pyparm int|usage||Specifies the resource usage to be enumerated. // @pyparm <o PyNETRESOURCE>|resource||Python NETRESOURCE object. if (!PyArg_ParseTuple(args, "iiiO", &dwScope,&dwType,&dwUsage,&ob_nr)) return NULL; if (!PyWinObject_AsNETRESOURCE(ob_nr, &p_nr, TRUE)) return NULL; Py_BEGIN_ALLOW_THREADS Errno = WNetOpenEnum(dwScope, dwType, dwUsage, p_nr, &hEnum); Py_END_ALLOW_THREADS if (Errno != NO_ERROR) return(ReturnNetError("WNetOpenEnum", Errno)); return (PyNETENUMObject_FromHANDLE(hEnum)); // @rdesc PyHANDLE representing the Win32 HANDLE for the open resource. // This handle will be automatically be closed via <om win32wnet.WNetCloseEnum>, but // good style dictates it still be closed manually. };
/*---------------------------------------------------------------------------------------------- Given a target resource name, searches the parent node for a match, returning the results in the buffer as a NETRESOURCE. Usually the item we are searching for is in the lpRemoteName, but in some cases it is in the lpComment field of the NETRESOURCE. Parameters: pszTarget [in] The target for which we are searching. pnetrParent [in] A pointer to the parent node within which we are searching. If this if NULL, then we search at the root of the network. pszBuffer [out] A buffer into which to place the results, if found. The results are in the form of a NETRESOURCE structure. cBufferSize [in] The size of the pszBuffer. [out]The amount of pszBuffer actually occupied by the data (provided the target is found, of course.) Returns true if the target is found, false otherwise. ----------------------------------------------------------------------------------------------*/ bool NetworkTreeView::_FindChildNetResource(achar * pszTarget, NETRESOURCE * pnetrParent, achar * pszBuffer, DWORD * cBufferSize) { bool bResult = false; DWORD dwScope = (pnetrParent == NULL) ? RESOURCE_CONTEXT : RESOURCE_GLOBALNET; HANDLE hEnum; if (NO_ERROR == WNetOpenEnum(dwScope, RESOURCETYPE_ANY, 0, pnetrParent, &hEnum)) { DWORD dwCount = 1; int cBufferSizeOriginal = *cBufferSize; while (NO_ERROR == WNetEnumResource(hEnum, &dwCount, pszBuffer, cBufferSize)) { NETRESOURCE *netResource = (NETRESOURCE*)pszBuffer; if ((netResource->lpRemoteName && !_tcsicmp(pszTarget, netResource->lpRemoteName)) || (netResource->lpComment && !_tcsicmp(pszTarget, netResource->lpComment))) { bResult = true; break; } *cBufferSize = cBufferSizeOriginal; } WNetCloseEnum(hEnum); } return bResult; }
void DoUnMapShare(BOOL drivemap) //disconnect drivemap { TCHAR szMachine[MAX_PATH],szPath[MAX_PATH]; DWORD rc=28; HANDLE hEnum; LPNETRESOURCE lpnrLocal,lpnr=NULL; DWORD res; DWORD cbBuffer=16384; DWORD cEntries=-1; CHAR *pSubmount=""; memset(szMachine, '\0', sizeof(szMachine)); GetClientNetbiosName(szMachine); // Initialize the data structure if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR) return; sprintf(szPath,"\\\\%s\\",szMachine); _strlwr(szPath); lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer); do { /* Reset lpnrLocal and cEntries before each call */ memset(lpnrLocal,0,cbBuffer); cEntries = -1; if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR) { for (DWORD i=0;i<cEntries;i++) { if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)) { if ((lpnrLocal[i].lpLocalName) && (strlen(lpnrLocal[i].lpLocalName)>0)) { if (drivemap) { DisMountDOSDrive(*lpnrLocal[i].lpLocalName); DEBUG_EVENT1("AFS DriveUnMap","UnMap-Local=%x",res); } } else { DisMountDOSDriveFull(lpnrLocal[i].lpRemoteName); DEBUG_EVENT1("AFS DriveUnMap","UnMap-Remote=%x",res); } } } } } while (res == NO_ERROR); GlobalFree((HGLOBAL)lpnrLocal); WNetCloseEnum(hEnum); }
/*---------------------------------------------------------------------------------------------- Fill in the items in the tree control with respect to the Entire Network node of the network hierarchy. ----------------------------------------------------------------------------------------------*/ bool NetworkTreeView::_PopulateWorkgroups(HTREEITEM hTreeEntireNetwork, NETRESOURCE * pnetrParent) { // In Windows 2000 (unlike Windows 98) there is a "Micorosft Windows Network" node // in-between the "Entire Network" node and the various workgroups. Bother. Consistency // is too much to ask for. Anyway, we have to test for this, and if we find it we // call this method recursively so that we can just skip over the node and not have // it take up another mouse click in the UI. achar szMicrosoftWindowsNetwork[kMax]; LoadString(ModuleEntry::GetModuleHandle(), kridNetWindowsNetwork, szMicrosoftWindowsNetwork, sizeof(szMicrosoftWindowsNetwork)); // Enumerate the workgroups and insert into the tree HANDLE hEnum; if (NO_ERROR == WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, pnetrParent, &hEnum)) { DWORD dwCount = 1; char szBuffer[512]; char *psz = szBuffer; DWORD dwBufferSize = sizeof(szBuffer); HTREEITEM hNewNode; while (NO_ERROR == WNetEnumResource(hEnum, &dwCount, &szBuffer, &dwBufferSize)) { NETRESOURCE * pnetResource = (NETRESOURCE*)psz; if (NULL != pnetResource->lpRemoteName && * pnetResource->lpRemoteName) { if (0 == _tcscmp(pnetResource->lpRemoteName, szMicrosoftWindowsNetwork)) { _PopulateWorkgroups(hTreeEntireNetwork, pnetResource); } else { hNewNode = InsertItem(hTreeEntireNetwork, _CreateDisplayableNetworkName(pnetResource->lpRemoteName), kridImageWorkgroup); InsertItem(hNewNode, _T("placeholder"), -1); } } dwBufferSize = sizeof(szBuffer); } WNetCloseEnum(hEnum); } return true; }
HANDLE open_enum(char *server, WIN32_FIND_DATA *fdata) { NETRESOURCE netres; HANDLE henum; unsigned long ret; char *ptr; int slashes; nethandle_t *hnet; ptr = server; slashes = 0; while (*ptr) { if (*ptr == '/') *ptr = '\\'; if (*ptr == '\\') slashes++; ptr++; } if ((slashes == 3) && (*(ptr - 1) == '\\')) /* special case a server name like "//server/" */ *(ptr - 1) = '\0'; else if (slashes > 2) return INVALID_HANDLE_VALUE; memset(fdata, 0, sizeof(WIN32_FIND_DATA)); fdata->cFileName[0] = '.'; netres.dwScope = RESOURCE_GLOBALNET; netres.dwType = RESOURCETYPE_ANY; netres.lpRemoteName = server; netres.lpProvider = NULL; netres.dwUsage = 0; ret = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, &netres, &henum); if (ret != NO_ERROR) return INVALID_HANDLE_VALUE; hnet = (nethandle_t *)xmalloc(sizeof(nethandle_t)); hnet->netres = (unsigned char *)xcalloc(BLEN); hnet->henum = henum; return (HANDLE)hnet; }
std::bitset<32> AddSavedNetworkDisks(std::bitset<32>& Mask) { std::bitset<32> Result; HANDLE hEnum; if (!WNetOpenEnum(RESOURCE_REMEMBERED, RESOURCETYPE_DISK, 0, 0, &hEnum)) { DWORD bufsz = 16*1024; block_ptr<NETRESOURCE> netResource(bufsz); if (netResource) { for (;;) { DWORD size=1; bufsz = 16*1024; memset(netResource.get(),0,bufsz); DWORD res = WNetEnumResource(hEnum, &size, netResource.get(), &bufsz); if (res == NO_ERROR && size > 0 && netResource->lpLocalName ) { wchar_t letter = ToLower(netResource->lpLocalName[0]); if (letter >= L'a' && letter <= L'z' && !wcscmp(netResource->lpLocalName+1, L":")) { size_t index = letter - L'a'; if (!Mask[index]) { Mask[index] = 1; Result[index] = 1; } } } else { break; } } } WNetCloseEnum(hEnum); } return Result; }
static BOOL GetNetworkServersEnum(StringTimeNode** head, NETRESOURCE *nr) { HANDLE hEnum; DWORD cbBuffer = 16384; NETRESOURCE *nrLocal; DWORD dwResultEnum; DWORD cEntries = (DWORD)-1; DWORD i; DWORD dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER, nr, &hEnum); if (dwResult != NO_ERROR) return FALSE; nrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer); if (!nrLocal) return FALSE; for(;;) { ZeroMemory(nrLocal, cbBuffer); dwResultEnum = WNetEnumResource(hEnum, &cEntries, nrLocal, &cbBuffer); if (dwResultEnum != NO_ERROR) break; for (i = 0; i < cEntries; i++) { AddToListIfServer(head, &nrLocal[i]); if (RESOURCEUSAGE_CONTAINER == (nrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) { GetNetworkServersEnum(head, &nrLocal[i]); } } } GlobalFree((HGLOBAL) nrLocal); dwResult = WNetCloseEnum(hEnum); if (dwResult != NO_ERROR) return FALSE; return TRUE; }
void CIRC::GetNetworkInfo(NETRESOURCE *hNetRes, int *iDepth) { HANDLE hOpenEnum; DWORD dwRetVal; DWORD dwRequest=5000; DWORD dwBufSize; char szTemp[MSG_SIZE]=""; dwRetVal = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_ALL, hNetRes, &hOpenEnum); if(dwRetVal != NO_ERROR)return; dwBufSize = sizeof(NETRESOURCE)*5000; NETRESOURCE *hBuffer = new NETRESOURCE[5000]; dwRetVal = WNetEnumResource(hOpenEnum, &dwRequest, hBuffer, &dwBufSize); if(dwRetVal != NO_ERROR)return; for(int i=0; i<dwRequest; i++) { *iDepth+=1; if(*iDepth==1) { GetNetworkInfo(&hBuffer[i], iDepth); } else { sprintf(szTemp, "%s", hBuffer[i].lpRemoteName); SendMessage(szTemp); } } WNetCloseEnum(hOpenEnum); }
bool FolderTree::EnumNetwork(HTREEITEM hParent) { //What will be the return value from this function bool bGotChildren = false; //Check if the item already has a network resource and use it. FolderTreeItemInfo* pItem = (FolderTreeItemInfo*) GetItemData(hParent); NETRESOURCE* pNetResource = pItem->m_pNetResource; //Setup for the network enumeration HANDLE hEnum; DWORD dwResult = WNetOpenEnum(pNetResource ? RESOURCE_GLOBALNET : RESOURCE_CONTEXT, m_dwNetworkItemTypes, 0, pNetResource ? pNetResource : NULL, &hEnum); //Was the read sucessful if (dwResult != NO_ERROR) { //TRACE(_T("Cannot enumerate network drives, Error:%d\n"), dwResult); return FALSE; } //Do the network enumeration DWORD cbBuffer = 16384; bool bNeedMoreMemory = true; bool bSuccess = false; LPNETRESOURCE lpnrDrv = NULL; DWORD cEntries = 0; while (bNeedMoreMemory && !bSuccess) { //Allocate the memory and enumerate lpnrDrv = (LPNETRESOURCE) new BYTE[cbBuffer]; cEntries = 0xFFFFFFFF; dwResult = WNetEnumResource(hEnum, &cEntries, lpnrDrv, &cbBuffer); if (dwResult == ERROR_MORE_DATA) { //Free up the heap memory we have used delete [] lpnrDrv; cbBuffer *= 2; } else if (dwResult == NO_ERROR) bSuccess = true; else bNeedMoreMemory = false; } //Enumeration successful? if (bSuccess) { //Scan through the results for (DWORD i=0; i<cEntries; i++) { tstring sNameRemote; if(lpnrDrv[i].lpRemoteName != NULL) sNameRemote = lpnrDrv[i].lpRemoteName; else sNameRemote = lpnrDrv[i].lpComment; //Remove leading back slashes if (sNameRemote.size() > 0 && sNameRemote[0] == _T('\\')) sNameRemote = sNameRemote.substr(1); if (sNameRemote.size() > 0 && sNameRemote[0] == _T('\\')) sNameRemote = sNameRemote.substr(1); //Setup the item data for the new item pItem = new FolderTreeItemInfo; pItem->m_pNetResource = new NETRESOURCE; memzero(pItem->m_pNetResource, sizeof(NETRESOURCE)); *pItem->m_pNetResource = lpnrDrv[i]; if (lpnrDrv[i].lpLocalName) pItem->m_pNetResource->lpLocalName = _tcsdup(lpnrDrv[i].lpLocalName); if (lpnrDrv[i].lpRemoteName) pItem->m_pNetResource->lpRemoteName = _tcsdup(lpnrDrv[i].lpRemoteName); if (lpnrDrv[i].lpComment) pItem->m_pNetResource->lpComment = _tcsdup(lpnrDrv[i].lpComment); if (lpnrDrv[i].lpProvider) pItem->m_pNetResource->lpProvider = _tcsdup(lpnrDrv[i].lpProvider); if (lpnrDrv[i].lpRemoteName) pItem->m_sFQPath = lpnrDrv[i].lpRemoteName; else pItem->m_sFQPath = sNameRemote; pItem->m_sRelativePath = sNameRemote; pItem->m_bNetworkNode = true; //Display a share and the appropiate icon if (lpnrDrv[i].dwDisplayType == RESOURCEDISPLAYTYPE_SHARE) { //Display only the share name int nPos = pItem->m_sRelativePath.find(_T('\\')); if (nPos >= 0) pItem->m_sRelativePath = pItem->m_sRelativePath.substr(nPos+1); //Now add the item into the control InsertFileItem(hParent, pItem, m_bShowSharedUsingDifferentIcon, GetIconIndex(pItem->m_sFQPath), GetSelIconIndex(pItem->m_sFQPath), false); } else if (lpnrDrv[i].dwDisplayType == RESOURCEDISPLAYTYPE_SERVER) { //Now add the item into the control tstring sServer = _T("\\\\"); sServer += pItem->m_sRelativePath; InsertFileItem(hParent, pItem, false, GetIconIndex(sServer), GetSelIconIndex(sServer), false); } else { //Now add the item into the control //Just use the generic Network Neighborhood icons for everything else LPITEMIDLIST lpNNPidl; int nIcon = 0xFFFF; int nSelIcon = nIcon; if (SUCCEEDED(SHGetSpecialFolderLocation(NULL, CSIDL_NETWORK, &lpNNPidl))) { nIcon = GetIconIndex(lpNNPidl); nSelIcon = GetSelIconIndex(lpNNPidl); //Free up the pidl now that we are finished with it //ASSERT(m_pMalloc); m_pMalloc->Free(lpNNPidl); m_pMalloc->Release(); } InsertFileItem(hParent, pItem, false, nIcon, nSelIcon, false); } bGotChildren = true; } } /* else TRACE(_T("Cannot complete network drive enumeration, Error:%d\n"), dwResult); */ //Clean up the enumeration handle WNetCloseEnum(hEnum); //Free up the heap memory we have used delete [] lpnrDrv; //Return whether or not we added any items return bGotChildren; }
static int wnet_enumerate_netdrive(LPNETRESOURCE lpnr) { DWORD dwResult, dwResultEnum; HANDLE hEnum; DWORD cbBuffer = 16384; // 16K is a good size DWORD cEntries = -1; // enumerate all possible entries LPNETRESOURCE lpnrLocal; // pointer to enumerated structures DWORD i; dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, lpnr, // NULL first time the function is called &hEnum); // handle to the resource if (dwResult != NO_ERROR) { printf("WnetOpenEnum failed with error %ld\n", dwResult); return FALSE; } lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer); if (lpnrLocal == NULL) { printf("WnetOpenEnum failed with error %ld\n", dwResult); return FALSE; } do { ZeroMemory(lpnrLocal, cbBuffer); dwResultEnum = WNetEnumResource(hEnum, // resource handle &cEntries, // defined locally as -1 lpnrLocal, // LPNETRESOURCE &cbBuffer); if (dwResultEnum == NO_ERROR) { for (i = 0; i < cEntries; i++) { printf("NETRESOURCE[%ld] Usage: 0x%ld = ", i, lpnrLocal[i].dwUsage); if (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONNECTABLE) printf("connectable "); if (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER) printf("container "); printf("\n"); printf("NETRESOURCE[%ld] Localname: %s\n", i, lpnrLocal[i].lpLocalName); printf("NETRESOURCE[%ld] Remotename: %s\n", i, lpnrLocal[i].lpRemoteName); printf("NETRESOURCE[%ld] Comment: %s\n", i, lpnrLocal[i].lpComment); printf("NETRESOURCE[%ld] Provider: %s\n", i, lpnrLocal[i].lpProvider); printf("\n"); if (RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) if (!wnet_enumerate_netdrive(&lpnrLocal[i])) printf("EnumerateFunc returned FALSE\n"); } } else if (dwResultEnum != ERROR_NO_MORE_ITEMS) { printf("WNetEnumResource failed with error %ld\n", dwResultEnum); break; } } while (dwResultEnum != ERROR_NO_MORE_ITEMS); GlobalFree((HGLOBAL) lpnrLocal); dwResult = WNetCloseEnum(hEnum); if (dwResult != NO_ERROR) { printf("WNetCloseEnum failed with error %ld\n", dwResult); return FALSE; } return TRUE; }
static VOID RestoreAllConnections(PWLSESSION Session) { DWORD dRet; HANDLE hEnum; LPNETRESOURCE lpRes; DWORD dSize = 0x1000; DWORD dCount = -1; LPNETRESOURCE lpCur; BOOL UserProfile; UserProfile = (Session && Session->UserToken); if (!UserProfile) { return; } if (!ImpersonateLoggedOnUser(Session->UserToken)) { ERR("WL: ImpersonateLoggedOnUser() failed with error %lu\n", GetLastError()); return; } dRet = WNetOpenEnum(RESOURCE_REMEMBERED, RESOURCETYPE_DISK, 0, NULL, &hEnum); if (dRet != WN_SUCCESS) { ERR("Failed to open enumeration: %lu\n", dRet); goto quit; } lpRes = HeapAlloc(GetProcessHeap(), 0, dSize); if (!lpRes) { ERR("Failed to allocate memory\n"); WNetCloseEnum(hEnum); goto quit; } do { dSize = 0x1000; dCount = -1; memset(lpRes, 0, dSize); dRet = WNetEnumResource(hEnum, &dCount, lpRes, &dSize); if (dRet == WN_SUCCESS || dRet == WN_MORE_DATA) { lpCur = lpRes; for (; dCount; dCount--) { WNetAddConnection(lpCur->lpRemoteName, NULL, lpCur->lpLocalName); lpCur++; } } } while (dRet != WN_NO_MORE_ENTRIES); HeapFree(GetProcessHeap(), 0, lpRes); WNetCloseEnum(hEnum); quit: RevertToSelf(); }
BOOL CNetFolderEnum::EnumerateRec(LPNETRESOURCE lpNet) { BOOL bRet = TRUE; DWORD dRet; HANDLE hEnum; LPNETRESOURCE lpRes; DWORD dSize = 0x1000; DWORD dCount = -1; LPNETRESOURCE lpCur; dRet = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_DISK, 0, lpNet, &hEnum); if (dRet != WN_SUCCESS) { ERR("WNetOpenEnum() failed: %x\n", dRet); return FALSE; } lpRes = (LPNETRESOURCE)CoTaskMemAlloc(dSize); if (!lpRes) { ERR("CoTaskMemAlloc() failed\n"); WNetCloseEnum(hEnum); return FALSE; } do { dSize = 0x1000; dCount = -1; memset(lpRes, 0, dSize); dRet = WNetEnumResource(hEnum, &dCount, lpRes, &dSize); if (dRet == WN_SUCCESS || dRet == WN_MORE_DATA) { lpCur = lpRes; for (; dCount; dCount--) { TRACE("lpRemoteName: %S\n", lpCur->lpRemoteName); if ((lpCur->dwUsage & RESOURCEUSAGE_CONTAINER) == RESOURCEUSAGE_CONTAINER) { TRACE("Found provider: %S\n", lpCur->lpProvider); EnumerateRec(lpCur); } else { LPITEMIDLIST pidl; #ifdef HACKY_UNC_PATHS pidl = ILCreateFromNetworkPlaceW(lpCur->lpRemoteName); #endif if (pidl != NULL) bRet = AddToEnumList(pidl); else { ERR("ILCreateFromPathW() failed\n"); bRet = FALSE; break; } } lpCur++; } } } while (dRet != WN_NO_MORE_ENTRIES); CoTaskMemFree(lpRes); WNetCloseEnum(hEnum); TRACE("Done: %u\n", bRet); return bRet; }
static xpr_bool_t WINAPI EnumerateFunc(LPNETRESOURCE lpnr2, LPNETRESOURCE aNetResource, in_addr *pin_addr2) { DWORD sWNetResult, sWNetEnumResult; HANDLE sWNetEnum; DWORD sBufferSize = 16384; DWORD i, sEntries = -1; LPNETRESOURCE sLocalNetResource; xpr_tchar_t sFullName[XPR_MAX_URL_LENGTH + 1] = {0}; xpr_char_t sAnsiFullName[XPR_MAX_URL_LENGTH + 1] = {0}; xpr_char_t sHostName[XPR_MAX_URL_LENGTH + 1] = {0}; xpr_size_t sInputBytes; xpr_size_t sOutputBytes; sWNetResult = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, lpnr2, &sWNetEnum); if (sWNetResult != NO_ERROR) return XPR_FALSE; sLocalNetResource = (LPNETRESOURCE)GlobalAlloc(GPTR, sBufferSize); if (sLocalNetResource == XPR_NULL) return XPR_FALSE; xpr_bool_t sResult = XPR_FALSE; do { ZeroMemory(sLocalNetResource, sBufferSize); sWNetEnumResult = WNetEnumResource(sWNetEnum, &sEntries, sLocalNetResource, &sBufferSize); if (sWNetEnumResult == NO_ERROR) { for (i = 0; i < sEntries; ++i) { // sLocalNetResource[i] _tcscpy(sFullName, sLocalNetResource[i].lpRemoteName); if (_tcscmp(sFullName, XPR_STRING_LITERAL("\\\\")) == 0) { xpr_sint_t sLen = (xpr_sint_t)_tcslen(sFullName) - 2; memmove(sFullName, sFullName+2, sLen*sizeof(xpr_tchar_t)); sFullName[sLen] = '\0'; } sInputBytes = _tcslen(sFullName) * sizeof(xpr_tchar_t); sOutputBytes = XPR_MAX_URL_LENGTH * sizeof(xpr_tchar_t); XPR_TCS_TO_MBS(sFullName, &sInputBytes, sAnsiFullName, &sOutputBytes); sAnsiFullName[sOutputBytes / sizeof(xpr_char_t)] = 0; gethostname(sHostName, (xpr_sint_t)strlen(sHostName)); HOSTENT *sHostEnt = gethostbyname(sAnsiFullName); if (XPR_IS_NOT_NULL(sHostEnt)) { struct in_addr *sInAddr = (struct in_addr *)sHostEnt->h_addr_list[0]; if (sInAddr->S_un.S_un_b.s_b1 == pin_addr2->S_un.S_un_b.s_b1 && sInAddr->S_un.S_un_b.s_b2 == pin_addr2->S_un.S_un_b.s_b2 && sInAddr->S_un.S_un_b.s_b3 == pin_addr2->S_un.S_un_b.s_b3 && sInAddr->S_un.S_un_b.s_b4 == pin_addr2->S_un.S_un_b.s_b4) { _tcscpy(aNetResource->lpRemoteName, sLocalNetResource[i].lpRemoteName); sResult = XPR_TRUE; goto ENUM_END; } } if (RESOURCEUSAGE_CONTAINER == (sLocalNetResource[i].dwUsage & RESOURCEUSAGE_CONTAINER)) { if (EnumerateFunc(&sLocalNetResource[i], aNetResource, pin_addr2)) goto ENUM_END; } } } else if (sWNetEnumResult != ERROR_NO_MORE_ITEMS) { break; } } while (sWNetEnumResult != ERROR_NO_MORE_ITEMS); ENUM_END: GlobalFree((HGLOBAL)sLocalNetResource); sWNetResult = WNetCloseEnum(sWNetEnum); if (sWNetResult != NO_ERROR) return XPR_FALSE; return sResult; }
// // drivestr - is "<drive-letter>:" // static BOOL DriveIsMappedToAFS(char *drivestr, char *NetbiosName) { DWORD dwResult, dwResultEnum; HANDLE hEnum; DWORD cbBuffer = 16384; // 16K is a good size DWORD cEntries = -1; // enumerate all possible entries LPNETRESOURCE lpnrLocal; // pointer to enumerated structures DWORD i; BOOL bIsAFS = FALSE; char subststr[MAX_PATH]; char device[MAX_PATH]; // // Handle drive letter substitution created with "SUBST <drive> <path>". // If a substitution has occurred, use the target drive letter instead // of the source. // if ( DriveSubstitution(drivestr, subststr, MAX_PATH) ) { if (subststr[0] == '\\' && subststr[1] == '\\') { if (_strnicmp( &subststr[2], NetbiosName, strlen(NetbiosName)) == 0) return TRUE; else return FALSE; } drivestr = subststr; } // // Check for \Device\AFSRedirector // if (QueryDosDevice(drivestr, device, MAX_PATH) && _strnicmp( device, "\\Device\\AFSRedirector", strlen("\\Device\\AFSRedirector")) == 0) { return TRUE; } // // Call the WNetOpenEnum function to begin the enumeration. // dwResult = WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_DISK, RESOURCEUSAGE_ALL, NULL, // NULL first time the function is called &hEnum); // handle to the resource if (dwResult != NO_ERROR) return FALSE; // // Call the GlobalAlloc function to allocate resources. // lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer); if (lpnrLocal == NULL) return FALSE; do { // // Initialize the buffer. // ZeroMemory(lpnrLocal, cbBuffer); // // Call the WNetEnumResource function to continue // the enumeration. // cEntries = -1; dwResultEnum = WNetEnumResource(hEnum, // resource handle &cEntries, // defined locally as -1 lpnrLocal, // LPNETRESOURCE &cbBuffer); // buffer size // // If the call succeeds, loop through the structures. // if (dwResultEnum == NO_ERROR) { for (i = 0; i < cEntries; i++) { if (lpnrLocal[i].lpLocalName && toupper(lpnrLocal[i].lpLocalName[0]) == toupper(drivestr[0])) { // // Skip the two backslashes at the start of the UNC device name // if ( _strnicmp( &(lpnrLocal[i].lpRemoteName[2]), NetbiosName, strlen(NetbiosName)) == 0 ) { bIsAFS = TRUE; break; } } } } // Process errors. // else if (dwResultEnum != ERROR_NO_MORE_ITEMS) break; } while (dwResultEnum != ERROR_NO_MORE_ITEMS); // // Call the GlobalFree function to free the memory. // GlobalFree((HGLOBAL) lpnrLocal); // // Call WNetCloseEnum to end the enumeration. // dwResult = WNetCloseEnum(hEnum); return bIsAFS; }
BOOL COXNetBrowseTree::CreateChildren(HTREEITEM hParentItem, NETRESOURCE* pParentNetResources) // --- In : hParentItem : Node of which the children nodes have to be created // pParentNetResources : Net resource of this parent node // --- Out : // --- Returns : // --- Effect : Computes the netresources of the children and creates the child nodes { HANDLE hEnum = NULL; DWORD dwScope = pParentNetResources == NULL ? m_nResourceScope : pParentNetResources->dwScope; DWORD nResult = WNetOpenEnum( dwScope, // scope of enumeration RESOURCETYPE_ANY, // resource types to list 0, // resource usage to list pParentNetResources, // pointer to resource structure &hEnum); // pointer to enumeration handle buffer if (nResult != NO_ERROR) { TRACE2("COXNetBrowseTree::CreateChildren : WNetOpenEnum failed with error code %i == 0x%X\n", nResult, nResult); ReportNetError(nResult, pParentNetResources == NULL ? NULL : pParentNetResources->lpRemoteName); return FALSE; } DWORD nCurrentCount(0); DWORD nCurrentSkipCount(0); /* =============================================================================== */ // The problem with the WNetEnumResoiurce fuction is that allthough you use // 0xFFFFFFFF as requested resource count (this means everything) the function // does NOT return ERROR_MORE_DATA if the buffer is too small. It only returns // this value if the buffer supplied is too small even for one value, in this // case the space needed to hold the first resource found in the enumeration // Normally the size of this resource should be sizeof(NETRESOURCE) which is // 32 bytes but experience learned that this fluctuates between 32 bytes and // more than 1000 bytes. This is probably due to the fact that WNetEnumResource // also needs allocated memory for the strings inside the NETRESOURCE struct. // This leads to the conclusion that we cannot calculate with certainty the size // of the buffer we need for a certain number of resources. The most robust // solution to this problem is to request a absolute number of resources, make // an serious and realistic estimation of the maximum amount of memory needed // to hold ALL requested resources and then test to see whether you have retrieved // all requested resources. If this is TRUE then again enumerate the resources // to determine whether there aren't any left and so on until the returned // number of resources is smaller than the requested number. This last remark // explains why we need to be sure that the requested number of resources // allways fit in the amount of memory we allocated for the buffer. We could // alocated a very big buffer but we prefer the loop. // Also note that we don't use NETRESOURCE* pRes = new NETRESOURCE[Count] // because the array allocated will be an array of structs of size sizeof(NETRESOURCE) // and that's just not correct to hold one netresource. That's why we use // GlobalAlloc. // USERS WHO WANT TO TUNE THE PERFORMANCE OF THIS FUNCTION CAN PLAY WITH THE // NUMBER OF NETRESOURCES VIA THE nCOUNT VARIABLE AND WITH THE SIZE OF THE // ALLOCATED BUFFER VIA THE nBUFFERSIZE VARIABLE BUT KEEP THE REMARKS ABOVE // IN MIND. /* =============================================================================== */ // Start with a reasonable buffer size DWORD nCount = 5; DWORD nBufferSize = 5000; LPNETRESOURCE rgpNetResources = (LPNETRESOURCE)GlobalAlloc(GPTR, nBufferSize); while (TRUE) { DWORD nTempCount = nCount; DWORD nTempBufferSize = nBufferSize; memset(rgpNetResources, 0, nBufferSize); DWORD nResult2 = WNetEnumResource( hEnum, // handle to enumeration &nTempCount, // pointer to entries to list (LPVOID)rgpNetResources, // pointer to buffer for results &nTempBufferSize); // pointer to buffer size variable TRACE2("COXNetBrowseTree::WNetEnumResource : Number of Netresources (%i), in buffersize (0x%X)\n", nTempCount, nTempBufferSize); if ((nResult2 != NO_ERROR) && (nResult2 != ERROR_NO_MORE_ITEMS) && (nResult2 != ERROR_MORE_DATA)) { TRACE2("COXNetBrowseTree::CreateChildren : WNetEnumResource failed with error code %i == 0x%X\n", nResult2, nResult2); ReportNetError(nResult2, pParentNetResources == NULL ? NULL : pParentNetResources->lpRemoteName); // ... Cleanup the handle and memeory allocated VERIFY(WNetCloseEnum(hEnum) == NO_ERROR); GlobalFree((HGLOBAL)rgpNetResources); return FALSE; } if (nResult2 == ERROR_NO_MORE_ITEMS) nTempCount = 0; // Loop the requested number of NetResources and make tree item nodes { HTREEITEM hNewItem; NETRESOURCE* pSourceNetResource = NULL; NETRESOURCE* pCopyNetResource = NULL; DWORD nIndex; DWORD nSkipCount = 0; for (nIndex = 0; nIndex < nTempCount; nIndex++) { pSourceNetResource = &rgpNetResources[nIndex]; // Check special case for disks and printers if ((pSourceNetResource->dwType == RESOURCETYPE_DISK) && !m_bShowDisks) { // Skip this item nSkipCount++; continue; } if ((pSourceNetResource->dwType == RESOURCETYPE_PRINT) && !m_bShowPrinters) { // Skip this item nSkipCount++; continue; } // ... Create a new item hNewItem = InsertResourceItem(pSourceNetResource, hParentItem); if (hNewItem == NULL) { TRACE0("COXNetBrowseTree::InsertResourceItem returned NULL\n"); // Skip this item nSkipCount++; continue; } // Add a copy to the map // ... Should not yet be in map #ifdef _DEBUG NETRESOURCE* pCheckNetResource = NULL; ASSERT(!m_resourceMap.Lookup(hNewItem, pCheckNetResource)); #endif // _DEBUG pCopyNetResource = new NETRESOURCE; // ... Copy the struct itself memcpy(pCopyNetResource, pSourceNetResource, sizeof(NETRESOURCE)); // ... Make a copy of all the string members if (pSourceNetResource->lpLocalName != NULL) { size_t len = _tcslen(pSourceNetResource->lpLocalName) + 1; pCopyNetResource->lpLocalName = new TCHAR[len]; UTBStr::tcscpy(pCopyNetResource->lpLocalName, len, pSourceNetResource->lpLocalName); } else { pCopyNetResource->lpLocalName = new TCHAR[1]; *pCopyNetResource->lpLocalName = _T('\0'); } if (pSourceNetResource->lpRemoteName != NULL) { size_t len = _tcslen(pSourceNetResource->lpRemoteName) + 1; pCopyNetResource->lpRemoteName = new TCHAR[len]; UTBStr::tcscpy(pCopyNetResource->lpRemoteName, len, pSourceNetResource->lpRemoteName); } else { pCopyNetResource->lpRemoteName = new TCHAR[1]; *pCopyNetResource->lpRemoteName = _T('\0'); } if (pSourceNetResource->lpComment != NULL) { size_t len = _tcslen(pSourceNetResource->lpComment) + 1; pCopyNetResource->lpComment = new TCHAR[len]; UTBStr::tcscpy(pCopyNetResource->lpComment, len, pSourceNetResource->lpComment); } else { pCopyNetResource->lpComment = new TCHAR[1]; *pCopyNetResource->lpComment = _T('\0'); } if (pSourceNetResource->lpProvider != NULL) { size_t len = _tcslen(pSourceNetResource->lpProvider) + 1; pCopyNetResource->lpProvider = new TCHAR[len]; UTBStr::tcscpy(pCopyNetResource->lpProvider, len, pSourceNetResource->lpProvider); } else { pCopyNetResource->lpProvider = new TCHAR[1]; *pCopyNetResource->lpProvider = _T('\0'); } // ... Add to map m_resourceMap.SetAt(hNewItem, pCopyNetResource); } // we need to keep track of the real number of nodes because we // need it to set the correct treeitem number for the parent node nCurrentCount += nTempCount; nCurrentSkipCount += nSkipCount; if (hParentItem != NULL) { // Mark the parent node as expanded at least once VERIFY(SetItemState(hParentItem, TVIS_EXPANDEDONCE, TVIS_EXPANDEDONCE)); // Set the number of child items to the correct value TV_ITEM item; item.hItem = hParentItem; item.mask = TVIF_CHILDREN; ASSERT(nSkipCount <= nTempCount); item.cChildren = nCurrentCount - nCurrentSkipCount; VERIFY(SetItem(&item)); } } if (nResult2 == ERROR_MORE_DATA || nTempCount == nCount) // Possibly there is more data to retrieve { nTempCount = nCount; continue; } else // There was no error and there isn't anymore data to retrieve break; } // Cleanup the handle and allocated memory VERIFY(WNetCloseEnum(hEnum) == NO_ERROR); GlobalFree((HGLOBAL)rgpNetResources); return TRUE; }
//************************************************************************** BOOL OPCServerDlg::EnumerateNodes(LPNETRESOURCE lpnr) { CComboBox* pNodes = (CComboBox*)GetDlgItem(IDC_NODE); HANDLE hEnum = 0; DWORD dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, RESOURCEUSAGE_CONTAINER, lpnr, // NULL first time this function is called &hEnum); // handle to resource if (dwResult != NO_ERROR) { return FALSE; } DWORD cbBuffer = 16384; // 16K buffer LPNETRESOURCE lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer); do { DWORD cEntries = 0xFFFFFFFF; // enumerate all possible entries dwResult = WNetEnumResource(hEnum, &cEntries, lpnrLocal, &cbBuffer); if (dwResult == NO_ERROR) { for( DWORD i = 0; i < cEntries; i++) { // If this NETRESOURCE is a container, call the function // recursively. if(RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) { if(RESOURCEDISPLAYTYPE_SERVER == lpnrLocal[i].dwDisplayType ) { CString node(lpnrLocal[i].lpRemoteName); int index = node.Find( _T("\\") ); if( index > -1 ) node = node.Mid(index+2); if( pNodes ) pNodes->AddString(node); } else { EnumerateNodes(&lpnrLocal[i]); break; // ONLY enumerate the first "Container" } } } } else if (dwResult != ERROR_NO_MORE_ITEMS) { break; } } while(dwResult != ERROR_NO_MORE_ITEMS); GlobalFree((HGLOBAL) lpnrLocal); dwResult = WNetCloseEnum(hEnum); pNodes->SetWindowText(m_Node); if (dwResult != NO_ERROR) { return FALSE; } return TRUE; }
BOOL WINAPI EnumerateFunc(LPNETRESOURCE lpnr) { DWORD dwResult, dwResultEnum; HANDLE hEnum; DWORD cbBuffer = 16384; DWORD cEntries = -1; LPNETRESOURCE lpnrLocal; DWORD i; dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, lpnr, &hEnum); if (dwResult != NO_ERROR) { printf("WnetOpenEnum failed with error %d\n", dwResult); return FALSE; } lpnrLocal = (LPNETRESOURCE)GlobalAlloc(GPTR, cbBuffer); if (lpnrLocal == NULL) { printf("WnetOpenEnum failed with error %d\n", dwResult); return FALSE; } do { ZeroMemory(lpnrLocal, cbBuffer); dwResultEnum = WNetEnumResource(hEnum, &cEntries, lpnrLocal, &cbBuffer); if (dwResultEnum == NO_ERROR) { for (i = 0; i < cEntries; i++) { DisplayStruct(i, &lpnrLocal[i]); if (RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) if (!EnumerateFunc(&lpnrLocal[i])) printf("EnumerateFunc returned FALSE\n"); } } else if (dwResultEnum != ERROR_NO_MORE_ITEMS) { printf("WNetEnumResource failed with error %d\n", dwResultEnum); break; } } while (dwResultEnum != ERROR_NO_MORE_ITEMS); GlobalFree((HGLOBAL)lpnrLocal); dwResult = WNetCloseEnum(hEnum); if (dwResult != NO_ERROR) { printf("WNetCloseEnum failed with error %d\n", dwResult); return FALSE; } return TRUE; }
/*---------------------------------------------------------------------------------------------- Called in response to the user clicking on a Group within the tree view of the network. The idea is to wait until the user clicks before filling in the contents of the node. Otherwise we'd have to fill in the entire tree, and this can take a very, very long time. The function tests to see if we have filled in the contents yet; and if not, does the work. ----------------------------------------------------------------------------------------------*/ void NetworkTreeView::_ExpandGroupNode(TVITEM *item) { // Check to see if the item's image is a Group image. Otherwise, we are not at any node // that this function is concerned with. if (kridImageWorkgroup != item->iImage) return; CWaitCursor wait; // Now retrieve the first child. If there is no child, or if the child is not a // "placeholder", then we have nothing to do. If it is a placeholder, then get rid of it. HTREEITEM hChild = TreeView_GetChild(Hwnd(), item->hItem); if (NULL == hChild) return; achar szItemText[512]; _GetItemText(hChild, szItemText, sizeof(szItemText)); if (0 != _tcscmp(szItemText, _T("placeholder"))) return; TreeView_DeleteItem(Hwnd(), hChild); // Get the text of the Group that we'll be expanding. _GetItemText(item->hItem, szItemText, sizeof(szItemText)); // Get the parent netresource, by scanning down from the top of the hierarchy. achar szNetwork[512]; DWORD cNetwork = sizeof(szNetwork); if (false == _FindChildNetResource(_T("Entire Network"), NULL, szNetwork, &cNetwork)) return; achar szGroup[512]; DWORD cGroup = sizeof(szGroup); if (false == _FindChildNetResource(szItemText, (NETRESOURCE*)szNetwork, szGroup, &cGroup)) { // If we failed, we might be in Windows 2000; so try again, this time with the // "Microsoft Windows Network" as an intermediate node. achar szMicrosoftWindowsNetwork[512]; DWORD cMicrosoftWindowsNetwork = sizeof(szMicrosoftWindowsNetwork); if (!_FindChildNetResource(_T("Microsoft Windows Network"), (NETRESOURCE *)szNetwork, szMicrosoftWindowsNetwork, &cMicrosoftWindowsNetwork)) { return; } if (!_FindChildNetResource(szItemText, (NETRESOURCE*)szMicrosoftWindowsNetwork, szGroup, &cGroup)) { return; } } // Finally, enumerate the machines into the tree node HANDLE hEnum; if (NO_ERROR == WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, (NETRESOURCE*)szGroup, &hEnum)) { DWORD dwCount = 1; char szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); while (NO_ERROR == WNetEnumResource(hEnum, &dwCount, &szBuffer, &dwBufferSize)) { NETRESOURCE *netResource = (NETRESOURCE*)szBuffer; if (NULL != netResource->lpRemoteName && *netResource->lpRemoteName) { InsertItem(item->hItem, _CreateDisplayableNetworkName(netResource->lpRemoteName), kridImageComputer); } dwBufferSize = sizeof(szBuffer); } WNetCloseEnum(hEnum); } }
BOOL afsd_ServicePerformFlushVolumes() { CONST CHAR COLON = ':'; CONST CHAR SLASH = '\\'; CONST DWORD NETRESBUFSIZE = 16384; CHAR bufMessage[1024]; UINT i; DWORD dwServerSize; DWORD dwRet; DWORD dwCount; DWORD dwNetResBufSize; DWORD dwTotalVols = 0; DWORD dwVolBegin, dwVolEnd; DWORD dwFlushBegin, dwFlushEnd; HANDLE hEnum; LPNETRESOURCE lpNetResBuf, lpnr; char *pszShareName, *pc; afs_int32 afsRet = 0; if (cm_noIPAddr == 0) { // Nothing to do if we only have a loopback interface return TRUE; } // Determine the root share name (\\AFS\ALL or \\<machine>-AFS\ALL), // and the length of the server name prefix. pszShareName = smb_GetSharename(); if (pszShareName == NULL) { LogEvent(EVENTLOG_ERROR_TYPE, MSG_FLUSH_NO_SHARE_NAME, NULL); return FALSE; } pc = strrchr(pszShareName, SLASH); if ((pc == NULL) || ((dwServerSize = (DWORD)(pc - pszShareName)) < 3)) { LogEvent(EVENTLOG_ERROR_TYPE, MSG_FLUSH_BAD_SHARE_NAME, pszShareName, NULL); free(pszShareName); return FALSE; } // Allocate a buffer to hold network resources returned by // WNetEnumResource(). lpNetResBuf = malloc(NETRESBUFSIZE); if (lpNetResBuf == NULL) { // Out of memory, give up now. LogEvent(EVENTLOG_ERROR_TYPE, MSG_FLUSH_NO_MEMORY, NULL); free(pszShareName); return FALSE; } // Initialize the flush timer. Note that GetTickCount() returns // the number of milliseconds since the system started, in a DWORD, // so that the value wraps around every 49.7 days. We do not bother // to handle the case where the flush elapsed time is greater than // that. dwFlushBegin = GetTickCount(); dwRet = WNetOpenEnum(RESOURCE_CONNECTED, RESOURCETYPE_ANY, 0, NULL, &hEnum); if (dwRet != NO_ERROR) { LogEventMessage(EVENTLOG_ERROR_TYPE, MSG_FLUSH_OPEN_ENUM_ERROR, dwRet); free(pszShareName); return FALSE; } // Loop to enumerate network resources, and flush those associated // with AFS volumes. while (1) { dwCount = -1; memset(lpNetResBuf, 0, NETRESBUFSIZE); dwNetResBufSize = NETRESBUFSIZE; dwRet = WNetEnumResource(hEnum, &dwCount, lpNetResBuf, &dwNetResBufSize); if (dwRet != NO_ERROR) break; // Iterate over the returned network resources. for (i = 0, lpnr = lpNetResBuf; i < dwCount; i++, lpnr++) { // Ensure resource has a remote name, and is connected. if ((lpnr->lpRemoteName == NULL) || (lpnr->dwScope != RESOURCE_CONNECTED)) continue; if ((_strnicmp(lpnr->lpRemoteName, pszShareName, dwServerSize) == 0) && (lpnr->lpRemoteName[dwServerSize] == SLASH)) { // got one! // but we don't want to flush '\\[...]afs\all' if (cm_stricmp_utf8(lpnr->lpRemoteName, pszShareName) == 0) continue; ++dwTotalVols; dwVolBegin = GetTickCount(); afsRet = afsd_ServicePerformFlushVolumeCmd(lpnr->lpRemoteName); dwVolEnd = GetTickCount(); if (afsRet == 0) { LogTimingEvent(MSG_TIME_FLUSH_PER_VOLUME, lpnr->lpRemoteName, dwVolEnd - dwVolBegin); } else { LogEvent(EVENTLOG_WARNING_TYPE, MSG_FLUSH_FAILED, lpnr->lpRemoteName, NULL); } } } } WNetCloseEnum(hEnum); free(lpNetResBuf); free(pszShareName); if (dwRet != ERROR_NO_MORE_ITEMS) { LogEventMessage(EVENTLOG_ERROR_TYPE, MSG_FLUSH_ENUM_ERROR, dwRet); return FALSE; } dwFlushEnd = GetTickCount(); // display total volume count in Event Logger sprintf(bufMessage, "%d", dwTotalVols); LogTimingEvent(MSG_TIME_FLUSH_TOTAL, bufMessage, dwFlushEnd - dwFlushBegin); return TRUE; }
// enumerates all network resources (hostnames) std::vector<std::string> getNetworkResourceNames(LPNETRESOURCE lpnr) { std::vector<std::string> hostnames; DWORD dwResult, dwResultEnum; HANDLE hEnum; DWORD cbBuffer = 16384; DWORD cEntries = -1; LPNETRESOURCE lpnrLocal; dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, // all network resources RESOURCETYPE_ANY, // all resources 0, // enumerate all resources lpnr, // (first time the function is called) &hEnum); // handle to the resource lpnrLocal = (LPNETRESOURCE)GlobalAlloc(GPTR, cbBuffer); if (dwResult != NO_ERROR || lpnrLocal == NULL) return hostnames; do { // Initialize the buffer ZeroMemory(lpnrLocal, cbBuffer); // Enumerate the network resources dwResultEnum = WNetEnumResource(hEnum, &cEntries, lpnrLocal, &cbBuffer); if (dwResultEnum == NO_ERROR) { // loop through the structures for (int i = 0; i < cEntries; ++i) { std::string remoteName(wstringToString(lpnrLocal[i].lpRemoteName)); // check if the resource name starts with '\\' if (remoteName.compare(0, 2, "\\\\") == 0) { remoteName = remoteName.substr(2); // remove the first '\\' // find other slashes and remove them if (remoteName.find("\\") != std::string::npos) remoteName = remoteName.substr(0, remoteName.find("\\")); // add to the hostnames vector if (std::find(hostnames.begin(), hostnames.end(), remoteName) == hostnames.end()) hostnames.push_back(remoteName); } // if the resource found is a resource container, call the function recursively if (RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) { std::vector<std::string> hn = getNetworkResourceNames(&lpnrLocal[i]); // append the vector returned by the recursive call to our vector if (!hn.empty()) for (auto name : hn) if (std::find(hostnames.begin(), hostnames.end(), remoteName) == hostnames.end()) hostnames.push_back(name); } } } else if (dwResultEnum != ERROR_NO_MORE_ITEMS) break; } while (dwResultEnum != ERROR_NO_MORE_ITEMS); // free the memory GlobalFree((HGLOBAL)lpnrLocal); // end enumeration dwResult = WNetCloseEnum(hEnum); if (dwResult != NO_ERROR) return std::vector<std::string>(); // empty vector return hostnames; }
BOOL DoMapShareChange(BOOL removeUnknown) { DRIVEMAPLIST List; TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH]; DWORD rc=28; HANDLE hEnum; LPNETRESOURCE lpnrLocal,lpnr=NULL; DWORD res; DWORD cEntries=-1; DWORD cbBuffer=16384; memset(szMachine, '\0', sizeof(szMachine)); GetClientNetbiosName(szMachine); // Initialize the data structure if (!IsServiceActive()) return TRUE; memset (&List, 0x00, sizeof(DRIVEMAPLIST)); for (size_t ii = 0; ii < 26; ++ii) List.aDriveMap[ii].chDrive = chDRIVE_A + ii; QueryDriveMapList_ReadSubmounts (&List); if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR) return FALSE; lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer); sprintf(szPath,"\\\\%s\\",szMachine); _strlwr(szPath); do { /* Reset lpnrLocal and cEntries before each call */ memset(lpnrLocal,0,cbBuffer); cEntries = -1; if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR) { for (DWORD i=0;i<cEntries;i++) { if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)==NULL) continue; //only look at real afs mappings CHAR * pSubmount=strrchr(lpnrLocal[i].lpRemoteName,'\\')+1; if (lstrcmpi(pSubmount,"all")==0) continue; // do not remove 'all' for (DWORD j=0;j<List.cSubmounts;j++) { if ((List.aSubmounts[j].szSubmount[0]) && (lstrcmpi(List.aSubmounts[j].szSubmount,pSubmount)==0) ) { List.aSubmounts[j].fInUse=TRUE; goto nextname; } } // wasn't on list so lets remove DisMountDOSDrive(pSubmount); nextname:; } } } while (res == NO_ERROR); GlobalFree((HGLOBAL)lpnrLocal); WNetCloseEnum(hEnum); sprintf(szPath,"\\\\%s\\all",szMachine); // Lets connect all submounts that weren't connectd DWORD cbUser=MAXRANDOMNAMELEN-1; CHAR szUser[MAXRANDOMNAMELEN]; CHAR * pUser = NULL; if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)==NO_ERROR) { if ((pUser=strchr(szUser,'\\'))!=NULL) pUser++; } for (DWORD j=0;j<List.cSubmounts;j++) { if (List.aSubmounts[j].fInUse) continue; DWORD res=MountDOSDrive(0,List.aSubmounts[j].szSubmount,FALSE,pUser); } return TRUE; }
/*---------------------------------------------------------------------------------------------- Notifications ----------------------------------------------------------------------------------------------*/ bool NetworkTreeView::OnNotifyThis(int id, NMHDR * pnmh, long & lnRet) { AssertPtr(pnmh); Assert(pnmh->hwndFrom == m_hwnd); switch (pnmh->code) { // The user has clicked to expand a tree item. If the item is a Group in the network, // we need to populate that node of the tree before showing it to the user. case TVN_ITEMEXPANDING: { NMTREEVIEW * pntv = reinterpret_cast<NMTREEVIEW *>(pnmh); if (TVE_EXPAND == pntv->action) { if (!m_fNetworkPopulated && m_hTreeNeighborhood && m_hTreeEntireNetwork) { m_fNetworkPopulated = true; // Enumerate that Network Neighborhood node and insert into the tree HANDLE hEnum; if (WNetOpenEnum(RESOURCE_CONTEXT, RESOURCETYPE_ANY, 0, NULL, &hEnum) == NO_ERROR) { DWORD dwCount = 1; char szBuffer[kMax]; char *psz = szBuffer; DWORD dwBufferSize = sizeof(szBuffer); achar szEntireNetwork[kMax]; LoadString(ModuleEntry::GetModuleHandle(), kridNetEntireNetwork, szEntireNetwork, sizeof(szEntireNetwork)); while (WNetEnumResource(hEnum, &dwCount, &szBuffer, &dwBufferSize) == NO_ERROR) { NETRESOURCE * pnetResource = (NETRESOURCE*)psz; // Recognize the Entire Network node and populate it. if (pnetResource->lpComment && !_tcscmp(szEntireNetwork, pnetResource->lpComment)) { _PopulateWorkgroups(m_hTreeEntireNetwork, pnetResource); } // Otherwise populate the machines in this local context else if (pnetResource->lpRemoteName && *pnetResource->lpRemoteName) { InsertItem(m_hTreeNeighborhood, _CreateDisplayableNetworkName(pnetResource->lpRemoteName), kridImageComputer); } dwBufferSize = sizeof(szBuffer); } WNetCloseEnum(hEnum); } m_hTreeNeighborhood = NULL; m_hTreeEntireNetwork = NULL; } _ExpandGroupNode(&pntv->itemNew); } } break; default: return false; } return false; }
BOOL WINAPI EnumerateFunc(LPNETRESOURCE lpnr) { DWORD dwResult, dwResultEnum; HANDLE hEnum; DWORD cbBuffer = 16384; // 16K is a good size DWORD cEntries = -1; // enumerate all possible entries LPNETRESOURCE lpnrLocal; // pointer to enumerated structures DWORD i; // // Call the WNetOpenEnum function to begin the enumeration. // dwResult = WNetOpenEnum(RESOURCE_CONNECTED /*RESOURCE_GLOBALNET*/, // all network resources RESOURCETYPE_ANY, // all resources 0, // enumerate all resources lpnr, // NULL first time the function is called &hEnum); // handle to the resource if (dwResult != NO_ERROR) { // // Process errors with an application-defined error handler. // //NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetOpenEnum"); return FALSE; } // // Call the GlobalAlloc function to allocate resources. // lpnrLocal = (LPNETRESOURCE)GlobalAlloc(GPTR, cbBuffer); do { // // Initialize the buffer. // ZeroMemory(lpnrLocal, cbBuffer); // // Call the WNetEnumResource function to continue // the enumeration. // dwResultEnum = WNetEnumResource(hEnum, // resource handle &cEntries, // defined locally as -1 lpnrLocal, // LPNETRESOURCE &cbBuffer); // buffer size // // If the call succeeds, loop through the structures. // if (dwResultEnum == NO_ERROR) { for (i = 0; i < cEntries; i++) { // Call an application-defined function to // display the contents of the NETRESOURCE structures. // DisplayStruct(&lpnrLocal[i]); // If the NETRESOURCE structure represents a container resource, // call the EnumerateFunc function recursively. if (RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) if (!EnumerateFunc(&lpnrLocal[i])) return FALSE; //TextOut(hdc, 10, 10, "EnumerateFunc returned FALSE.", 29); } } // Process errors. // else if (dwResultEnum != ERROR_NO_MORE_ITEMS) { //NetErrorHandler(hwnd, dwResultEnum, (LPSTR)"WNetEnumResource"); break; } } // // End do. // while (dwResultEnum != ERROR_NO_MORE_ITEMS); // // Call the GlobalFree function to free the memory. // GlobalFree((HGLOBAL)lpnrLocal); // // Call WNetCloseEnum to end the enumeration. // dwResult = WNetCloseEnum(hEnum); if (dwResult != NO_ERROR) { // // Process errors. // //NetErrorHandler(hwnd, dwResult, (LPSTR)"WNetCloseEnum"); return FALSE; } return TRUE; }
/* Returns the IP of all computers networks connected to this computer. */ int CLANDiscovery::NetworkComputersIP( char* &sz ) { #ifdef _DEBUG printf("\nCLANDiscovery::NetworkComputers sz=%p\n",sz); #endif // delete[] sz; sz=NULL; // int computers=0; // NETRESOURCE* NetResource=NULL; HANDLE hEnum; WNetOpenEnum(RESOURCE_CONTEXT,RESOURCETYPE_ANY,NULL,NULL,&hEnum); if(hEnum==NULL) { log.AddLog( _T(__FILE__), __LINE__, L"CLANDiscovery::NetworkComputersIP", L"Could not enumerate computer resources. NETBIOS may disabled, protocol blocked by firewall or Network disabled."); return 0; } else { // DWORD ResourceCount=0xFFFFFFFF; DWORD BufferSize=2048; LPVOID Buffer=new char[2048]; WNetEnumResource(hEnum,&ResourceCount,Buffer,&BufferSize); NetResource= (NETRESOURCE*)Buffer; // if(ResourceCount<=0) { log.AddLog( _T(__FILE__), __LINE__, L"CLANDiscovery::NetworkComputersIP", L"Resource discovery returns %d computers. NETBIOS may disabled or protocol blocked by firewall.", ResourceCount); return 0; } // int const szlength=(32 + 1) * ResourceCount + 1; sz=new char[szlength+1]; if(sz==NULL) { log.AddLog( _T(__FILE__), __LINE__, L"CLANDiscovery::NetworkComputers", L"Memory allocation of %d bytes failed.", szlength+1); return 0; } // sz[0]='\0'; // char szHostName[64 + 1]; // #ifdef _DEBUG printf("BufferSize=%d\n",BufferSize); printf("sizeof(NETRESOURCE)=%d\n",sizeof(NETRESOURCE)); printf("ResourceCount=%d\n",ResourceCount); #endif for(unsigned int i=0; i < ResourceCount; i++, NetResource++) { if(ResourceCount==1 && NetResource->dwDisplayType==7) { log.AddLog( _T(__FILE__), __LINE__, L"CLANDiscovery::NetworkComputersIP", L"There may to be a network configuration problem preventing network discovery. Run the test harness for comparison and/or contact your administrator: dwUsage=%d dwType=%d dwDisplayType=%d lpRemoteName=%p lpLocalName=%p %s.", NetResource->dwUsage, NetResource->dwType, NetResource->dwDisplayType, NetResource->lpRemoteName, NetResource->lpLocalName, NetResource->lpLocalName); } #ifdef _DEBUG printf("%d] dwUsage=%d dwType=%d dwDisplayType=%d lpRemoteName=%p lpLocalName=%p %s\n", i, NetResource->dwUsage, NetResource->dwType, NetResource->dwDisplayType, NetResource->lpRemoteName, NetResource->lpLocalName, NetResource->lpLocalName); #endif if( NetResource->dwUsage == RESOURCEUSAGE_CONTAINER && NetResource->dwType == RESOURCETYPE_ANY ) { if(NetResource->lpRemoteName) { // computers++; // char szRemoteName[256 + 1]; //#ifdef _UNICODE size_t lenRemoteName=wcslen(NetResource->lpRemoteName); if(lenRemoteName>256) lenRemoteName=256; wcstombs(szRemoteName,NetResource->lpRemoteName,lenRemoteName); //#else // int lenRemoteName=strlen(NetResource->lpRemoteName); // if(lenRemoteName>256) lenRemoteName=256; // strncpy(szRemoteName,NetResource->lpRemoteName,lenRemoteName); //#endif szRemoteName[lenRemoteName]='\0'; char szFullName[256 + 1]; if(strncmp(szRemoteName,"\\\\",2) == 0) strncpy(szFullName,(szRemoteName) + 2,lenRemoteName - 2 + 1); else strncpy(szFullName,szRemoteName,lenRemoteName + 1); #ifdef _DEBUG printf(" lpRemoteName=%s\n",szRemoteName); printf(" szFullName=%s\n",szFullName); #endif // struct hostent* host; struct in_addr* ptr; gethostname(szHostName,(int)strlen(szHostName)); #ifdef _DEBUG printf(" szHostName=%s\n",szHostName); #endif host=gethostbyname(szFullName); if(host) { // ptr= (struct in_addr*)host->h_addr_list[0]; // const int a=ptr->S_un.S_un_b.s_b1; const int b=ptr->S_un.S_un_b.s_b2; const int c=ptr->S_un.S_un_b.s_b3; const int d=ptr->S_un.S_un_b.s_b4; char tmp[18 + 1]; _snprintf(tmp,18,"%d.%d.%d.%d",a,b,c,d); strcat(sz,tmp); if(i < ResourceCount - 1) strcat(sz,","); #ifdef _DEBUG printf(" %d] %s --> %d.%d.%d.%d\n",i,szFullName,a,b,c,d); #endif } } } } // delete[] Buffer; Buffer=NULL; // WNetCloseEnum(hEnum); } return computers; }
int CNetWorkFinder::StartFind(LPNETRESOURCE lpnr) { DWORD dwResult, dwResultEnum; HANDLE hEnum; DWORD cbBuffer = 16384; // 16K is a good size DWORD cEntries = (DWORD)-1; // enumerate all possible entries LPNETRESOURCE lpnrLocal; // pointer to enumerated structures DWORD i; int count = 0; // // Call the WNetOpenEnum function to begin the enumeration. // dwResult = WNetOpenEnum(RESOURCE_GLOBALNET, // all network resources RESOURCETYPE_ANY, // all resources 0, // enumerate all resources lpnr, // NULL first time the function is called &hEnum); // handle to the resource TCHAR szDescription[256]; TCHAR szProvider[256]; DWORD dwWNetResult, dwLastError; if (dwResult != NO_ERROR) { dwWNetResult = WNetGetLastError(&dwLastError, // error code szDescription, // buffer for error description sizeof(szDescription), // size of error buffer szProvider, // buffer for provider name sizeof(szProvider)); // size of name buffer // // Process errors with an application-defined error handler. // return count; } // // Call the GlobalAlloc function to allocate resources. // lpnrLocal = (LPNETRESOURCE) GlobalAlloc(GPTR, cbBuffer); if (lpnrLocal == NULL) return count; do { // // Initialize the buffer. // ZeroMemory(lpnrLocal, cbBuffer); // // Call the WNetEnumResource function to continue // the enumeration. // dwResultEnum = WNetEnumResource(hEnum, // resource handle &cEntries, // defined locally as -1 lpnrLocal, // LPNETRESOURCE &cbBuffer); // buffer size // // If the call succeeds, loop through the structures. // bool bRecursive = m_bRecursive; if (dwResultEnum == NO_ERROR) { count += cEntries; // Sort as per thier name as qsort(lpnrLocal, cEntries, sizeof(NETRESOURCE), (GenericCompareFn)CompareNetResource); for(i = 0; i < cEntries && !m_bAborted; i++) { // Call callback if (mNetWorkFindCallBack != NULL) { switch (mNetWorkFindCallBack(lpnrLocal+i,m_pUserParam)) { case FCB_ABORT: m_bAborted = true; break; case FCB_DORECURSIVE: bRecursive = true; break; case FCB_NORECURSIVE: bRecursive = false; break; } } if (!m_bAborted && cEntries > 0 && bRecursive) { if(RESOURCEUSAGE_CONTAINER == (lpnrLocal[i].dwUsage & RESOURCEUSAGE_CONTAINER)) count += StartFind(&lpnrLocal[i]); } } } // Process errors. // else if (dwResultEnum != ERROR_NO_MORE_ITEMS) { break; } } // // End do. // while(dwResultEnum != ERROR_NO_MORE_ITEMS && !m_bAborted); // // Call the GlobalFree function to free the memory. // GlobalFree((HGLOBAL)lpnrLocal); // // Call WNetCloseEnum to end the enumeration. // dwResult = WNetCloseEnum(hEnum); return count; }