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.
35 #include <afs/param.h>
38 #include <afs/fs_utils.h>
43 #include <WINNT/TaLocale.h>
44 #include <WINNT/afsreg.h>
53 #include <lanahelper.h>
56 extern void Config_GetLanAdapter (ULONG *pnLanAdapter);
59 * REGISTRY ___________________________________________________________________
65 * PROFILE SECTIONS ___________________________________________________________
69 #define cREALLOC_SUBMOUNTS 4
71 static TCHAR cszSECTION_SUBMOUNTS[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Submounts");
72 static TCHAR cszSECTION_MAPPINGS[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Mappings");
73 static TCHAR cszSECTION_ACTIVE[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Active Maps");
75 static TCHAR cszAUTOSUBMOUNT[] = TEXT("Auto");
76 static TCHAR cszLANMANDEVICE[] = TEXT("\\Device\\LanmanRedirector\\");
80 WriteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
87 REG_OPTION_NON_VOLATILE,
93 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
98 return (status == ERROR_SUCCESS);
102 WriteExpandedRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
109 REG_OPTION_NON_VOLATILE,
115 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_EXPAND_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
118 RegCloseKey( hkSub );
120 return (status == ERROR_SUCCESS);
124 ReadRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs, DWORD * size)
131 REG_OPTION_NON_VOLATILE,
138 DWORD localSize = *size;
140 DWORD status = RegQueryValueEx( hkSub, lhs, 0, &dwType, (LPBYTE)rhs, &localSize);
141 if (status == 0 && dwType == REG_EXPAND_SZ) {
142 TCHAR * buf = (TCHAR *)malloc((*size) * sizeof(TCHAR));
143 memcpy(buf, rhs, (*size) * sizeof(TCHAR));
144 localSize = ExpandEnvironmentStrings(buf, rhs, *size);
146 if ( localSize > *size )
147 status = !ERROR_SUCCESS;
152 RegCloseKey( hkSub );
154 return (status == ERROR_SUCCESS);
158 DeleteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs)
165 REG_OPTION_NON_VOLATILE,
171 DWORD status = RegDeleteValue( hkSub, lhs );
174 RegCloseKey( hkSub );
176 return (status == ERROR_SUCCESS);
180 * STRINGS ____________________________________________________________________
184 static LPTSTR AllocateStringMemory (size_t cch)
186 LPTSTR psz = (LPTSTR)Allocate (sizeof(TCHAR) * (cch+1));
187 memset (psz, 0x00, sizeof(TCHAR) * (cch+1));
191 static void FreeStringMemory (LPTSTR pszString)
196 static int lstrncmpi (LPCTSTR pszA, LPCTSTR pszB, size_t cch)
200 return (!pszB) - (!pszA); // A,!B:1, !A,B:-1, !A,!B:0
203 for ( ; cch > 0; cch--, pszA = CharNext(pszA), pszB = CharNext(pszB))
205 TCHAR chA = toupper( *pszA );
206 TCHAR chB = toupper( *pszB );
209 return (!chB) - (!chA); // A,!B:1, !A,B:-1, !A,!B:0
212 return (int)(chA) - (int)(chB); // -1:A<B, 0:A==B, 1:A>B
215 return 0; // no differences before told to stop comparing, so A==B
220 * REALLOC ____________________________________________________________________
225 #define REALLOC(_a,_c,_r,_i) DriveMapReallocFunction ((LPVOID*)&_a,sizeof(*_a),&_c,_r,_i)
226 BOOL DriveMapReallocFunction (LPVOID *ppTarget, size_t cbElement, size_t *pcTarget, size_t cReq, size_t cInc)
231 if (cReq <= *pcTarget)
234 if ((cNew = cInc * ((cReq + cInc-1) / cInc)) <= 0)
237 if ((pNew = Allocate (cbElement * cNew)) == NULL)
239 memset (pNew, 0x00, cbElement * cNew);
243 memcpy (pNew, *ppTarget, cbElement * (*pcTarget));
255 * WINDOWS NT STUFF ___________________________________________________________
259 static BOOL IsWindowsNT (void)
261 static BOOL fChecked = FALSE;
262 static BOOL fIsWinNT = FALSE;
268 OSVERSIONINFO Version;
269 memset (&Version, 0x00, sizeof(Version));
270 Version.dwOSVersionInfoSize = sizeof(Version);
272 if (GetVersionEx (&Version))
274 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT)
282 /* Check if the OS is Windows 2000 or higher.
284 BOOL IsWindows2000 (void)
286 static BOOL fChecked = FALSE;
287 static BOOL fIsWin2K = FALSE;
293 OSVERSIONINFO Version;
294 memset (&Version, 0x00, sizeof(Version));
295 Version.dwOSVersionInfoSize = sizeof(Version);
297 if (GetVersionEx (&Version))
299 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
300 Version.dwMajorVersion >= 5)
309 * GENERAL ____________________________________________________________________
313 void GetClientNetbiosName (LPTSTR pszName)
315 static TCHAR szNetbiosName[32] = "";
317 if ( szNetbiosName[0] == 0 ) {
318 lana_GetNetbiosName(szNetbiosName, LANA_NETBIOS_NAME_FULL);
320 _tcscpy(pszName, szNetbiosName);
324 BOOL SubmountToPath (PDRIVEMAPLIST pList, LPTSTR pszPath, LPTSTR pszSubmount, BOOL fMarkInUse)
326 // We can't do this translation unless we're under Windows NT.
331 // \\computer-afs\all always maps to "/afs"
333 if (!lstrcmpi (pszSubmount, TEXT("all")))
335 lstrcpy (pszPath, cm_slash_mount_root);
339 // Otherwise, look up our list of submounts.
342 AdjustAfsPath (pszPath, pszSubmount, TRUE, TRUE);
344 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
348 b = !lstrcmpi (pList->aSubmounts[ii].szSubmount, pszSubmount);
350 b = !lstrcmpi (pList->aSubmounts[ii].szMapping, pszPath);
355 pList->aSubmounts[ii].fInUse = TRUE;
356 AdjustAfsPath (pszPath, pList->aSubmounts[ii].szMapping, TRUE, TRUE);
365 BOOL IsValidSubmountName (LPTSTR pszSubmount)
369 if (lstrlen (pszSubmount) > 12)
372 for ( ; *pszSubmount; ++pszSubmount)
374 if (!isprint(*pszSubmount))
376 if (*pszSubmount == TEXT(' '))
378 if (*pszSubmount == TEXT('/'))
380 if (*pszSubmount == TEXT('\\'))
382 if (*pszSubmount == TEXT('\t'))
391 * PIOCTL SUPPORT _____________________________________________________________
397 #include "../afsd/fs_utils.h"
399 #define __CM_CONFIG_INTERFACES_ONLY__
400 #include "../afsd/cm_config.h"
402 #define __CM_IOCTL_INTERFACES_ONLY__
403 #include "../afsd/cm_ioctl.h"
407 #define PIOCTL_MAXSIZE 2048
410 BOOL fCanIssuePIOCTL (void)
414 TCHAR szGateway[ 256 ] = TEXT("");
415 GetClientNetbiosName (szGateway);
416 return (szGateway[0]) ? TRUE : FALSE;
419 SERVICE_STATUS Status;
420 memset (&Status, 0x00, sizeof(Status));
421 Status.dwCurrentState = SERVICE_STOPPED;
424 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
427 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
429 QueryServiceStatus (hService, &Status);
430 CloseServiceHandle (hService);
433 CloseServiceHandle (hManager);
436 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
441 * QUERYDRIVEMAPLIST __________________________________________________________
445 void QueryDriveMapList_ReadSubmounts (PDRIVEMAPLIST pList)
451 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
452 cszSECTION_SUBMOUNTS,
455 REG_OPTION_NON_VOLATILE,
456 KEY_READ|KEY_QUERY_VALUE,
462 RegQueryInfoKey( hkSubmounts,
465 NULL, /* lpReserved */
466 NULL, /* lpcSubKeys */
467 NULL, /* lpcMaxSubKeyLen */
468 NULL, /* lpcMaxClassLen */
469 &dwSubmounts, /* lpcValues */
470 NULL, /* lpcMaxValueNameLen */
471 NULL, /* lpcMaxValueLen */
472 NULL, /* lpcbSecurityDescriptor */
473 NULL /* lpftLastWriteTime */
476 for ( DWORD dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
477 TCHAR submountPath[MAX_PATH] = "";
478 DWORD submountPathLen = MAX_PATH;
479 TCHAR submountName[MAX_PATH];
480 DWORD submountNameLen = MAX_PATH;
483 RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
484 &dwType, (LPBYTE)submountPath, &submountPathLen);
486 if (dwType == REG_EXPAND_SZ) {
488 StringCbCopyA(buf, MAX_PATH, submountPath);
489 submountPathLen = ExpandEnvironmentStrings(buf, submountPath, MAX_PATH);
490 if (submountPathLen > MAX_PATH)
495 memset (&Submount, 0x00, sizeof(SUBMOUNT));
496 lstrcpy (Submount.szSubmount, submountName);
498 if ( submountPath[0] != TEXT('\0') ) {
499 AdjustAfsPath (Submount.szMapping, submountPath, FALSE, TRUE);
501 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
503 if (!pList->aSubmounts[ii].szSubmount[0])
506 if (REALLOC (pList->aSubmounts, pList->cSubmounts, 1+ii, cREALLOC_SUBMOUNTS))
508 memcpy (&pList->aSubmounts[ii], &Submount, sizeof(SUBMOUNT));
513 RegCloseKey(hkSubmounts);
518 void QueryDriveMapList_ReadMappings (PDRIVEMAPLIST pList)
521 RegCreateKeyEx( HKEY_CURRENT_USER,
525 REG_OPTION_NON_VOLATILE,
526 KEY_READ|KEY_QUERY_VALUE,
532 RegQueryInfoKey( hkMappings,
535 NULL, /* lpReserved */
536 NULL, /* lpcSubKeys */
537 NULL, /* lpcMaxSubKeyLen */
538 NULL, /* lpcMaxClassLen */
539 &dwMappings, /* lpcValues */
540 NULL, /* lpcMaxValueNameLen */
541 NULL, /* lpcMaxValueLen */
542 NULL, /* lpcbSecurityDescriptor */
543 NULL /* lpftLastWriteTime */
546 for ( DWORD dwIndex = 0; dwIndex < dwMappings; dwIndex ++ ) {
547 TCHAR mapping[MAX_PATH] = "";
548 DWORD mappingLen = MAX_PATH;
549 TCHAR drive[MAX_PATH];
550 DWORD driveLen = MAX_PATH;
553 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL,
554 &dwType, (LPBYTE)mapping, &mappingLen);
555 if ( dwType == REG_EXPAND_SZ ) {
557 DWORD dummyLen = ExpandEnvironmentStrings(mapping, buf, MAX_PATH);
558 if (dummyLen > MAX_PATH)
560 _tcsncpy(mapping, buf, MAX_PATH);
564 memset (&DriveMap, 0x00, sizeof(DRIVEMAP));
565 DriveMap.chDrive = toupper(*drive);
566 DriveMap.fPersistent = TRUE;
567 if ((DriveMap.chDrive < chDRIVE_A) || (DriveMap.chDrive > chDRIVE_Z))
570 if (mapping[0] != TEXT('\0'))
572 AdjustAfsPath (DriveMap.szMapping, mapping, TRUE, TRUE);
573 if (DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] == TEXT('*'))
575 DriveMap.fPersistent = FALSE;
576 DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] = TEXT('\0');
578 size_t iDrive = DriveMap.chDrive - chDRIVE_A;
579 memcpy (&pList->aDriveMap[ iDrive ], &DriveMap, sizeof(DRIVEMAP));
583 RegCloseKey(hkMappings);
586 BOOL ForceMapActive (TCHAR chDrive)
591 szDrive[0] = chDrive;
594 DWORD len = sizeof(szActive);
595 ReadRegistryString( HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, szActive, &len);
597 if ( !lstrcmp(szActive,"1") || !lstrcmpi(szActive,"true") || !lstrcmpi(szActive,"on") || !lstrcmpi(szActive,"yes") )
603 void WriteActiveMap (TCHAR chDrive, BOOL on)
607 szDrive[0] = chDrive;
610 WriteRegistryString(HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, on ? "1" : "0");
613 void QueryDriveMapList_WriteMappings (PDRIVEMAPLIST pList)
615 WriteDriveMappings (pList);
619 void WriteDriveMappings (PDRIVEMAPLIST pList)
622 RegCreateKeyEx( HKEY_CURRENT_USER,
626 REG_OPTION_NON_VOLATILE,
627 KEY_READ|KEY_QUERY_VALUE|KEY_WRITE,
633 RegQueryInfoKey( hkMappings,
636 NULL, /* lpReserved */
637 NULL, /* lpcSubKeys */
638 NULL, /* lpcMaxSubKeyLen */
639 NULL, /* lpcMaxClassLen */
640 &dwMappings, /* lpcValues */
641 NULL, /* lpcMaxValueNameLen */
642 NULL, /* lpcMaxValueLen */
643 NULL, /* lpcbSecurityDescriptor */
644 NULL /* lpftLastWriteTime */
647 if ( dwMappings > 0 ) {
648 for ( long dwIndex = dwMappings - 1; dwIndex >= 0; dwIndex-- ) {
649 TCHAR drive[MAX_PATH];
650 DWORD driveLen = MAX_PATH;
652 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL, NULL, NULL, NULL);
653 RegDeleteValue( hkMappings, drive );
657 for (size_t iDrive = 0; iDrive < 26; ++iDrive)
659 if (pList->aDriveMap[iDrive].szMapping[0] != TEXT('\0'))
661 TCHAR szLHS[] = TEXT("*");
662 szLHS[0] = pList->aDriveMap[iDrive].chDrive;
664 TCHAR szRHS[MAX_PATH];
665 AdjustAfsPath (szRHS, pList->aDriveMap[iDrive].szMapping, TRUE, TRUE);
666 if (!pList->aDriveMap[iDrive].fPersistent)
667 lstrcat (szRHS, TEXT("*"));
669 RegSetValueEx( hkMappings, szLHS, 0, REG_EXPAND_SZ, (const BYTE *)szRHS, lstrlen(szRHS) + 1);
672 RegCloseKey( hkMappings );
675 BOOL DriveIsGlobalAfsDrive(TCHAR chDrive)
677 TCHAR szKeyName[128];
678 TCHAR szValueName[128];
682 _stprintf(szKeyName, TEXT("%s\\GlobalAutoMapper"), AFSREG_CLT_SVC_PARAM_SUBKEY);
684 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
687 _stprintf(szValueName, TEXT("%c:"), chDrive);
689 DWORD dwSize = sizeof(szValue);
690 BOOL bIsGlobal = (RegQueryValueEx (hKey, szValueName, NULL, NULL, (PBYTE)szValue, &dwSize) == ERROR_SUCCESS);
698 void QueryDriveMapList_FindNetworkDrives (PDRIVEMAPLIST pList, BOOL *pfFoundNew)
700 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
702 TCHAR szSubmount[ MAX_PATH ];
703 if (!GetDriveSubmount (chDrive, szSubmount))
706 // We've got a mapping! Drive {chDrive} is mapped to submount
707 // {szSubmount}. See if that submount makes sense.
711 size_t iDrive = chDrive - chDRIVE_A;
712 if (pList->aDriveMap[ iDrive ].szMapping[0] != TEXT('\0'))
714 pList->aDriveMap[ iDrive ].fActive = TRUE;
715 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
719 else // (IsWindowsNT())
721 TCHAR szAfsPath[ MAX_PATH ];
722 if (!SubmountToPath (pList, szAfsPath, szSubmount, TRUE))
725 // Okay, we know that drive {chDrive} is mapped to afs path {szAfsPath}.
726 // If this drive is a global afs drive, then reject it. Otherwise, look
727 // at pList->aDriveMap, to see if this drive mapping is already in our
728 // list. If not, add it and set pfFoundNew.
730 if (DriveIsGlobalAfsDrive(chDrive))
733 size_t iDrive = chDrive - chDRIVE_A;
734 if (lstrcmpi (pList->aDriveMap[ iDrive ].szMapping, szAfsPath))
737 pList->aDriveMap[ iDrive ].fPersistent = TRUE;
739 pList->aDriveMap[ iDrive ].fActive = TRUE;
740 pList->aDriveMap[ iDrive ].chDrive = chDrive;
741 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
742 AdjustAfsPath (pList->aDriveMap[ iDrive ].szMapping, szAfsPath, TRUE, TRUE);
748 void QueryDriveMapList (PDRIVEMAPLIST pList)
750 // Initialize the data structure
752 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
753 for (size_t ii = 0; ii < 26; ++ii)
754 pList->aDriveMap[ii].chDrive = chDRIVE_A + ii;
756 // Read the current lists of submounts and drive letter mappings
758 QueryDriveMapList_ReadSubmounts (pList);
759 QueryDriveMapList_ReadMappings (pList);
761 // Look through the current list of network drives, and see if
762 // any are currently mapped to AFS. If we find any which are mapped
763 // into AFS unexpectedly, we'll have to rewrite the mappings list.
765 BOOL fFoundNew = FALSE;
766 QueryDriveMapList_FindNetworkDrives (pList, &fFoundNew);
770 QueryDriveMapList_WriteMappings (pList);
775 void FreeDriveMapList (PDRIVEMAPLIST pList)
777 if (pList->aSubmounts)
778 Free (pList->aSubmounts);
779 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
783 BOOL PathToSubmount (LPTSTR pszSubmount, LPTSTR pszMapping, LPTSTR pszSubmountReq, ULONG *pStatus)
785 if (pszSubmountReq && !IsValidSubmountName (pszSubmountReq))
786 pszSubmountReq = NULL;
788 TCHAR szAfsPath[ MAX_PATH ];
789 AdjustAfsPath (szAfsPath, pszMapping, TRUE, TRUE);
791 // Try to ask AFSD for a new submount name.
793 if (!fCanIssuePIOCTL())
796 BYTE InData[ PIOCTL_MAXSIZE ];
797 memset (InData, 0x00, sizeof(InData));
799 LPTSTR pszInData = (LPTSTR)InData;
800 lstrcpy (pszInData, pszMapping);
801 pszInData += 1+lstrlen(pszInData);
803 lstrcpy (pszInData, pszSubmountReq);
805 BYTE OutData[ PIOCTL_MAXSIZE ];
806 memset (OutData, 0x00, sizeof(OutData));
808 struct ViceIoctl IOInfo;
809 IOInfo.in = (char *)InData;
810 IOInfo.in_size = PIOCTL_MAXSIZE;
811 IOInfo.out = (char *)OutData;
812 IOInfo.out_size = PIOCTL_MAXSIZE;
814 ULONG status = pioctl (0, VIOC_MAKESUBMOUNT, &IOInfo, 1);
821 lstrcpy (pszSubmount, (LPCTSTR)OutData);
822 return (pszSubmount[0] != TEXT('\0')) ? TRUE : FALSE;
826 BOOL ActivateDriveMap (TCHAR chDrive, LPTSTR pszMapping, LPTSTR pszSubmountReq, BOOL fPersistent, DWORD *pdwStatus)
828 // We can only map drives to places in AFS using this function.
830 if ( (lstrncmpi (pszMapping, cm_slash_mount_root, lstrlen(cm_slash_mount_root))) &&
831 (lstrncmpi (pszMapping, cm_back_slash_mount_root, lstrlen(cm_back_slash_mount_root))) )
834 *pdwStatus = ERROR_BAD_NETPATH;
838 // First we have to translate {pszMapping} into a submount, and if there is
839 // no current submount associated with this path, we'll have to make one.
842 TCHAR szSubmount[ MAX_PATH ];
843 if (!PathToSubmount (szSubmount, pszMapping, pszSubmountReq, &status))
850 // We now have a submount name and drive letter--map the network drive.
853 rc=MountDOSDrive(chDrive,szSubmount,fPersistent,NULL);
855 rc=MountDOSDrive(chDrive,/*szSubmount*/pszMapping,fPersistent,NULL);
866 BOOL InactivateDriveMap (TCHAR chDrive, DWORD *pdwStatus)
868 DWORD rc = DisMountDOSDrive(chDrive, FALSE);
878 void AddSubMount (LPTSTR pszSubmount, LPTSTR pszMapping)
880 TCHAR szRHS[ MAX_PATH ];
881 AdjustAfsPath (szRHS, pszMapping, FALSE, TRUE);
883 lstrcpy (szRHS, TEXT("/"));
885 WriteExpandedRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount, szRHS);
889 void RemoveSubMount (LPTSTR pszSubmount)
891 DeleteRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount);
895 void AdjustAfsPath (LPTSTR pszTarget, LPCTSTR pszSource, BOOL fWantAFS, BOOL fWantForwardSlashes)
898 lstrcpy (pszTarget, (fWantAFS) ? cm_slash_mount_root : TEXT(""));
899 else if ((*pszSource != TEXT('/')) && (*pszSource != TEXT('\\')))
900 wsprintf (pszTarget, TEXT("%s/%s"),cm_slash_mount_root, pszSource);
901 // We don't want to strip afs off the start if it is part of something for example afscell.company.com
902 else if (fWantAFS && (lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root))) || !((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
903 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
904 (lstrlen(pszSource) == strlen(cm_slash_mount_root))))
905 wsprintf (pszTarget, TEXT("%s%s"),cm_slash_mount_root, pszSource);
906 else if (!fWantAFS && (!lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root)) && ((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
907 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
908 (lstrlen(pszSource) == strlen(cm_slash_mount_root)))))
909 lstrcpy (pszTarget, &pszSource[strlen(cm_slash_mount_root)]);
911 lstrcpy (pszTarget, pszSource);
913 for (LPTSTR pch = pszTarget; *pch; ++pch)
915 if (fWantForwardSlashes)
917 *pch = (*pch == TEXT('\\')) ? TEXT('/') : (*pch);
919 else // (!fWantForwardSlashes)
921 *pch = (*pch == TEXT('/')) ? TEXT('\\') : (*pch);
925 if (lstrlen(pszTarget) &&
926 ((pszTarget[lstrlen(pszTarget)-1] == TEXT('/')) ||
927 (pszTarget[lstrlen(pszTarget)-1] == TEXT('\\'))))
929 pszTarget[lstrlen(pszTarget)-1] = TEXT('\0');
933 BOOL GetDriveSubmount (TCHAR chDrive, LPTSTR pszSubmountNow)
935 BOOL isWinNT = IsWindowsNT();
937 TCHAR szDrive[] = TEXT("*:");
938 szDrive[0] = chDrive;
940 TCHAR szMapping[ _MAX_PATH ] = TEXT("");
942 if (isWinNT && !QueryDosDevice (szDrive, szMapping, MAX_PATH))
945 LPTSTR pszSubmount = szMapping;
947 TCHAR szNetBiosName[32];
948 memset(szNetBiosName, '\0', sizeof(szNetBiosName));
949 GetClientNetbiosName(szNetBiosName);
950 _tcscat(szNetBiosName, TEXT("\\"));
954 // Now if this is an AFS network drive mapping, {szMapping} will be:
956 // \Device\LanmanRedirector\<Drive>:\<netbiosname>\submount
958 // on Windows NT. On Windows 2000, it will be:
960 // \Device\LanmanRedirector\;<Drive>:0\<netbiosname>\submount
962 // (This is presumably to support multiple drive mappings with
965 // on Windows XP and 2003, it will be :
966 // \Device\LanmanRedirector\;<Drive>:<AuthID>\<netbiosname>\submount
968 // where : <Drive> : DOS drive letter
969 // <AuthID>: Authentication ID, 16 char hex.
970 // <netbiosname>: Netbios name of server
974 b = _tcsnicmp(szMapping, cszLANMANDEVICE, _tcslen(cszLANMANDEVICE));
976 const TCHAR ker_sub_path[] = "\\Device\\afsrdr\\";
977 b = _tcsnicmp(szMapping, ker_sub_path, _tcslen(ker_sub_path));
982 pszSubmount = &szMapping[ _tcslen(cszLANMANDEVICE) ];
984 pszSubmount = &szMapping[ _tcslen(ker_sub_path) ];
988 if (*(pszSubmount) < '0' ||
989 *(pszSubmount) > '9')
995 if (*(pszSubmount) != TEXT(';'))
1000 if (toupper(*(++pszSubmount)) != chDrive)
1003 if (*(++pszSubmount) != TEXT(':'))
1007 // No longer a safe assumption on XP
1008 if (IsWindows2000())
1009 if (*(++pszSubmount) != TEXT('0'))
1013 // scan for next "\"
1014 while (*(++pszSubmount) != TEXT('\\'))
1016 if (*pszSubmount==0)
1020 // note that szNetBiosName has a '\\' tagged in the end earlier
1021 for (++pszSubmount; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1022 if (!_tcsncicmp(pszSubmount, szNetBiosName, _tcslen(szNetBiosName)))
1024 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1027 pszSubmount += _tcslen(szNetBiosName);
1030 else // (!IsWindowsNT())
1032 DWORD dwSize = MAX_PATH;
1033 if (WNetGetConnection (szDrive, szMapping, &dwSize) != NO_ERROR)
1035 if (*(pszSubmount++) != TEXT('\\'))
1037 if (*(pszSubmount++) != TEXT('\\'))
1039 for ( ; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1040 if (!lstrncmpi (pszSubmount, szNetBiosName, lstrlen(szNetBiosName)))
1042 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1044 pszSubmount += lstrlen(szNetBiosName);
1047 if (!pszSubmount || !*pszSubmount)
1051 lstrcpy (pszSubmountNow, pszSubmount);
1053 lstrcpy (pszSubmountNow, "\\afs");
1054 lstrcat (pszSubmountNow, pszSubmount);
1059 /* Generate Random User name random acording to time*/
1061 TCHAR pUserName[MAXRANDOMNAMELEN]=TEXT("");
1062 BOOL fUserName=FALSE;
1063 #define AFSLogonOptionName TEXT(AFSREG_CLT_SVC_PROVIDER_SUBKEY)
1065 void SetBitLogonOption(BOOL set,DWORD value)
1068 RWLogonOption(FALSE,((set)?value | RWLogonOption(TRUE,0):RWLogonOption(TRUE,0) & ~value) );
1071 DWORD RWLogonOption(BOOL read,DWORD value)
1073 // if read is true then if value==0 return registry value
1074 // if read and value!=0 then use value to test registry, return TRUE if value bits match value read
1077 DWORD LSPtype, LSPsize;
1083 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, KEY_QUERY_VALUE, &hk)==ERROR_SUCCESS)
1085 LSPsize=sizeof(rval);
1086 RegQueryValueEx(hk, "LogonOptions", NULL,
1087 &LSPtype, (LPBYTE)&rval, &LSPsize);
1090 return (value==0)?rval:((rval & value)==value);
1092 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, NULL, 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
1094 RegSetValueEx(hk,TEXT("LogonOptions"),NULL,REG_DWORD,(LPBYTE)&value,sizeof(value));
1101 void MapShareName(char *pszCmdLineA)
1106 while (*pszCmdLineA && (*pszCmdLineA != ' '))
1108 *p++=*pszCmdLineA++;
1112 void GenRandomName(TCHAR *pname,int len)
1115 { //user name was passed through command line, use once
1119 srand( (unsigned)time( NULL ) );
1120 for (int i=0;i<len;i++)
1121 pname[i]='a'+(rand() % 26);
1127 Make a connection using users name
1128 if fUserName then force a connection
1131 BOOL TestAndDoMapShare(DWORD dwState)
1133 if ((dwState!=SERVICE_RUNNING) || (dwOldState!=SERVICE_START_PENDING))
1138 dwOldState=SERVICE_RUNNING;
1139 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1140 return (DoMapShare() && GlobalMountDrive());
1141 return GlobalMountDrive();
1144 BOOL IsServiceActive()
1147 SERVICE_STATUS Status;
1148 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
1151 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
1153 QueryServiceStatus (hService, &Status);
1154 CloseServiceHandle (hService);
1157 CloseServiceHandle (hManager);
1160 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
1163 void TestAndDoUnMapShare()
1165 if (!RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1167 DoUnMapShare(FALSE);
1170 void DoUnMapShare(BOOL drivemap) //disconnect drivemap
1172 TCHAR szMachine[MAX_PATH],szPath[MAX_PATH];
1175 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1177 DWORD cbBuffer=16384;
1181 memset(szMachine, '\0', sizeof(szMachine));
1182 GetClientNetbiosName(szMachine);
1184 // Initialize the data structure
1185 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1187 sprintf(szPath,"\\\\%s\\",szMachine);
1189 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1191 memset(lpnrLocal,0,cbBuffer);
1192 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1194 for (DWORD i=0;i<cEntries;i++)
1196 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath))
1198 if ((lpnrLocal[i].lpLocalName) && (strlen(lpnrLocal[i].lpLocalName)>0))
1201 DisMountDOSDrive(*lpnrLocal[i].lpLocalName);
1202 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Local=%x",res);
1205 DisMountDOSDriveFull(lpnrLocal[i].lpRemoteName);
1206 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Remote=%x",res);
1211 } while (res!=ERROR_NO_MORE_ITEMS);
1212 GlobalFree((HGLOBAL)lpnrLocal);
1213 WNetCloseEnum(hEnum);
1216 BOOL DoMapShareChange()
1219 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1222 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1225 DWORD cbBuffer=16384;
1227 memset(szMachine, '\0', sizeof(szMachine));
1228 GetClientNetbiosName(szMachine);
1230 // Initialize the data structure
1231 if (!IsServiceActive())
1233 memset (&List, 0x00, sizeof(DRIVEMAPLIST));
1234 for (size_t ii = 0; ii < 26; ++ii)
1235 List.aDriveMap[ii].chDrive = chDRIVE_A + ii;
1236 QueryDriveMapList_ReadSubmounts (&List);
1237 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1239 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1240 sprintf(szPath,"\\\\%s\\",szMachine);
1243 memset(lpnrLocal,0,cbBuffer);
1244 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1246 for (DWORD i=0;i<cEntries;i++)
1248 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)==NULL)
1249 continue; //only look at real afs mappings
1250 CHAR * pSubmount=strrchr(lpnrLocal[i].lpRemoteName,'\\')+1;
1251 if (lstrcmpi(pSubmount,"all")==0)
1252 continue; // do not remove 'all'
1253 for (DWORD j=0;j<List.cSubmounts;j++)
1256 (List.aSubmounts[j].szSubmount[0]) &&
1257 (lstrcmpi(List.aSubmounts[j].szSubmount,pSubmount)==0)
1260 List.aSubmounts[j].fInUse=TRUE;
1264 // wasn't on list so lets remove
1265 DisMountDOSDrive(pSubmount);
1269 } while (res!=ERROR_NO_MORE_ITEMS);
1270 GlobalFree((HGLOBAL)lpnrLocal);
1271 WNetCloseEnum(hEnum);
1272 sprintf(szPath,"\\\\%s\\all",szMachine);
1274 // Lets connect all submounts that weren't connectd
1275 DWORD cbUser=MAXRANDOMNAMELEN-1;
1276 CHAR szUser[MAXRANDOMNAMELEN];
1277 CHAR * pUser = NULL;
1278 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1279 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1280 if (!pUserName[0]) {
1281 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1288 if ((pUser=strchr(szUser,'\\'))!=NULL)
1292 for (DWORD j=0;j<List.cSubmounts;j++)
1294 if (List.aSubmounts[j].fInUse)
1296 DWORD res=MountDOSDrive(0,List.aSubmounts[j].szSubmount,FALSE,pUser);
1305 BOOL bMappedAll=FALSE;
1307 // Initialize the data structure
1308 DEBUG_EVENT0("AFS DoMapShare");
1309 QueryDriveMapList (&List);
1311 // All connections have been removed
1312 // Lets restore them after making the connection from the random name
1314 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1315 memset(szMachine, '\0', sizeof(szMachine));
1316 GetClientNetbiosName(szMachine);
1317 sprintf(szPath,"\\\\%s\\all",szMachine);
1319 // Lets connect all submounts that weren't connectd
1320 DWORD cbUser=MAXRANDOMNAMELEN-1;
1321 CHAR szUser[MAXRANDOMNAMELEN];
1322 CHAR * pUser = NULL;
1323 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1324 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1325 if (!pUserName[0]) {
1326 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1333 if ((pUser=strchr(szUser,'\\'))!=NULL)
1337 for (DWORD i=0;i<List.cSubmounts;i++)
1339 if (List.aSubmounts[i].szSubmount[0])
1341 DWORD res=MountDOSDrive(0,List.aSubmounts[i].szSubmount,FALSE,pUser);
1342 if (lstrcmpi("all",List.aSubmounts[i].szSubmount)==0)
1346 if (!bMappedAll) //make sure all is mapped also
1348 DWORD res=MountDOSDrive(0,"all",FALSE,pUser);
1349 if (res==ERROR_SESSION_CREDENTIAL_CONFLICT)
1351 DisMountDOSDrive("all");
1352 MountDOSDrive(0,"all",FALSE,pUser);
1355 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
1357 if (List.aDriveMap[chDrive-chDRIVE_A].fActive ||
1358 ForceMapActive(chDrive))
1360 TCHAR szSubmount[ MAX_PATH ];
1361 if (List.aDriveMap[chDrive-chDRIVE_A].szSubmount[0])
1362 lstrcpy(szSubmount,List.aDriveMap[chDrive-chDRIVE_A].szSubmount);
1363 else if (!PathToSubmount (szSubmount, List.aDriveMap[chDrive-chDRIVE_A].szMapping, NULL, NULL))
1366 BOOL fPersistent = List.aDriveMap[chDrive-chDRIVE_A].fPersistent;
1367 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1368 fPersistent = FALSE;
1369 DWORD res=MountDOSDrive(chDrive
1371 ,fPersistent,pUser);
1377 BOOL GlobalMountDrive()
1379 char szDriveToMapTo[5];
1381 char szKeyName[256];
1385 DWORD dwSubMountSize;
1386 char unsigned szSubMount[256];
1387 char cm_HostName[200];
1388 DWORD dwType=sizeof(cm_HostName);
1389 if (!IsServiceActive())
1391 if (!GetComputerName(cm_HostName, &dwType))
1393 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSREG_CLT_SVC_PARAM_SUBKEY);
1395 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE,
1397 if (dwResult != ERROR_SUCCESS)
1401 dwDriveSize = sizeof(szDriveToMapTo);
1402 dwSubMountSize = sizeof(szSubMount);
1403 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize,
1404 0, &dwType, szSubMount, &dwSubMountSize);
1405 if (dwResult != ERROR_MORE_DATA) {
1406 if (dwResult != ERROR_SUCCESS) {
1407 if (dwResult != ERROR_NO_MORE_ITEMS)
1409 DEBUG_EVENT1("AFS DriveMap","Failed to read GlobalAutoMapper values: %d",dwResult);
1414 dwResult=MountDOSDrive(*szDriveToMapTo,(const char *)szSubMount,FALSE,NULL);
1420 DWORD MountDOSDrive(char chDrive,const char *szSubmount,BOOL bPersistent,const char * pUsername)
1424 TCHAR szPath[MAX_PATH], szTokens[MAX_PATH], *tok;
1425 TCHAR szClient[MAX_PATH];
1426 TCHAR szDrive[3] = TEXT("?:");
1429 int pathCount, currPos, lastPos, x;
1434 strcpy(szTokens, szSubmount);
1435 tok = strtok(szTokens, "/\\");
1439 if (pathCount || stricmp(tok, "afs"))
1441 strcat(szPath, "\\");
1442 strcat(szPath, tok);
1445 tok = strtok(NULL, "/\\");
1448 sprintf(szDrive,"%c:",chDrive);
1449 strcpy(szTokens, szPath);
1450 sprintf(szPath,"\\Device\\afsrdr\\%d%s",pathCount,szTokens);
1451 //succ = DefineDosDevice(DDD_RAW_TARGET_PATH, "J:", "\\Device\\afsrdr\\2\\ericjw\\test");
1452 succ = DefineDosDevice(DDD_RAW_TARGET_PATH, szDrive, szPath);
1453 err = GetLastError();
1455 return succ ? NO_ERROR : ERROR_DEVICE_IN_USE;
1457 sprintf(szDrive,"%c:",chDrive);
1458 GetClientNetbiosName (szClient);
1459 sprintf(szPath,"\\\\%s\\%s",szClient,szSubmount);
1461 memset (&nr, 0x00, sizeof(NETRESOURCE));
1462 nr.dwType=RESOURCETYPE_DISK;
1463 nr.lpLocalName=szDrive;
1464 nr.lpRemoteName=szPath;
1465 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
1466 DWORD res=WNetAddConnection2(&nr,NULL,pUsername,(bPersistent)?CONNECT_UPDATE_PROFILE:0);
1467 DEBUG_EVENT5("AFS DriveMap","Mount %s Local[%s] Remote[%s] User[%s]=%x",
1468 (bPersistent)?"Persistant" : "NonPresistant",
1469 szDrive,szPath,pUsername?pUsername:"NULL",res);
1474 DWORD DisMountDOSDriveFull(const char *szPath,BOOL bForce)
1477 DWORD res=WNetCancelConnection(szPath,bForce);
1480 res = ERROR_DEVICE_IN_USE;
1481 // must handle drive letters and afs paths
1482 // DDD_REMOVE_DEFINITION
1484 DEBUG_EVENT3("AFS DriveMap","%sDismount Remote[%s]=%x",
1485 bForce ? "Forced " : "",szPath,res);
1486 return (res==ERROR_NOT_CONNECTED)?NO_ERROR:res;
1489 DWORD DisMountDOSDrive(const char *pSubmount,BOOL bForce)
1491 TCHAR szPath[MAX_PATH];
1492 TCHAR szClient[MAX_PATH];
1493 GetClientNetbiosName (szClient);
1494 sprintf(szPath,"\\\\%s\\%s",szClient,pSubmount);
1495 return DisMountDOSDriveFull(szPath,bForce);
1499 DWORD DisMountDOSDrive(const char chDrive,BOOL bForce)
1501 TCHAR szPath[MAX_PATH];
1504 sprintf(szPath,"%c:",chDrive);
1506 succ = DefineDosDevice(DDD_REMOVE_DEFINITION, szPath, NULL);
1507 return (!succ) ? GetLastError() : 0;
1509 return DisMountDOSDriveFull(szPath,bForce);