2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
11 #include <afs/param.h>
14 #include <afs/fs_utils.h>
19 #include <WINNT/TaLocale.h>
26 #include <lanahelper.h>
28 extern void Config_GetLanAdapter (ULONG *pnLanAdapter);
31 * REGISTRY ___________________________________________________________________
35 #undef AFSConfigKeyName
36 const TCHAR sAFSConfigKeyName[] = TEXT("SYSTEM\\CurrentControlSet\\Services\\TransarcAFSDaemon\\Parameters");
40 * PROFILE SECTIONS ___________________________________________________________
44 #define cREALLOC_SUBMOUNTS 4
46 static TCHAR cszSECTION_SUBMOUNTS[] = TEXT("SOFTWARE\\OpenAFS\\Client\\Submounts");
47 static TCHAR cszSECTION_MAPPINGS[] = TEXT("SOFTWARE\\OpenAFS\\Client\\Mappings");
48 static TCHAR cszSECTION_ACTIVE[] = TEXT("SOFTWARE\\OpenAFS\\Client\\Active Maps");
50 static TCHAR cszAUTOSUBMOUNT[] = TEXT("Auto");
51 static TCHAR cszLANMANDEVICE[] = TEXT("\\Device\\LanmanRedirector\\");
55 WriteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
62 REG_OPTION_NON_VOLATILE,
68 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
73 return (status == ERROR_SUCCESS);
77 ReadRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs, DWORD * size)
84 REG_OPTION_NON_VOLATILE,
91 DWORD status = RegQueryValueEx( hkSub, lhs, 0, &dwType, (LPBYTE)rhs, size );
96 return (status == ERROR_SUCCESS);
100 DeleteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs)
107 REG_OPTION_NON_VOLATILE,
114 DWORD status = RegDeleteValue( hkSub, lhs );
117 RegCloseKey( hkSub );
119 return (status == ERROR_SUCCESS);
123 * STRINGS ____________________________________________________________________
127 static LPTSTR AllocateStringMemory (size_t cch)
129 LPTSTR psz = (LPTSTR)Allocate (sizeof(TCHAR) * (cch+1));
130 memset (psz, 0x00, sizeof(TCHAR) * (cch+1));
134 static void FreeStringMemory (LPTSTR pszString)
139 static int lstrncmpi (LPCTSTR pszA, LPCTSTR pszB, size_t cch)
143 return (!pszB) - (!pszA); // A,!B:1, !A,B:-1, !A,!B:0
146 for ( ; cch > 0; cch--, pszA = CharNext(pszA), pszB = CharNext(pszB))
148 TCHAR chA = toupper( *pszA );
149 TCHAR chB = toupper( *pszB );
152 return (!chB) - (!chA); // A,!B:1, !A,B:-1, !A,!B:0
155 return (int)(chA) - (int)(chB); // -1:A<B, 0:A==B, 1:A>B
158 return 0; // no differences before told to stop comparing, so A==B
163 * REALLOC ____________________________________________________________________
168 #define REALLOC(_a,_c,_r,_i) DriveMapReallocFunction ((LPVOID*)&_a,sizeof(*_a),&_c,_r,_i)
169 BOOL DriveMapReallocFunction (LPVOID *ppTarget, size_t cbElement, size_t *pcTarget, size_t cReq, size_t cInc)
174 if (cReq <= *pcTarget)
177 if ((cNew = cInc * ((cReq + cInc-1) / cInc)) <= 0)
180 if ((pNew = Allocate (cbElement * cNew)) == NULL)
182 memset (pNew, 0x00, cbElement * cNew);
186 memcpy (pNew, *ppTarget, cbElement * (*pcTarget));
198 * WINDOWS NT STUFF ___________________________________________________________
202 static BOOL IsWindowsNT (void)
204 static BOOL fChecked = FALSE;
205 static BOOL fIsWinNT = FALSE;
211 OSVERSIONINFO Version;
212 memset (&Version, 0x00, sizeof(Version));
213 Version.dwOSVersionInfoSize = sizeof(Version);
215 if (GetVersionEx (&Version))
217 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT)
225 /* Check if the OS is Windows 2000 or higher.
227 BOOL IsWindows2000 (void)
229 static BOOL fChecked = FALSE;
230 static BOOL fIsWin2K = FALSE;
236 OSVERSIONINFO Version;
237 memset (&Version, 0x00, sizeof(Version));
238 Version.dwOSVersionInfoSize = sizeof(Version);
240 if (GetVersionEx (&Version))
242 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
243 Version.dwMajorVersion >= 5)
252 * GENERAL ____________________________________________________________________
256 void GetClientNetbiosName (LPTSTR pszName)
258 static TCHAR szNetbiosName[32] = "";
260 if ( szNetbiosName[0] == 0 ) {
261 lana_GetNetbiosName(szNetbiosName, LANA_NETBIOS_NAME_FULL);
263 _tcscpy(pszName, szNetbiosName);
267 BOOL SubmountToPath (PDRIVEMAPLIST pList, LPTSTR pszPath, LPTSTR pszSubmount, BOOL fMarkInUse)
269 // We can't do this translation unless we're under Windows NT.
274 // \\computer-afs\all always maps to "/afs"
276 if (!lstrcmpi (pszSubmount, TEXT("all")))
278 lstrcpy (pszPath, cm_slash_mount_root);
282 // Otherwise, look up our list of submounts.
284 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
286 if (!lstrcmpi (pList->aSubmounts[ii].szSubmount, pszSubmount))
289 pList->aSubmounts[ii].fInUse = TRUE;
290 AdjustAfsPath (pszPath, pList->aSubmounts[ii].szMapping, TRUE, TRUE);
299 BOOL IsValidSubmountName (LPTSTR pszSubmount)
303 if (lstrlen (pszSubmount) > 12)
306 for ( ; *pszSubmount; ++pszSubmount)
308 if (!isprint(*pszSubmount))
310 if (*pszSubmount == TEXT(' '))
312 if (*pszSubmount == TEXT('\t'))
321 * PIOCTL SUPPORT _____________________________________________________________
327 #include "../afsd/fs_utils.h"
329 #define __CM_CONFIG_INTERFACES_ONLY__
330 #include "../afsd/cm_config.h"
332 #define __CM_IOCTL_INTERFACES_ONLY__
333 #include "../afsd/cm_ioctl.h"
337 #define PIOCTL_MAXSIZE 2048
340 BOOL fCanIssuePIOCTL (void)
344 TCHAR szGateway[ 256 ] = TEXT("");
345 GetClientNetbiosName (szGateway);
346 return (szGateway[0]) ? TRUE : FALSE;
349 SERVICE_STATUS Status;
350 memset (&Status, 0x00, sizeof(Status));
351 Status.dwCurrentState = SERVICE_STOPPED;
354 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
357 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
359 QueryServiceStatus (hService, &Status);
360 CloseServiceHandle (hService);
363 CloseServiceHandle (hManager);
366 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
371 * QUERYDRIVEMAPLIST __________________________________________________________
375 void QueryDriveMapList_ReadSubmounts (PDRIVEMAPLIST pList)
381 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
382 "SOFTWARE\\OpenAFS\\Client\\Submounts",
385 REG_OPTION_NON_VOLATILE,
386 KEY_READ|KEY_QUERY_VALUE,
392 RegQueryInfoKey( hkSubmounts,
395 NULL, /* lpReserved */
396 NULL, /* lpcSubKeys */
397 NULL, /* lpcMaxSubKeyLen */
398 NULL, /* lpcMaxClassLen */
399 &dwSubmounts, /* lpcValues */
400 NULL, /* lpcMaxValueNameLen */
401 NULL, /* lpcMaxValueLen */
402 NULL, /* lpcbSecurityDescriptor */
403 NULL /* lpftLastWriteTime */
406 for ( DWORD dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
407 TCHAR submountPath[MAX_PATH] = "";
408 DWORD submountPathLen = MAX_PATH;
409 TCHAR submountName[MAX_PATH];
410 DWORD submountNameLen = MAX_PATH;
413 RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
414 &dwType, (LPBYTE)submountPath, &submountPathLen);
417 memset (&Submount, 0x00, sizeof(SUBMOUNT));
418 lstrcpy (Submount.szSubmount, submountName);
420 if ( submountPath[0] != TEXT('\0') ) {
421 AdjustAfsPath (Submount.szMapping, submountPath, FALSE, TRUE);
423 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
425 if (!pList->aSubmounts[ii].szSubmount[0])
428 if (REALLOC (pList->aSubmounts, pList->cSubmounts, 1+ii, cREALLOC_SUBMOUNTS))
430 memcpy (&pList->aSubmounts[ii], &Submount, sizeof(SUBMOUNT));
435 RegCloseKey(hkSubmounts);
440 void QueryDriveMapList_ReadMappings (PDRIVEMAPLIST pList)
443 RegCreateKeyEx( HKEY_CURRENT_USER,
444 "SOFTWARE\\OpenAFS\\Client\\Mappings",
447 REG_OPTION_NON_VOLATILE,
448 KEY_READ|KEY_QUERY_VALUE,
454 RegQueryInfoKey( hkMappings,
457 NULL, /* lpReserved */
458 NULL, /* lpcSubKeys */
459 NULL, /* lpcMaxSubKeyLen */
460 NULL, /* lpcMaxClassLen */
461 &dwMappings, /* lpcValues */
462 NULL, /* lpcMaxValueNameLen */
463 NULL, /* lpcMaxValueLen */
464 NULL, /* lpcbSecurityDescriptor */
465 NULL /* lpftLastWriteTime */
468 for ( DWORD dwIndex = 0; dwIndex < dwMappings; dwIndex ++ ) {
469 TCHAR mapping[MAX_PATH] = "";
470 DWORD mappingLen = MAX_PATH;
471 TCHAR drive[MAX_PATH];
472 DWORD driveLen = MAX_PATH;
475 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL,
476 &dwType, (LPBYTE)mapping, &mappingLen);
479 memset (&DriveMap, 0x00, sizeof(DRIVEMAP));
480 DriveMap.chDrive = toupper(*drive);
481 DriveMap.fPersistent = TRUE;
482 if ((DriveMap.chDrive < chDRIVE_A) || (DriveMap.chDrive > chDRIVE_Z))
485 if (mapping[0] != TEXT('\0'))
487 AdjustAfsPath (DriveMap.szMapping, mapping, TRUE, TRUE);
488 if (DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] == TEXT('*'))
490 DriveMap.fPersistent = FALSE;
491 DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] = TEXT('\0');
493 size_t iDrive = DriveMap.chDrive - chDRIVE_A;
494 memcpy (&pList->aDriveMap[ iDrive ], &DriveMap, sizeof(DRIVEMAP));
498 RegCloseKey(hkMappings);
501 BOOL ForceMapActive (TCHAR chDrive)
506 szDrive[0] = chDrive;
509 DWORD len = sizeof(szActive);
510 ReadRegistryString( HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, szActive, &len);
512 if ( !lstrcmp(szActive,"1") || !lstrcmpi(szActive,"true") || !lstrcmpi(szActive,"on") || !lstrcmpi(szActive,"yes") )
518 void WriteActiveMap (TCHAR chDrive, BOOL on)
522 szDrive[0] = chDrive;
525 WriteRegistryString(HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, on ? "1" : "0");
528 void QueryDriveMapList_WriteMappings (PDRIVEMAPLIST pList)
530 WriteDriveMappings (pList);
534 void WriteDriveMappings (PDRIVEMAPLIST pList)
537 RegCreateKeyEx( HKEY_CURRENT_USER,
538 "SOFTWARE\\OpenAFS\\Client\\Mappings",
541 REG_OPTION_NON_VOLATILE,
542 KEY_READ|KEY_QUERY_VALUE|KEY_WRITE,
548 RegQueryInfoKey( hkMappings,
551 NULL, /* lpReserved */
552 NULL, /* lpcSubKeys */
553 NULL, /* lpcMaxSubKeyLen */
554 NULL, /* lpcMaxClassLen */
555 &dwMappings, /* lpcValues */
556 NULL, /* lpcMaxValueNameLen */
557 NULL, /* lpcMaxValueLen */
558 NULL, /* lpcbSecurityDescriptor */
559 NULL /* lpftLastWriteTime */
562 if ( dwMappings > 0 ) {
563 for ( long dwIndex = dwMappings - 1; dwIndex >= 0; dwIndex-- ) {
564 TCHAR drive[MAX_PATH];
565 DWORD driveLen = MAX_PATH;
567 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL, NULL, NULL, NULL);
568 RegDeleteValue( hkMappings, drive );
572 for (size_t iDrive = 0; iDrive < 26; ++iDrive)
574 if (pList->aDriveMap[iDrive].szMapping[0] != TEXT('\0'))
576 TCHAR szLHS[] = TEXT("*");
577 szLHS[0] = pList->aDriveMap[iDrive].chDrive;
579 TCHAR szRHS[MAX_PATH];
580 AdjustAfsPath (szRHS, pList->aDriveMap[iDrive].szMapping, TRUE, TRUE);
581 if (!pList->aDriveMap[iDrive].fPersistent)
582 lstrcat (szRHS, TEXT("*"));
584 RegSetValueEx( hkMappings, szLHS, 0, REG_SZ, (const BYTE *)szRHS, lstrlen(szRHS) + 1);
587 RegCloseKey( hkMappings );
590 BOOL DriveIsGlobalAfsDrive(TCHAR chDrive)
592 TCHAR szKeyName[128];
593 TCHAR szValueName[128];
597 _stprintf(szKeyName, TEXT("%s\\GlobalAutoMapper"), sAFSConfigKeyName);
599 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
602 _stprintf(szValueName, TEXT("%c:"), chDrive);
604 DWORD dwSize = sizeof(szValue);
605 BOOL bIsGlobal = (RegQueryValueEx (hKey, szValueName, NULL, NULL, (PBYTE)szValue, &dwSize) == ERROR_SUCCESS);
613 void QueryDriveMapList_FindNetworkDrives (PDRIVEMAPLIST pList, BOOL *pfFoundNew)
615 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
617 TCHAR szSubmount[ MAX_PATH ];
618 if (!GetDriveSubmount (chDrive, szSubmount))
621 // We've got a mapping! Drive {chDrive} is mapped to submount
622 // {szSubmount}. See if that submount makes sense.
626 size_t iDrive = chDrive - chDRIVE_A;
627 if (pList->aDriveMap[ iDrive ].szMapping[0] != TEXT('\0'))
629 pList->aDriveMap[ iDrive ].fActive = TRUE;
630 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
634 else // (IsWindowsNT())
636 TCHAR szAfsPath[ MAX_PATH ];
637 if (!SubmountToPath (pList, szAfsPath, szSubmount, TRUE))
640 // Okay, we know that drive {chDrive} is mapped to afs path {szAfsPath}.
641 // If this drive is a global afs drive, then reject it. Otherwise, look
642 // at pList->aDriveMap, to see if this drive mapping is already in our
643 // list. If not, add it and set pfFoundNew.
645 if (DriveIsGlobalAfsDrive(chDrive))
648 size_t iDrive = chDrive - chDRIVE_A;
649 if (lstrcmpi (pList->aDriveMap[ iDrive ].szMapping, szAfsPath))
652 pList->aDriveMap[ iDrive ].fPersistent = TRUE;
654 pList->aDriveMap[ iDrive ].fActive = TRUE;
655 pList->aDriveMap[ iDrive ].chDrive = chDrive;
656 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
657 AdjustAfsPath (pList->aDriveMap[ iDrive ].szMapping, szAfsPath, TRUE, TRUE);
663 void QueryDriveMapList (PDRIVEMAPLIST pList)
665 // Initialize the data structure
667 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
668 for (size_t ii = 0; ii < 26; ++ii)
669 pList->aDriveMap[ii].chDrive = chDRIVE_A + ii;
671 // Read the current lists of submounts and drive letter mappings
673 QueryDriveMapList_ReadSubmounts (pList);
674 QueryDriveMapList_ReadMappings (pList);
676 // Look through the current list of network drives, and see if
677 // any are currently mapped to AFS. If we find any which are mapped
678 // into AFS unexpectedly, we'll have to rewrite the mappings list.
680 BOOL fFoundNew = FALSE;
681 QueryDriveMapList_FindNetworkDrives (pList, &fFoundNew);
685 QueryDriveMapList_WriteMappings (pList);
690 void FreeDriveMapList (PDRIVEMAPLIST pList)
692 if (pList->aSubmounts)
693 Free (pList->aSubmounts);
694 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
698 BOOL PathToSubmount (LPTSTR pszSubmount, LPTSTR pszMapping, LPTSTR pszSubmountReq, ULONG *pStatus)
700 if (pszSubmountReq && !IsValidSubmountName (pszSubmountReq))
701 pszSubmountReq = NULL;
703 TCHAR szAfsPath[ MAX_PATH ];
704 AdjustAfsPath (szAfsPath, pszMapping, TRUE, TRUE);
706 // Try to ask AFSD for a new submount name.
708 if (!fCanIssuePIOCTL())
711 BYTE InData[ PIOCTL_MAXSIZE ];
712 memset (InData, 0x00, sizeof(InData));
714 LPTSTR pszInData = (LPTSTR)InData;
715 lstrcpy (pszInData, pszMapping);
716 pszInData += 1+lstrlen(pszInData);
718 lstrcpy (pszInData, pszSubmountReq);
720 BYTE OutData[ PIOCTL_MAXSIZE ];
721 memset (OutData, 0x00, sizeof(OutData));
723 struct ViceIoctl IOInfo;
724 IOInfo.in = (char *)InData;
725 IOInfo.in_size = PIOCTL_MAXSIZE;
726 IOInfo.out = (char *)OutData;
727 IOInfo.out_size = PIOCTL_MAXSIZE;
729 ULONG status = pioctl (0, VIOC_MAKESUBMOUNT, &IOInfo, 1);
736 lstrcpy (pszSubmount, (LPCTSTR)OutData);
737 return (pszSubmount[0] != TEXT('\0')) ? TRUE : FALSE;
741 BOOL ActivateDriveMap (TCHAR chDrive, LPTSTR pszMapping, LPTSTR pszSubmountReq, BOOL fPersistent, DWORD *pdwStatus)
743 // We can only map drives to places in AFS using this function.
745 if ( (lstrncmpi (pszMapping, cm_slash_mount_root, lstrlen(cm_slash_mount_root))) &&
746 (lstrncmpi (pszMapping, cm_back_slash_mount_root, lstrlen(cm_back_slash_mount_root))) )
749 *pdwStatus = ERROR_BAD_NETPATH;
753 // First we have to translate {pszMapping} into a submount, and if there is
754 // no current submount associated with this path, we'll have to make one.
757 TCHAR szSubmount[ MAX_PATH ];
758 if (!PathToSubmount (szSubmount, pszMapping, pszSubmountReq, &status))
765 // We now have a submount name and drive letter--map the network drive.
766 DWORD rc=MountDOSDrive(chDrive,szSubmount,fPersistent,NULL);
776 BOOL InactivateDriveMap (TCHAR chDrive, DWORD *pdwStatus)
778 DWORD rc = DisMountDOSDrive(chDrive, FALSE);
788 void AddSubMount (LPTSTR pszSubmount, LPTSTR pszMapping)
790 TCHAR szRHS[ MAX_PATH ];
791 AdjustAfsPath (szRHS, pszMapping, FALSE, TRUE);
793 lstrcpy (szRHS, TEXT("/"));
795 WriteRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount, szRHS);
799 void RemoveSubMount (LPTSTR pszSubmount)
801 DeleteRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount);
805 void AdjustAfsPath (LPTSTR pszTarget, LPCTSTR pszSource, BOOL fWantAFS, BOOL fWantForwardSlashes)
808 lstrcpy (pszTarget, (fWantAFS) ? cm_slash_mount_root : TEXT(""));
809 else if ((*pszSource != TEXT('/')) && (*pszSource != TEXT('\\')))
810 wsprintf (pszTarget, TEXT("%s/%s"),cm_slash_mount_root, pszSource);
811 // We don't want to strip afs off the start if it is part of something for example afscell.company.com
812 else if (fWantAFS && (lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root))) || !((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
813 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
814 (lstrlen(pszSource) == strlen(cm_slash_mount_root))))
815 wsprintf (pszTarget, TEXT("%s%s"),cm_slash_mount_root, pszSource);
816 else if (!fWantAFS && (!lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root)) && ((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
817 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
818 (lstrlen(pszSource) == strlen(cm_slash_mount_root)))))
819 lstrcpy (pszTarget, &pszSource[strlen(cm_slash_mount_root)]);
821 lstrcpy (pszTarget, pszSource);
823 for (LPTSTR pch = pszTarget; *pch; ++pch)
825 if (fWantForwardSlashes)
827 *pch = (*pch == TEXT('\\')) ? TEXT('/') : (*pch);
829 else // (!fWantForwardSlashes)
831 *pch = (*pch == TEXT('/')) ? TEXT('\\') : (*pch);
835 if (lstrlen(pszTarget) &&
836 ((pszTarget[lstrlen(pszTarget)-1] == TEXT('/')) ||
837 (pszTarget[lstrlen(pszTarget)-1] == TEXT('\\'))))
839 pszTarget[lstrlen(pszTarget)-1] = TEXT('\0');
843 BOOL GetDriveSubmount (TCHAR chDrive, LPTSTR pszSubmountNow)
845 BOOL isWinNT = IsWindowsNT();
847 TCHAR szDrive[] = TEXT("*:");
848 szDrive[0] = chDrive;
850 TCHAR szMapping[ _MAX_PATH ] = TEXT("");
852 if (isWinNT && !QueryDosDevice (szDrive, szMapping, MAX_PATH))
855 LPTSTR pszSubmount = szMapping;
857 TCHAR szNetBiosName[32];
858 memset(szNetBiosName, '\0', sizeof(szNetBiosName));
859 GetClientNetbiosName(szNetBiosName);
860 _tcscat(szNetBiosName, TEXT("\\"));
864 // Now if this is an AFS network drive mapping, {szMapping} will be:
866 // \Device\LanmanRedirector\<Drive>:\<netbiosname>\submount
868 // on Windows NT. On Windows 2000, it will be:
870 // \Device\LanmanRedirector\;<Drive>:0\<netbiosname>\submount
872 // (This is presumably to support multiple drive mappings with
875 // on Windows XP and 2003, it will be :
876 // \Device\LanmanRedirector\;<Drive>:<AuthID>\<netbiosname>\submount
878 // where : <Drive> : DOS drive letter
879 // <AuthID>: Authentication ID, 16 char hex.
880 // <netbiosname>: Netbios name of server
882 if (_tcsnicmp(szMapping, cszLANMANDEVICE, _tcslen(cszLANMANDEVICE)))
884 pszSubmount = &szMapping[ _tcslen(cszLANMANDEVICE) ];
888 if (*(pszSubmount) != TEXT(';'))
893 if (toupper(*(++pszSubmount)) != chDrive)
896 if (*(++pszSubmount) != TEXT(':'))
900 // No longer a safe assumption on XP
902 if (*(++pszSubmount) != TEXT('0'))
907 while (*(++pszSubmount) != TEXT('\\'))
913 // note that szNetBiosName has a '\\' tagged in the end earlier
914 for (++pszSubmount; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
915 if (!_tcsncicmp(pszSubmount, szNetBiosName, _tcslen(szNetBiosName)))
917 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
920 pszSubmount += _tcslen(szNetBiosName);
922 else // (!IsWindowsNT())
924 DWORD dwSize = MAX_PATH;
925 if (WNetGetConnection (szDrive, szMapping, &dwSize) != NO_ERROR)
927 if (*(pszSubmount++) != TEXT('\\'))
929 if (*(pszSubmount++) != TEXT('\\'))
931 for ( ; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
932 if (!lstrncmpi (pszSubmount, szNetBiosName, lstrlen(szNetBiosName)))
934 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
936 pszSubmount += lstrlen(szNetBiosName);
939 if (!pszSubmount || !*pszSubmount)
942 lstrcpy (pszSubmountNow, pszSubmount);
946 /* Generate Random User name random acording to time*/
948 TCHAR pUserName[MAXRANDOMNAMELEN]=TEXT("");
949 BOOL fUserName=FALSE;
950 #define AFSLogonOptionName TEXT("System\\CurrentControlSet\\Services\\TransarcAFSDaemon\\NetworkProvider")
952 void SetBitLogonOption(BOOL set,DWORD value)
955 RWLogonOption(FALSE,((set)?value | RWLogonOption(TRUE,0):RWLogonOption(TRUE,0) & ~value) );
958 DWORD RWLogonOption(BOOL read,DWORD value)
960 // if read is true then if value==0 return registry value
961 // if read and value!=0 then use value to test registry, return TRUE if value bits match value read
964 DWORD LSPtype, LSPsize;
969 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, KEY_QUERY_VALUE, &hk)==ERROR_SUCCESS)
971 LSPsize=sizeof(rval);
972 RegQueryValueEx(hk, "LogonOptions", NULL,
973 &LSPtype, (LPBYTE)&rval, &LSPsize);
976 return (value==0)?rval:((rval & value)==value);
979 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, NULL, 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
981 RegSetValueEx(hk,TEXT("LogonOptions"),NULL,REG_DWORD,(LPBYTE)&value,sizeof(value));
988 void MapShareName(char *pszCmdLineA)
993 while (*pszCmdLineA && (*pszCmdLineA != ' '))
999 void GenRandomName(TCHAR *pname,int len)
1002 { //user name was passed through command line, use once
1006 srand( (unsigned)time( NULL ) );
1007 for (int i=0;i<len;i++)
1008 pname[i]='a'+(rand() % 26);
1014 Make a connection using users name
1015 if fUserName then force a connection
1018 BOOL TestAndDoMapShare(DWORD dwState)
1020 if ((dwState!=SERVICE_RUNNING) || (dwOldState!=SERVICE_START_PENDING))
1025 dwOldState=SERVICE_RUNNING;
1026 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1027 return (DoMapShare() && GlobalMountDrive());
1028 return GlobalMountDrive();
1031 BOOL IsServiceActive()
1034 SERVICE_STATUS Status;
1035 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
1038 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
1040 QueryServiceStatus (hService, &Status);
1041 CloseServiceHandle (hService);
1044 CloseServiceHandle (hManager);
1047 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
1050 void TestAndDoUnMapShare()
1052 if (!RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1054 DoUnMapShare(FALSE);
1057 void DoUnMapShare(BOOL drivemap) //disconnect drivemap
1059 TCHAR szMachine[MAX_PATH],szPath[MAX_PATH];
1062 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1064 DWORD cbBuffer=16384;
1068 memset(szMachine, '\0', sizeof(szMachine));
1069 GetClientNetbiosName(szMachine);
1071 // Initialize the data structure
1072 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1074 sprintf(szPath,"\\\\%s\\",szMachine);
1076 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1078 memset(lpnrLocal,0,cbBuffer);
1079 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1081 for (DWORD i=0;i<cEntries;i++)
1083 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath))
1085 if ((lpnrLocal[i].lpLocalName) && (strlen(lpnrLocal[i].lpLocalName)>0))
1088 DisMountDOSDrive(*lpnrLocal[i].lpLocalName);
1089 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Local=%x",res);
1092 DisMountDOSDriveFull(lpnrLocal[i].lpRemoteName);
1093 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Remote=%x",res);
1098 } while (res!=ERROR_NO_MORE_ITEMS);
1099 GlobalFree((HGLOBAL)lpnrLocal);
1100 WNetCloseEnum(hEnum);
1103 BOOL DoMapShareChange()
1106 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1109 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1112 DWORD cbBuffer=16384;
1114 memset(szMachine, '\0', sizeof(szMachine));
1115 GetClientNetbiosName(szMachine);
1117 // Initialize the data structure
1118 if (!IsServiceActive())
1120 memset (&List, 0x00, sizeof(DRIVEMAPLIST));
1121 for (size_t ii = 0; ii < 26; ++ii)
1122 List.aDriveMap[ii].chDrive = chDRIVE_A + ii;
1123 QueryDriveMapList_ReadSubmounts (&List);
1124 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1126 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1127 sprintf(szPath,"\\\\%s\\",szMachine);
1130 memset(lpnrLocal,0,cbBuffer);
1131 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1133 for (DWORD i=0;i<cEntries;i++)
1135 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)==NULL)
1136 continue; //only look at real afs mappings
1137 CHAR * pSubmount=strrchr(lpnrLocal[i].lpRemoteName,'\\')+1;
1138 if (lstrcmpi(pSubmount,"all")==0)
1139 continue; // do not remove 'all'
1140 for (DWORD j=0;j<List.cSubmounts;j++)
1143 (List.aSubmounts[j].szSubmount[0]) &&
1144 (lstrcmpi(List.aSubmounts[j].szSubmount,pSubmount)==0)
1147 List.aSubmounts[j].fInUse=TRUE;
1151 // wasn't on list so lets remove
1152 DisMountDOSDrive(pSubmount);
1156 } while (res!=ERROR_NO_MORE_ITEMS);
1157 GlobalFree((HGLOBAL)lpnrLocal);
1158 WNetCloseEnum(hEnum);
1159 sprintf(szPath,"\\\\%s\\all",szMachine);
1161 // Lets connect all submounts that weren't connectd
1162 DWORD cbUser=MAXRANDOMNAMELEN-1;
1163 CHAR szUser[MAXRANDOMNAMELEN];
1164 CHAR * pUser = NULL;
1165 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1166 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1167 if (!pUserName[0]) {
1168 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1175 if ((pUser=strchr(szUser,'\\'))!=NULL)
1179 for (DWORD j=0;j<List.cSubmounts;j++)
1181 if (List.aSubmounts[j].fInUse)
1183 DWORD res=MountDOSDrive(0,List.aSubmounts[j].szSubmount,FALSE,pUser);
1192 BOOL bMappedAll=FALSE;
1194 // Initialize the data structure
1195 DEBUG_EVENT0("AFS DoMapShare");
1196 QueryDriveMapList (&List);
1198 // All connections have been removed
1199 // Lets restore them after making the connection from the random name
1201 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1202 memset(szMachine, '\0', sizeof(szMachine));
1203 GetClientNetbiosName(szMachine);
1204 sprintf(szPath,"\\\\%s\\all",szMachine);
1206 // Lets connect all submounts that weren't connectd
1207 DWORD cbUser=MAXRANDOMNAMELEN-1;
1208 CHAR szUser[MAXRANDOMNAMELEN];
1209 CHAR * pUser = NULL;
1210 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1211 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1212 if (!pUserName[0]) {
1213 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1220 if ((pUser=strchr(szUser,'\\'))!=NULL)
1224 for (DWORD i=0;i<List.cSubmounts;i++)
1226 if (List.aSubmounts[i].szSubmount[0])
1228 DWORD res=MountDOSDrive(0,List.aSubmounts[i].szSubmount,FALSE,pUser);
1229 if (lstrcmpi("all",List.aSubmounts[i].szSubmount)==0)
1233 if (!bMappedAll) //make sure all is mapped also
1235 DWORD res=MountDOSDrive(0,"all",FALSE,pUser);
1236 if (res==ERROR_SESSION_CREDENTIAL_CONFLICT)
1238 DisMountDOSDrive("all");
1239 MountDOSDrive(0,"all",FALSE,pUser);
1242 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
1244 if (List.aDriveMap[chDrive-chDRIVE_A].fActive ||
1245 ForceMapActive(chDrive))
1247 TCHAR szSubmount[ MAX_PATH ];
1248 if (List.aDriveMap[chDrive-chDRIVE_A].szSubmount[0])
1249 lstrcpy(szSubmount,List.aDriveMap[chDrive-chDRIVE_A].szSubmount);
1250 else if (!PathToSubmount (szSubmount, List.aDriveMap[chDrive-chDRIVE_A].szMapping, NULL, NULL))
1253 BOOL fPersistent = List.aDriveMap[chDrive-chDRIVE_A].fPersistent;
1254 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1255 fPersistent = FALSE;
1256 DWORD res=MountDOSDrive(chDrive
1258 ,fPersistent,pUser);
1264 BOOL GlobalMountDrive()
1266 char szDriveToMapTo[5];
1268 char szKeyName[256];
1272 DWORD dwSubMountSize;
1273 char unsigned szSubMount[256];
1274 char cm_HostName[200];
1275 DWORD dwType=sizeof(cm_HostName);
1276 if (!IsServiceActive())
1278 if (!GetComputerName(cm_HostName, &dwType))
1280 sprintf(szKeyName, "%s\\GlobalAutoMapper", sAFSConfigKeyName);
1282 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE,
1284 if (dwResult != ERROR_SUCCESS)
1288 dwDriveSize = sizeof(szDriveToMapTo);
1289 dwSubMountSize = sizeof(szSubMount);
1290 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize,
1291 0, &dwType, szSubMount, &dwSubMountSize);
1292 if (dwResult != ERROR_MORE_DATA) {
1293 if (dwResult != ERROR_SUCCESS) {
1294 if (dwResult != ERROR_NO_MORE_ITEMS)
1296 DEBUG_EVENT1("AFS DriveMap","Failed to read GlobalAutoMapper values: %d",dwResult);
1301 dwResult=MountDOSDrive(*szDriveToMapTo,(const char *)szSubMount,FALSE,NULL);
1307 DWORD MountDOSDrive(char chDrive,const char *szSubmount,BOOL bPersistent,const char * pUsername)
1309 TCHAR szPath[MAX_PATH];
1310 TCHAR szClient[MAX_PATH];
1311 TCHAR szDrive[3] = TEXT("?:");
1312 sprintf(szDrive,"%c:",chDrive);
1313 GetClientNetbiosName (szClient);
1314 sprintf(szPath,"\\\\%s\\%s",szClient,szSubmount);
1316 memset (&nr, 0x00, sizeof(NETRESOURCE));
1317 nr.dwType=RESOURCETYPE_DISK;
1318 nr.lpLocalName=szDrive;
1319 nr.lpRemoteName=szPath;
1320 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE;
1321 DWORD res=WNetAddConnection2(&nr,NULL,pUsername,(bPersistent)?CONNECT_UPDATE_PROFILE:0);
1322 DEBUG_EVENT5("AFS DriveMap","Mount %s Local[%s] Remote[%s] User[%s]=%x",
1323 (bPersistent)?"Persistant" : "NonPresistant",
1324 szDrive,szPath,pUsername?pUsername:"NULL",res);
1328 DWORD DisMountDOSDriveFull(const char *szPath,BOOL bForce)
1330 DWORD res=WNetCancelConnection(szPath,bForce);
1331 DEBUG_EVENT3("AFS DriveMap","%sDismount Remote[%s]=%x",
1332 bForce ? "Forced " : "",szPath,res);
1333 return (res==ERROR_NOT_CONNECTED)?NO_ERROR:res;
1336 DWORD DisMountDOSDrive(const char *pSubmount,BOOL bForce)
1338 TCHAR szPath[MAX_PATH];
1339 TCHAR szClient[MAX_PATH];
1340 GetClientNetbiosName (szClient);
1341 sprintf(szPath,"\\\\%s\\%s",szClient,pSubmount);
1342 return DisMountDOSDriveFull(szPath,bForce);
1346 DWORD DisMountDOSDrive(const char chDrive,BOOL bForce)
1348 TCHAR szPath[MAX_PATH];
1349 sprintf(szPath,"%c:",chDrive);
1350 return DisMountDOSDriveFull(szPath,bForce);