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
9 /* AFSIFS portions copyright (c) 2005
10 * the regents of the university of michigan
13 * permission is granted to use, copy, create derivative works and
14 * redistribute this software and such derivative works for any purpose,
15 * so long as no fee is charged, and so long as the copyright notice
16 * above, this grant of permission, and the disclaimer below appear
17 * in all copies made; and so long as the name of the university of
18 * michigan is not used in any advertising or publicity pertaining
19 * to the use or distribution of this software without specific, written
20 * prior authorization.
22 * this software is provided as is, without representation from the
23 * university of michigan as to its fitness for any purpose, and without
24 * warranty by the university of michigan of any kind, either express
25 * or implied, including without limitation the implied warranties of
26 * merchantability and fitness for a particular purpose. the regents
27 * of the university of michigan shall not be liable for nay damages,
28 * including special, indirect, incidental, or consequential damages,
29 * with respect to ant claim arising out of or in connection with the
30 * use of the software, even if it has been or is hereafter advised
31 * of the possibility of such damages.
38 #include <afs/param.h>
41 #include <afs/fs_utils.h>
46 #include <WINNT/TaLocale.h>
47 #include <WINNT/afsreg.h>
56 #include <lanahelper.h>
59 extern void Config_GetLanAdapter (ULONG *pnLanAdapter);
62 * REGISTRY ___________________________________________________________________
68 * PROFILE SECTIONS ___________________________________________________________
72 #define cREALLOC_SUBMOUNTS 4
74 static TCHAR cszSECTION_SUBMOUNTS[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Submounts");
75 static TCHAR cszSECTION_MAPPINGS[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Mappings");
76 static TCHAR cszSECTION_ACTIVE[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Active Maps");
78 static TCHAR cszAUTOSUBMOUNT[] = TEXT("Auto");
79 static TCHAR cszLANMANDEVICE[] = TEXT("\\Device\\LanmanRedirector\\");
83 WriteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
90 REG_OPTION_NON_VOLATILE,
96 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
101 return (status == ERROR_SUCCESS);
105 WriteExpandedRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
112 REG_OPTION_NON_VOLATILE,
118 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_EXPAND_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
121 RegCloseKey( hkSub );
123 return (status == ERROR_SUCCESS);
127 ReadRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs, DWORD * size)
134 REG_OPTION_NON_VOLATILE,
141 DWORD localSize = *size;
143 DWORD status = RegQueryValueEx( hkSub, lhs, 0, &dwType, (LPBYTE)rhs, &localSize);
144 if (status == 0 && dwType == REG_EXPAND_SZ) {
145 TCHAR * buf = (TCHAR *)malloc((*size) * sizeof(TCHAR));
146 memcpy(buf, rhs, (*size) * sizeof(TCHAR));
147 localSize = ExpandEnvironmentStrings(buf, rhs, *size);
149 if ( localSize > *size )
150 status = !ERROR_SUCCESS;
155 RegCloseKey( hkSub );
157 return (status == ERROR_SUCCESS);
161 DeleteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs)
168 REG_OPTION_NON_VOLATILE,
174 DWORD status = RegDeleteValue( hkSub, lhs );
177 RegCloseKey( hkSub );
179 return (status == ERROR_SUCCESS);
183 * STRINGS ____________________________________________________________________
187 static LPTSTR AllocateStringMemory (size_t cch)
189 LPTSTR psz = (LPTSTR)Allocate (sizeof(TCHAR) * (cch+1));
190 memset (psz, 0x00, sizeof(TCHAR) * (cch+1));
194 static void FreeStringMemory (LPTSTR pszString)
200 static int lstrncmpi (LPCTSTR pszA, LPCTSTR pszB, size_t cch)
204 return (!pszB) - (!pszA); // A,!B:1, !A,B:-1, !A,!B:0
207 for ( ; cch > 0; cch--, pszA = CharNext(pszA), pszB = CharNext(pszB))
209 TCHAR chA = toupper( *pszA );
210 TCHAR chB = toupper( *pszB );
213 return (!chB) - (!chA); // A,!B:1, !A,B:-1, !A,!B:0
216 return (int)(chA) - (int)(chB); // -1:A<B, 0:A==B, 1:A>B
219 return 0; // no differences before told to stop comparing, so A==B
224 * REALLOC ____________________________________________________________________
229 #define REALLOC(_a,_c,_r,_i) DriveMapReallocFunction ((LPVOID*)&_a,sizeof(*_a),&_c,_r,_i)
230 BOOL DriveMapReallocFunction (LPVOID *ppTarget, size_t cbElement, size_t *pcTarget, size_t cReq, size_t cInc)
235 if (cReq <= *pcTarget)
238 if ((cNew = cInc * ((cReq + cInc-1) / cInc)) <= 0)
241 if ((pNew = Allocate (cbElement * cNew)) == NULL)
243 memset (pNew, 0x00, cbElement * cNew);
247 memcpy (pNew, *ppTarget, cbElement * (*pcTarget));
259 * WINDOWS NT STUFF ___________________________________________________________
263 static BOOL IsWindowsNT (void)
265 static BOOL fChecked = FALSE;
266 static BOOL fIsWinNT = FALSE;
272 OSVERSIONINFO Version;
273 memset (&Version, 0x00, sizeof(Version));
274 Version.dwOSVersionInfoSize = sizeof(Version);
276 if (GetVersionEx (&Version))
278 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT)
286 /* Check if the OS is Windows 2000 or higher.
288 BOOL IsWindows2000 (void)
290 static BOOL fChecked = FALSE;
291 static BOOL fIsWin2K = FALSE;
297 OSVERSIONINFO Version;
298 memset (&Version, 0x00, sizeof(Version));
299 Version.dwOSVersionInfoSize = sizeof(Version);
301 if (GetVersionEx (&Version))
303 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
304 Version.dwMajorVersion >= 5)
313 * GENERAL ____________________________________________________________________
317 void GetClientNetbiosName (LPTSTR pszName)
319 static TCHAR szNetbiosName[32] = "";
321 if ( szNetbiosName[0] == 0 ) {
322 lana_GetNetbiosName(szNetbiosName, LANA_NETBIOS_NAME_FULL);
324 _tcscpy(pszName, szNetbiosName);
328 BOOL SubmountToPath (PDRIVEMAPLIST pList, LPTSTR pszPath, LPTSTR pszSubmount, BOOL fMarkInUse)
330 // We can't do this translation unless we're under Windows NT.
335 // \\computer-afs\all always maps to "/afs"
337 if (!lstrcmpi (pszSubmount, TEXT("all")))
339 lstrcpy (pszPath, cm_slash_mount_root);
343 // Otherwise, look up our list of submounts.
346 AdjustAfsPath (pszPath, pszSubmount, TRUE, TRUE);
348 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
352 b = !lstrcmpi (pList->aSubmounts[ii].szSubmount, pszSubmount);
354 b = !lstrcmpi (pList->aSubmounts[ii].szMapping, pszPath);
359 pList->aSubmounts[ii].fInUse = TRUE;
360 AdjustAfsPath (pszPath, pList->aSubmounts[ii].szMapping, TRUE, TRUE);
369 BOOL IsValidSubmountName (LPTSTR pszSubmount)
373 if (lstrlen (pszSubmount) > 12)
376 for ( ; *pszSubmount; ++pszSubmount)
378 if (!isprint(*pszSubmount))
380 if (*pszSubmount == TEXT(' '))
382 if (*pszSubmount == TEXT('/'))
384 if (*pszSubmount == TEXT('\\'))
386 if (*pszSubmount == TEXT('\t'))
395 * PIOCTL SUPPORT _____________________________________________________________
401 #include "../afsd/fs_utils.h"
403 #define __CM_CONFIG_INTERFACES_ONLY__
404 #include "../afsd/cm_config.h"
406 #define __CM_IOCTL_INTERFACES_ONLY__
407 #include "../afsd/cm_ioctl.h"
411 #define PIOCTL_MAXSIZE 2048
414 BOOL fCanIssuePIOCTL (void)
418 TCHAR szGateway[ 256 ] = TEXT("");
419 GetClientNetbiosName (szGateway);
420 return (szGateway[0]) ? TRUE : FALSE;
423 SERVICE_STATUS Status;
424 memset (&Status, 0x00, sizeof(Status));
425 Status.dwCurrentState = SERVICE_STOPPED;
428 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
431 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
433 QueryServiceStatus (hService, &Status);
434 CloseServiceHandle (hService);
437 CloseServiceHandle (hManager);
440 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
445 * QUERYDRIVEMAPLIST __________________________________________________________
449 void QueryDriveMapList_ReadSubmounts (PDRIVEMAPLIST pList)
455 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
456 cszSECTION_SUBMOUNTS,
459 REG_OPTION_NON_VOLATILE,
460 KEY_READ|KEY_QUERY_VALUE,
466 RegQueryInfoKey( hkSubmounts,
469 NULL, /* lpReserved */
470 NULL, /* lpcSubKeys */
471 NULL, /* lpcMaxSubKeyLen */
472 NULL, /* lpcMaxClassLen */
473 &dwSubmounts, /* lpcValues */
474 NULL, /* lpcMaxValueNameLen */
475 NULL, /* lpcMaxValueLen */
476 NULL, /* lpcbSecurityDescriptor */
477 NULL /* lpftLastWriteTime */
480 for ( DWORD dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
481 TCHAR submountPath[MAX_PATH] = "";
482 DWORD submountPathLen = MAX_PATH;
483 TCHAR submountName[MAX_PATH];
484 DWORD submountNameLen = MAX_PATH;
487 RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
488 &dwType, (LPBYTE)submountPath, &submountPathLen);
490 if (dwType == REG_EXPAND_SZ) {
492 StringCbCopyA(buf, MAX_PATH, submountPath);
493 submountPathLen = ExpandEnvironmentStrings(buf, submountPath, MAX_PATH);
494 if (submountPathLen > MAX_PATH)
499 memset (&Submount, 0x00, sizeof(SUBMOUNT));
500 lstrcpy (Submount.szSubmount, submountName);
502 if ( submountPath[0] != TEXT('\0') ) {
503 AdjustAfsPath (Submount.szMapping, submountPath, FALSE, TRUE);
506 for (ii = 0; ii < pList->cSubmounts; ++ii)
508 if (!pList->aSubmounts[ii].szSubmount[0])
511 if (REALLOC (pList->aSubmounts, pList->cSubmounts, 1+ii, cREALLOC_SUBMOUNTS))
513 memcpy (&pList->aSubmounts[ii], &Submount, sizeof(SUBMOUNT));
518 RegCloseKey(hkSubmounts);
523 void QueryDriveMapList_ReadMappings (PDRIVEMAPLIST pList)
526 RegCreateKeyEx( HKEY_CURRENT_USER,
530 REG_OPTION_NON_VOLATILE,
531 KEY_READ|KEY_QUERY_VALUE,
537 RegQueryInfoKey( hkMappings,
540 NULL, /* lpReserved */
541 NULL, /* lpcSubKeys */
542 NULL, /* lpcMaxSubKeyLen */
543 NULL, /* lpcMaxClassLen */
544 &dwMappings, /* lpcValues */
545 NULL, /* lpcMaxValueNameLen */
546 NULL, /* lpcMaxValueLen */
547 NULL, /* lpcbSecurityDescriptor */
548 NULL /* lpftLastWriteTime */
551 for ( DWORD dwIndex = 0; dwIndex < dwMappings; dwIndex ++ ) {
552 TCHAR mapping[MAX_PATH] = "";
553 DWORD mappingLen = MAX_PATH;
554 TCHAR drive[MAX_PATH];
555 DWORD driveLen = MAX_PATH;
558 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL,
559 &dwType, (LPBYTE)mapping, &mappingLen);
560 if ( dwType == REG_EXPAND_SZ ) {
562 DWORD dummyLen = ExpandEnvironmentStrings(mapping, buf, MAX_PATH);
563 if (dummyLen > MAX_PATH)
565 _tcsncpy(mapping, buf, MAX_PATH);
569 memset (&DriveMap, 0x00, sizeof(DRIVEMAP));
570 DriveMap.chDrive = toupper(*drive);
571 DriveMap.fPersistent = TRUE;
572 if ((DriveMap.chDrive < chDRIVE_A) || (DriveMap.chDrive > chDRIVE_Z))
575 if (mapping[0] != TEXT('\0'))
577 AdjustAfsPath (DriveMap.szMapping, mapping, TRUE, TRUE);
578 if (DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] == TEXT('*'))
580 DriveMap.fPersistent = FALSE;
581 DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] = TEXT('\0');
583 size_t iDrive = DriveMap.chDrive - chDRIVE_A;
584 memcpy (&pList->aDriveMap[ iDrive ], &DriveMap, sizeof(DRIVEMAP));
588 RegCloseKey(hkMappings);
591 BOOL ForceMapActive (TCHAR chDrive)
596 szDrive[0] = chDrive;
599 DWORD len = sizeof(szActive);
600 ReadRegistryString( HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, szActive, &len);
602 if ( !lstrcmp(szActive,"1") || !lstrcmpi(szActive,"true") || !lstrcmpi(szActive,"on") || !lstrcmpi(szActive,"yes") )
608 void WriteActiveMap (TCHAR chDrive, BOOL on)
612 szDrive[0] = chDrive;
615 WriteRegistryString(HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, on ? "1" : "0");
618 void QueryDriveMapList_WriteMappings (PDRIVEMAPLIST pList)
620 WriteDriveMappings (pList);
624 void WriteDriveMappings (PDRIVEMAPLIST pList)
627 RegCreateKeyEx( HKEY_CURRENT_USER,
631 REG_OPTION_NON_VOLATILE,
632 KEY_READ|KEY_QUERY_VALUE|KEY_WRITE,
638 RegQueryInfoKey( hkMappings,
641 NULL, /* lpReserved */
642 NULL, /* lpcSubKeys */
643 NULL, /* lpcMaxSubKeyLen */
644 NULL, /* lpcMaxClassLen */
645 &dwMappings, /* lpcValues */
646 NULL, /* lpcMaxValueNameLen */
647 NULL, /* lpcMaxValueLen */
648 NULL, /* lpcbSecurityDescriptor */
649 NULL /* lpftLastWriteTime */
652 if ( dwMappings > 0 ) {
653 for ( long dwIndex = dwMappings - 1; dwIndex >= 0; dwIndex-- ) {
654 TCHAR drive[MAX_PATH];
655 DWORD driveLen = MAX_PATH;
657 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL, NULL, NULL, NULL);
658 RegDeleteValue( hkMappings, drive );
662 for (size_t iDrive = 0; iDrive < 26; ++iDrive)
664 if (pList->aDriveMap[iDrive].szMapping[0] != TEXT('\0'))
666 TCHAR szLHS[] = TEXT("*");
667 szLHS[0] = pList->aDriveMap[iDrive].chDrive;
669 TCHAR szRHS[MAX_PATH];
670 AdjustAfsPath (szRHS, pList->aDriveMap[iDrive].szMapping, TRUE, TRUE);
671 if (!pList->aDriveMap[iDrive].fPersistent)
672 lstrcat (szRHS, TEXT("*"));
674 RegSetValueEx( hkMappings, szLHS, 0, REG_EXPAND_SZ, (const BYTE *)szRHS, lstrlen(szRHS) + 1);
677 RegCloseKey( hkMappings );
680 BOOL DriveIsGlobalAfsDrive(TCHAR chDrive)
682 TCHAR szKeyName[128];
683 TCHAR szValueName[128];
687 _stprintf(szKeyName, TEXT("%s\\GlobalAutoMapper"), AFSREG_CLT_SVC_PARAM_SUBKEY);
689 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
692 _stprintf(szValueName, TEXT("%c:"), chDrive);
694 DWORD dwSize = sizeof(szValue);
695 BOOL bIsGlobal = (RegQueryValueEx (hKey, szValueName, NULL, NULL, (PBYTE)szValue, &dwSize) == ERROR_SUCCESS);
703 void QueryDriveMapList_FindNetworkDrives (PDRIVEMAPLIST pList, BOOL *pfFoundNew)
705 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
707 TCHAR szSubmount[ MAX_PATH ];
708 if (!GetDriveSubmount (chDrive, szSubmount))
711 // We've got a mapping! Drive {chDrive} is mapped to submount
712 // {szSubmount}. See if that submount makes sense.
716 size_t iDrive = chDrive - chDRIVE_A;
717 if (pList->aDriveMap[ iDrive ].szMapping[0] != TEXT('\0'))
719 pList->aDriveMap[ iDrive ].fActive = TRUE;
720 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
724 else // (IsWindowsNT())
726 TCHAR szAfsPath[ MAX_PATH ];
727 if (!SubmountToPath (pList, szAfsPath, szSubmount, TRUE))
730 // Okay, we know that drive {chDrive} is mapped to afs path {szAfsPath}.
731 // If this drive is a global afs drive, then reject it. Otherwise, look
732 // at pList->aDriveMap, to see if this drive mapping is already in our
733 // list. If not, add it and set pfFoundNew.
735 if (DriveIsGlobalAfsDrive(chDrive))
738 size_t iDrive = chDrive - chDRIVE_A;
739 if (lstrcmpi (pList->aDriveMap[ iDrive ].szMapping, szAfsPath))
742 pList->aDriveMap[ iDrive ].fPersistent = TRUE;
744 pList->aDriveMap[ iDrive ].fActive = TRUE;
745 pList->aDriveMap[ iDrive ].chDrive = chDrive;
746 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
747 AdjustAfsPath (pList->aDriveMap[ iDrive ].szMapping, szAfsPath, TRUE, TRUE);
753 void QueryDriveMapList (PDRIVEMAPLIST pList)
755 // Initialize the data structure
757 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
758 for (size_t ii = 0; ii < 26; ++ii)
759 pList->aDriveMap[ii].chDrive = chDRIVE_A + ii;
761 // Read the current lists of submounts and drive letter mappings
763 QueryDriveMapList_ReadSubmounts (pList);
764 QueryDriveMapList_ReadMappings (pList);
766 // Look through the current list of network drives, and see if
767 // any are currently mapped to AFS. If we find any which are mapped
768 // into AFS unexpectedly, we'll have to rewrite the mappings list.
770 BOOL fFoundNew = FALSE;
771 QueryDriveMapList_FindNetworkDrives (pList, &fFoundNew);
775 QueryDriveMapList_WriteMappings (pList);
780 void FreeDriveMapList (PDRIVEMAPLIST pList)
782 if (pList->aSubmounts)
783 Free (pList->aSubmounts);
784 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
788 BOOL PathToSubmount (LPTSTR pszSubmount, LPTSTR pszMapping, LPTSTR pszSubmountReq, ULONG *pStatus)
790 if (pszSubmountReq && !IsValidSubmountName (pszSubmountReq))
791 pszSubmountReq = NULL;
793 TCHAR szAfsPath[ MAX_PATH ];
794 AdjustAfsPath (szAfsPath, pszMapping, TRUE, TRUE);
796 // Try to ask AFSD for a new submount name.
798 if (!fCanIssuePIOCTL())
801 BYTE InData[ PIOCTL_MAXSIZE ];
802 memset (InData, 0x00, sizeof(InData));
804 LPTSTR pszInData = (LPTSTR)InData;
805 lstrcpy (pszInData, pszMapping);
806 pszInData += 1+lstrlen(pszInData);
808 lstrcpy (pszInData, pszSubmountReq);
810 BYTE OutData[ PIOCTL_MAXSIZE ];
811 memset (OutData, 0x00, sizeof(OutData));
813 struct ViceIoctl IOInfo;
814 IOInfo.in = (char *)InData;
815 IOInfo.in_size = PIOCTL_MAXSIZE;
816 IOInfo.out = (char *)OutData;
817 IOInfo.out_size = PIOCTL_MAXSIZE;
819 ULONG status = pioctl (0, VIOC_MAKESUBMOUNT, &IOInfo, 1);
826 lstrcpy (pszSubmount, (LPCTSTR)OutData);
827 return (pszSubmount[0] != TEXT('\0')) ? TRUE : FALSE;
831 BOOL ActivateDriveMap (TCHAR chDrive, LPTSTR pszMapping, LPTSTR pszSubmountReq, BOOL fPersistent, DWORD *pdwStatus)
833 // We can only map drives to places in AFS using this function.
835 if ( (lstrncmpi (pszMapping, cm_slash_mount_root, lstrlen(cm_slash_mount_root))) &&
836 (lstrncmpi (pszMapping, cm_back_slash_mount_root, lstrlen(cm_back_slash_mount_root))) )
839 *pdwStatus = ERROR_BAD_NETPATH;
843 // First we have to translate {pszMapping} into a submount, and if there is
844 // no current submount associated with this path, we'll have to make one.
847 TCHAR szSubmount[ MAX_PATH ];
848 if (!PathToSubmount (szSubmount, pszMapping, pszSubmountReq, &status))
855 // We now have a submount name and drive letter--map the network drive.
858 rc=MountDOSDrive(chDrive,szSubmount,fPersistent,NULL);
860 rc=MountDOSDrive(chDrive,/*szSubmount*/pszMapping,fPersistent,NULL);
871 BOOL InactivateDriveMap (TCHAR chDrive, DWORD *pdwStatus)
873 DWORD rc = DisMountDOSDrive(chDrive, FALSE);
883 void AddSubMount (LPTSTR pszSubmount, LPTSTR pszMapping)
885 TCHAR szRHS[ MAX_PATH ];
886 AdjustAfsPath (szRHS, pszMapping, FALSE, TRUE);
888 lstrcpy (szRHS, TEXT("/"));
890 WriteExpandedRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount, szRHS);
894 void RemoveSubMount (LPTSTR pszSubmount)
896 DeleteRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount);
900 void AdjustAfsPath (LPTSTR pszTarget, LPCTSTR pszSource, BOOL fWantAFS, BOOL fWantForwardSlashes)
903 lstrcpy (pszTarget, (fWantAFS) ? cm_slash_mount_root : TEXT(""));
904 else if ((*pszSource != TEXT('/')) && (*pszSource != TEXT('\\')))
905 wsprintf (pszTarget, TEXT("%s/%s"),cm_slash_mount_root, pszSource);
906 // We don't want to strip afs off the start if it is part of something for example afscell.company.com
907 else if (fWantAFS && (lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root))) || !((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
908 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
909 (lstrlen(pszSource) == strlen(cm_slash_mount_root))))
910 wsprintf (pszTarget, TEXT("%s%s"),cm_slash_mount_root, pszSource);
911 else if (!fWantAFS && (!lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root)) && ((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
912 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
913 (lstrlen(pszSource) == strlen(cm_slash_mount_root)))))
914 lstrcpy (pszTarget, &pszSource[strlen(cm_slash_mount_root)]);
916 lstrcpy (pszTarget, pszSource);
918 for (LPTSTR pch = pszTarget; *pch; ++pch)
920 if (fWantForwardSlashes)
922 *pch = (*pch == TEXT('\\')) ? TEXT('/') : (*pch);
924 else // (!fWantForwardSlashes)
926 *pch = (*pch == TEXT('/')) ? TEXT('\\') : (*pch);
930 if (lstrlen(pszTarget) &&
931 ((pszTarget[lstrlen(pszTarget)-1] == TEXT('/')) ||
932 (pszTarget[lstrlen(pszTarget)-1] == TEXT('\\'))))
934 pszTarget[lstrlen(pszTarget)-1] = TEXT('\0');
938 BOOL GetDriveSubmount (TCHAR chDrive, LPTSTR pszSubmountNow)
940 BOOL isWinNT = IsWindowsNT();
942 TCHAR szDrive[] = TEXT("*:");
943 szDrive[0] = chDrive;
945 TCHAR szMapping[ _MAX_PATH ] = TEXT("");
947 if (isWinNT && !QueryDosDevice (szDrive, szMapping, MAX_PATH))
950 LPTSTR pszSubmount = szMapping;
952 TCHAR szNetBiosName[32];
953 memset(szNetBiosName, '\0', sizeof(szNetBiosName));
954 GetClientNetbiosName(szNetBiosName);
955 _tcscat(szNetBiosName, TEXT("\\"));
959 // Now if this is an AFS network drive mapping, {szMapping} will be:
961 // \Device\LanmanRedirector\<Drive>:\<netbiosname>\submount
963 // on Windows NT. On Windows 2000, it will be:
965 // \Device\LanmanRedirector\;<Drive>:0\<netbiosname>\submount
967 // (This is presumably to support multiple drive mappings with
970 // on Windows XP and 2003, it will be :
971 // \Device\LanmanRedirector\;<Drive>:<AuthID>\<netbiosname>\submount
973 // where : <Drive> : DOS drive letter
974 // <AuthID>: Authentication ID, 16 char hex.
975 // <netbiosname>: Netbios name of server
979 b = _tcsnicmp(szMapping, cszLANMANDEVICE, _tcslen(cszLANMANDEVICE));
981 const TCHAR ker_sub_path[] = "\\Device\\afsrdr\\";
982 b = _tcsnicmp(szMapping, ker_sub_path, _tcslen(ker_sub_path));
987 pszSubmount = &szMapping[ _tcslen(cszLANMANDEVICE) ];
989 pszSubmount = &szMapping[ _tcslen(ker_sub_path) ];
993 if (*(pszSubmount) < '0' ||
994 *(pszSubmount) > '9')
1000 if (*(pszSubmount) != TEXT(';'))
1005 if (toupper(*(++pszSubmount)) != chDrive)
1008 if (*(++pszSubmount) != TEXT(':'))
1012 // No longer a safe assumption on XP
1013 if (IsWindows2000())
1014 if (*(++pszSubmount) != TEXT('0'))
1018 // scan for next "\"
1019 while (*(++pszSubmount) != TEXT('\\'))
1021 if (*pszSubmount==0)
1025 // note that szNetBiosName has a '\\' tagged in the end earlier
1026 for (++pszSubmount; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1027 if (!_tcsncicmp(pszSubmount, szNetBiosName, _tcslen(szNetBiosName)))
1029 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1032 pszSubmount += _tcslen(szNetBiosName);
1035 else // (!IsWindowsNT())
1037 DWORD dwSize = MAX_PATH;
1038 if (WNetGetConnection (szDrive, szMapping, &dwSize) != NO_ERROR)
1040 if (*(pszSubmount++) != TEXT('\\'))
1042 if (*(pszSubmount++) != TEXT('\\'))
1044 for ( ; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1045 if (!lstrncmpi (pszSubmount, szNetBiosName, lstrlen(szNetBiosName)))
1047 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1049 pszSubmount += lstrlen(szNetBiosName);
1052 if (!pszSubmount || !*pszSubmount)
1056 lstrcpy (pszSubmountNow, pszSubmount);
1058 lstrcpy (pszSubmountNow, "\\afs");
1059 lstrcat (pszSubmountNow, pszSubmount);
1064 /* Generate Random User name random acording to time*/
1066 TCHAR pUserName[MAXRANDOMNAMELEN]=TEXT("");
1067 BOOL fUserName=FALSE;
1068 #define AFSLogonOptionName TEXT(AFSREG_CLT_SVC_PROVIDER_SUBKEY)
1070 void SetBitLogonOption(BOOL set,DWORD value)
1073 RWLogonOption(FALSE,((set)?value | RWLogonOption(TRUE,0):RWLogonOption(TRUE,0) & ~value) );
1076 DWORD RWLogonOption(BOOL read,DWORD value)
1078 // if read is true then if value==0 return registry value
1079 // if read and value!=0 then use value to test registry, return TRUE if value bits match value read
1082 DWORD LSPtype, LSPsize;
1088 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, KEY_QUERY_VALUE, &hk)==ERROR_SUCCESS)
1090 LSPsize=sizeof(rval);
1091 RegQueryValueEx(hk, "LogonOptions", NULL,
1092 &LSPtype, (LPBYTE)&rval, &LSPsize);
1095 return (value==0)?rval:((rval & value)==value);
1097 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, NULL, 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
1099 RegSetValueEx(hk,TEXT("LogonOptions"),NULL,REG_DWORD,(LPBYTE)&value,sizeof(value));
1106 void MapShareName(char *pszCmdLineA)
1111 while (*pszCmdLineA && (*pszCmdLineA != ' '))
1113 *p++=*pszCmdLineA++;
1117 void GenRandomName(TCHAR *pname,int len)
1120 { //user name was passed through command line, use once
1124 srand( (unsigned)time( NULL ) );
1125 for (int i=0;i<len;i++)
1126 pname[i]='a'+(rand() % 26);
1132 Make a connection using users name
1133 if fUserName then force a connection
1136 BOOL TestAndDoMapShare(DWORD dwState)
1138 if ((dwState!=SERVICE_RUNNING) || (dwOldState!=SERVICE_START_PENDING))
1143 dwOldState=SERVICE_RUNNING;
1144 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1145 return (DoMapShare() && GlobalMountDrive());
1146 return GlobalMountDrive();
1149 BOOL IsServiceActive()
1152 SERVICE_STATUS Status;
1153 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
1156 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
1158 QueryServiceStatus (hService, &Status);
1159 CloseServiceHandle (hService);
1162 CloseServiceHandle (hManager);
1165 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
1168 void TestAndDoUnMapShare()
1170 if (!RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1172 DoUnMapShare(FALSE);
1175 void DoUnMapShare(BOOL drivemap) //disconnect drivemap
1177 TCHAR szMachine[MAX_PATH],szPath[MAX_PATH];
1180 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1182 DWORD cbBuffer=16384;
1186 memset(szMachine, '\0', sizeof(szMachine));
1187 GetClientNetbiosName(szMachine);
1189 // Initialize the data structure
1190 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1192 sprintf(szPath,"\\\\%s\\",szMachine);
1194 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1196 memset(lpnrLocal,0,cbBuffer);
1197 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1199 for (DWORD i=0;i<cEntries;i++)
1201 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath))
1203 if ((lpnrLocal[i].lpLocalName) && (strlen(lpnrLocal[i].lpLocalName)>0))
1206 DisMountDOSDrive(*lpnrLocal[i].lpLocalName);
1207 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Local=%x",res);
1210 DisMountDOSDriveFull(lpnrLocal[i].lpRemoteName);
1211 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Remote=%x",res);
1216 } while (res!=ERROR_NO_MORE_ITEMS);
1217 GlobalFree((HGLOBAL)lpnrLocal);
1218 WNetCloseEnum(hEnum);
1221 BOOL DoMapShareChange(BOOL removeUnknown)
1224 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1227 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1230 DWORD cbBuffer=16384;
1232 memset(szMachine, '\0', sizeof(szMachine));
1233 GetClientNetbiosName(szMachine);
1235 // Initialize the data structure
1236 if (!IsServiceActive())
1238 memset (&List, 0x00, sizeof(DRIVEMAPLIST));
1239 for (size_t ii = 0; ii < 26; ++ii)
1240 List.aDriveMap[ii].chDrive = chDRIVE_A + ii;
1241 QueryDriveMapList_ReadSubmounts (&List);
1242 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1244 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1245 sprintf(szPath,"\\\\%s\\",szMachine);
1248 memset(lpnrLocal,0,cbBuffer);
1249 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1251 for (DWORD i=0;i<cEntries;i++)
1253 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)==NULL)
1254 continue; //only look at real afs mappings
1255 CHAR * pSubmount=strrchr(lpnrLocal[i].lpRemoteName,'\\')+1;
1256 if (lstrcmpi(pSubmount,"all")==0)
1257 continue; // do not remove 'all'
1258 for (DWORD j=0;j<List.cSubmounts;j++)
1260 if ((List.aSubmounts[j].szSubmount[0]) &&
1261 (lstrcmpi(List.aSubmounts[j].szSubmount,pSubmount)==0)
1264 List.aSubmounts[j].fInUse=TRUE;
1268 // wasn't on list so lets remove
1269 DisMountDOSDrive(pSubmount);
1273 } while (res!=ERROR_NO_MORE_ITEMS);
1274 GlobalFree((HGLOBAL)lpnrLocal);
1275 WNetCloseEnum(hEnum);
1276 sprintf(szPath,"\\\\%s\\all",szMachine);
1278 // Lets connect all submounts that weren't connectd
1279 DWORD cbUser=MAXRANDOMNAMELEN-1;
1280 CHAR szUser[MAXRANDOMNAMELEN];
1281 CHAR * pUser = NULL;
1282 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1283 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1284 if (!pUserName[0]) {
1285 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1292 if ((pUser=strchr(szUser,'\\'))!=NULL)
1296 for (DWORD j=0;j<List.cSubmounts;j++)
1298 if (List.aSubmounts[j].fInUse)
1300 DWORD res=MountDOSDrive(0,List.aSubmounts[j].szSubmount,FALSE,pUser);
1309 BOOL bMappedAll=FALSE;
1311 // Initialize the data structure
1312 DEBUG_EVENT0("AFS DoMapShare");
1313 QueryDriveMapList (&List);
1315 // All connections have been removed
1316 // Lets restore them after making the connection from the random name
1318 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1319 memset(szMachine, '\0', sizeof(szMachine));
1320 GetClientNetbiosName(szMachine);
1321 sprintf(szPath,"\\\\%s\\all",szMachine);
1323 // Lets connect all submounts that weren't connectd
1324 DWORD cbUser=MAXRANDOMNAMELEN-1;
1325 CHAR szUser[MAXRANDOMNAMELEN];
1326 CHAR * pUser = NULL;
1327 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1328 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1329 if (!pUserName[0]) {
1330 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1337 if ((pUser=strchr(szUser,'\\'))!=NULL)
1341 for (DWORD i=0;i<List.cSubmounts;i++)
1343 if (List.aSubmounts[i].szSubmount[0])
1345 DWORD res=MountDOSDrive(0,List.aSubmounts[i].szSubmount,FALSE,pUser);
1346 if (lstrcmpi("all",List.aSubmounts[i].szSubmount)==0)
1350 if (!bMappedAll) //make sure all is mapped also
1352 DWORD res=MountDOSDrive(0,"all",FALSE,pUser);
1353 if (res==ERROR_SESSION_CREDENTIAL_CONFLICT)
1355 DisMountDOSDrive("all");
1356 MountDOSDrive(0,"all",FALSE,pUser);
1359 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
1361 if (List.aDriveMap[chDrive-chDRIVE_A].fActive ||
1362 ForceMapActive(chDrive))
1364 TCHAR szSubmount[ MAX_PATH ];
1365 if (List.aDriveMap[chDrive-chDRIVE_A].szSubmount[0])
1366 lstrcpy(szSubmount,List.aDriveMap[chDrive-chDRIVE_A].szSubmount);
1367 else if (!PathToSubmount (szSubmount, List.aDriveMap[chDrive-chDRIVE_A].szMapping, NULL, NULL))
1370 BOOL fPersistent = List.aDriveMap[chDrive-chDRIVE_A].fPersistent;
1371 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1372 fPersistent = FALSE;
1373 DWORD res=MountDOSDrive(chDrive
1375 ,fPersistent,pUser);
1381 BOOL GlobalMountDrive()
1383 char szDriveToMapTo[5];
1385 char szKeyName[256];
1389 DWORD dwSubMountSize;
1390 char unsigned szSubMount[256];
1391 char cm_HostName[200];
1392 DWORD dwType=sizeof(cm_HostName);
1393 if (!IsServiceActive())
1395 if (!GetComputerName(cm_HostName, &dwType))
1397 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSREG_CLT_SVC_PARAM_SUBKEY);
1399 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE,
1401 if (dwResult != ERROR_SUCCESS)
1405 dwDriveSize = sizeof(szDriveToMapTo);
1406 dwSubMountSize = sizeof(szSubMount);
1407 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize,
1408 0, &dwType, szSubMount, &dwSubMountSize);
1409 if (dwResult != ERROR_MORE_DATA) {
1410 if (dwResult != ERROR_SUCCESS) {
1411 if (dwResult != ERROR_NO_MORE_ITEMS)
1413 DEBUG_EVENT1("AFS DriveMap","Failed to read GlobalAutoMapper values: %d",dwResult);
1418 dwResult=MountDOSDrive(*szDriveToMapTo,(const char *)szSubMount,FALSE,NULL);
1424 DWORD MountDOSDrive(char chDrive,const char *szSubmount,BOOL bPersistent,const char * pUsername)
1428 TCHAR szPath[MAX_PATH], szTokens[MAX_PATH], *tok;
1429 TCHAR szClient[MAX_PATH];
1430 TCHAR szDrive[3] = TEXT("?:");
1433 int pathCount, currPos, lastPos, x;
1438 strcpy(szTokens, szSubmount);
1439 tok = strtok(szTokens, "/\\");
1443 if (pathCount || stricmp(tok, "afs"))
1445 strcat(szPath, "\\");
1446 strcat(szPath, tok);
1449 tok = strtok(NULL, "/\\");
1452 sprintf(szDrive,"%c:",chDrive);
1453 strcpy(szTokens, szPath);
1454 sprintf(szPath,"\\Device\\afsrdr\\%d%s",pathCount,szTokens);
1455 //succ = DefineDosDevice(DDD_RAW_TARGET_PATH, "J:", "\\Device\\afsrdr\\2\\ericjw\\test");
1456 succ = DefineDosDevice(DDD_RAW_TARGET_PATH, szDrive, szPath);
1457 err = GetLastError();
1459 return succ ? NO_ERROR : ERROR_DEVICE_IN_USE;
1461 sprintf(szDrive,"%c:",chDrive);
1462 GetClientNetbiosName (szClient);
1463 sprintf(szPath,"\\\\%s\\%s",szClient,szSubmount);
1465 memset (&nr, 0x00, sizeof(NETRESOURCE));
1466 nr.dwType=RESOURCETYPE_DISK;
1467 nr.lpLocalName=szDrive;
1468 nr.lpRemoteName=szPath;
1469 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
1470 DWORD res=WNetAddConnection2(&nr,NULL,pUsername,(bPersistent)?CONNECT_UPDATE_PROFILE:0);
1471 DEBUG_EVENT5("AFS DriveMap","Mount %s Local[%s] Remote[%s] User[%s]=%x",
1472 (bPersistent)?"Persistant" : "NonPresistant",
1473 szDrive,szPath,pUsername?pUsername:"NULL",res);
1478 DWORD DisMountDOSDriveFull(const char *szPath,BOOL bForce)
1481 DWORD res=WNetCancelConnection(szPath,bForce);
1484 res = ERROR_DEVICE_IN_USE;
1485 // must handle drive letters and afs paths
1486 // DDD_REMOVE_DEFINITION
1488 DEBUG_EVENT3("AFS DriveMap","%sDismount Remote[%s]=%x",
1489 bForce ? "Forced " : "",szPath,res);
1490 return (res==ERROR_NOT_CONNECTED)?NO_ERROR:res;
1493 DWORD DisMountDOSDrive(const char *pSubmount,BOOL bForce)
1495 TCHAR szPath[MAX_PATH];
1496 TCHAR szClient[MAX_PATH];
1497 GetClientNetbiosName (szClient);
1498 sprintf(szPath,"\\\\%s\\%s",szClient,pSubmount);
1499 return DisMountDOSDriveFull(szPath,bForce);
1503 DWORD DisMountDOSDrive(const char chDrive,BOOL bForce)
1505 TCHAR szPath[MAX_PATH];
1508 sprintf(szPath,"%c:",chDrive);
1510 succ = DefineDosDevice(DDD_REMOVE_DEFINITION, szPath, NULL);
1511 return (!succ) ? GetLastError() : 0;
1513 return DisMountDOSDriveFull(szPath,bForce);