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)
197 static int lstrncmpi (LPCTSTR pszA, LPCTSTR pszB, size_t cch)
201 return (!pszB) - (!pszA); // A,!B:1, !A,B:-1, !A,!B:0
204 for ( ; cch > 0; cch--, pszA = CharNext(pszA), pszB = CharNext(pszB))
206 TCHAR chA = toupper( *pszA );
207 TCHAR chB = toupper( *pszB );
210 return (!chB) - (!chA); // A,!B:1, !A,B:-1, !A,!B:0
213 return (int)(chA) - (int)(chB); // -1:A<B, 0:A==B, 1:A>B
216 return 0; // no differences before told to stop comparing, so A==B
221 * REALLOC ____________________________________________________________________
226 #define REALLOC(_a,_c,_r,_i) DriveMapReallocFunction ((LPVOID*)&_a,sizeof(*_a),&_c,_r,_i)
227 BOOL DriveMapReallocFunction (LPVOID *ppTarget, size_t cbElement, size_t *pcTarget, size_t cReq, size_t cInc)
232 if (cReq <= *pcTarget)
235 if ((cNew = cInc * ((cReq + cInc-1) / cInc)) <= 0)
238 if ((pNew = Allocate (cbElement * cNew)) == NULL)
240 memset (pNew, 0x00, cbElement * cNew);
244 memcpy (pNew, *ppTarget, cbElement * (*pcTarget));
256 * WINDOWS NT STUFF ___________________________________________________________
260 static BOOL IsWindowsNT (void)
262 static BOOL fChecked = FALSE;
263 static BOOL fIsWinNT = FALSE;
269 OSVERSIONINFO Version;
270 memset (&Version, 0x00, sizeof(Version));
271 Version.dwOSVersionInfoSize = sizeof(Version);
273 if (GetVersionEx (&Version))
275 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT)
283 /* Check if the OS is Windows 2000 or higher.
285 BOOL IsWindows2000 (void)
287 static BOOL fChecked = FALSE;
288 static BOOL fIsWin2K = FALSE;
294 OSVERSIONINFO Version;
295 memset (&Version, 0x00, sizeof(Version));
296 Version.dwOSVersionInfoSize = sizeof(Version);
298 if (GetVersionEx (&Version))
300 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
301 Version.dwMajorVersion >= 5)
310 * GENERAL ____________________________________________________________________
314 void GetClientNetbiosName (LPTSTR pszName)
316 static TCHAR szNetbiosName[32] = "";
318 if ( szNetbiosName[0] == 0 ) {
319 lana_GetNetbiosName(szNetbiosName, LANA_NETBIOS_NAME_FULL);
321 _tcscpy(pszName, szNetbiosName);
325 BOOL SubmountToPath (PDRIVEMAPLIST pList, LPTSTR pszPath, LPTSTR pszSubmount, BOOL fMarkInUse)
327 // We can't do this translation unless we're under Windows NT.
332 // \\computer-afs\all always maps to "/afs"
334 if (!lstrcmpi (pszSubmount, TEXT("all")))
336 lstrcpy (pszPath, cm_slash_mount_root);
340 // Otherwise, look up our list of submounts.
343 AdjustAfsPath (pszPath, pszSubmount, TRUE, TRUE);
345 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
349 b = !lstrcmpi (pList->aSubmounts[ii].szSubmount, pszSubmount);
351 b = !lstrcmpi (pList->aSubmounts[ii].szMapping, pszPath);
356 pList->aSubmounts[ii].fInUse = TRUE;
357 AdjustAfsPath (pszPath, pList->aSubmounts[ii].szMapping, TRUE, TRUE);
366 BOOL IsValidSubmountName (LPTSTR pszSubmount)
370 if (lstrlen (pszSubmount) > 12)
373 for ( ; *pszSubmount; ++pszSubmount)
375 if (!isprint(*pszSubmount))
377 if (*pszSubmount == TEXT(' '))
379 if (*pszSubmount == TEXT('/'))
381 if (*pszSubmount == TEXT('\\'))
383 if (*pszSubmount == TEXT('\t'))
392 * PIOCTL SUPPORT _____________________________________________________________
398 #include "../afsd/fs_utils.h"
400 #define __CM_CONFIG_INTERFACES_ONLY__
401 #include "../afsd/cm_config.h"
403 #define __CM_IOCTL_INTERFACES_ONLY__
404 #include "../afsd/cm_ioctl.h"
408 #define PIOCTL_MAXSIZE 2048
411 BOOL fCanIssuePIOCTL (void)
415 TCHAR szGateway[ 256 ] = TEXT("");
416 GetClientNetbiosName (szGateway);
417 return (szGateway[0]) ? TRUE : FALSE;
420 SERVICE_STATUS Status;
421 memset (&Status, 0x00, sizeof(Status));
422 Status.dwCurrentState = SERVICE_STOPPED;
425 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
428 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
430 QueryServiceStatus (hService, &Status);
431 CloseServiceHandle (hService);
434 CloseServiceHandle (hManager);
437 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
442 * QUERYDRIVEMAPLIST __________________________________________________________
446 void QueryDriveMapList_ReadSubmounts (PDRIVEMAPLIST pList)
452 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
453 cszSECTION_SUBMOUNTS,
456 REG_OPTION_NON_VOLATILE,
457 KEY_READ|KEY_QUERY_VALUE,
463 RegQueryInfoKey( hkSubmounts,
466 NULL, /* lpReserved */
467 NULL, /* lpcSubKeys */
468 NULL, /* lpcMaxSubKeyLen */
469 NULL, /* lpcMaxClassLen */
470 &dwSubmounts, /* lpcValues */
471 NULL, /* lpcMaxValueNameLen */
472 NULL, /* lpcMaxValueLen */
473 NULL, /* lpcbSecurityDescriptor */
474 NULL /* lpftLastWriteTime */
477 for ( DWORD dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
478 TCHAR submountPath[MAX_PATH] = "";
479 DWORD submountPathLen = MAX_PATH;
480 TCHAR submountName[MAX_PATH];
481 DWORD submountNameLen = MAX_PATH;
484 RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
485 &dwType, (LPBYTE)submountPath, &submountPathLen);
487 if (dwType == REG_EXPAND_SZ) {
489 StringCbCopyA(buf, MAX_PATH, submountPath);
490 submountPathLen = ExpandEnvironmentStrings(buf, submountPath, MAX_PATH);
491 if (submountPathLen > MAX_PATH)
496 memset (&Submount, 0x00, sizeof(SUBMOUNT));
497 lstrcpy (Submount.szSubmount, submountName);
499 if ( submountPath[0] != TEXT('\0') ) {
500 AdjustAfsPath (Submount.szMapping, submountPath, FALSE, TRUE);
503 for (ii = 0; ii < pList->cSubmounts; ++ii)
505 if (!pList->aSubmounts[ii].szSubmount[0])
508 if (REALLOC (pList->aSubmounts, pList->cSubmounts, 1+ii, cREALLOC_SUBMOUNTS))
510 memcpy (&pList->aSubmounts[ii], &Submount, sizeof(SUBMOUNT));
515 RegCloseKey(hkSubmounts);
520 void QueryDriveMapList_ReadMappings (PDRIVEMAPLIST pList)
523 RegCreateKeyEx( HKEY_CURRENT_USER,
527 REG_OPTION_NON_VOLATILE,
528 KEY_READ|KEY_QUERY_VALUE,
534 RegQueryInfoKey( hkMappings,
537 NULL, /* lpReserved */
538 NULL, /* lpcSubKeys */
539 NULL, /* lpcMaxSubKeyLen */
540 NULL, /* lpcMaxClassLen */
541 &dwMappings, /* lpcValues */
542 NULL, /* lpcMaxValueNameLen */
543 NULL, /* lpcMaxValueLen */
544 NULL, /* lpcbSecurityDescriptor */
545 NULL /* lpftLastWriteTime */
548 for ( DWORD dwIndex = 0; dwIndex < dwMappings; dwIndex ++ ) {
549 TCHAR mapping[MAX_PATH] = "";
550 DWORD mappingLen = MAX_PATH;
551 TCHAR drive[MAX_PATH];
552 DWORD driveLen = MAX_PATH;
555 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL,
556 &dwType, (LPBYTE)mapping, &mappingLen);
557 if ( dwType == REG_EXPAND_SZ ) {
559 DWORD dummyLen = ExpandEnvironmentStrings(mapping, buf, MAX_PATH);
560 if (dummyLen > MAX_PATH)
562 _tcsncpy(mapping, buf, MAX_PATH);
566 memset (&DriveMap, 0x00, sizeof(DRIVEMAP));
567 DriveMap.chDrive = toupper(*drive);
568 DriveMap.fPersistent = TRUE;
569 if ((DriveMap.chDrive < chDRIVE_A) || (DriveMap.chDrive > chDRIVE_Z))
572 if (mapping[0] != TEXT('\0'))
574 AdjustAfsPath (DriveMap.szMapping, mapping, TRUE, TRUE);
575 if (DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] == TEXT('*'))
577 DriveMap.fPersistent = FALSE;
578 DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] = TEXT('\0');
580 size_t iDrive = DriveMap.chDrive - chDRIVE_A;
581 memcpy (&pList->aDriveMap[ iDrive ], &DriveMap, sizeof(DRIVEMAP));
585 RegCloseKey(hkMappings);
588 BOOL ForceMapActive (TCHAR chDrive)
593 szDrive[0] = chDrive;
596 DWORD len = sizeof(szActive);
597 ReadRegistryString( HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, szActive, &len);
599 if ( !lstrcmp(szActive,"1") || !lstrcmpi(szActive,"true") || !lstrcmpi(szActive,"on") || !lstrcmpi(szActive,"yes") )
605 void WriteActiveMap (TCHAR chDrive, BOOL on)
609 szDrive[0] = chDrive;
612 WriteRegistryString(HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, on ? "1" : "0");
615 void QueryDriveMapList_WriteMappings (PDRIVEMAPLIST pList)
617 WriteDriveMappings (pList);
621 void WriteDriveMappings (PDRIVEMAPLIST pList)
624 RegCreateKeyEx( HKEY_CURRENT_USER,
628 REG_OPTION_NON_VOLATILE,
629 KEY_READ|KEY_QUERY_VALUE|KEY_WRITE,
635 RegQueryInfoKey( hkMappings,
638 NULL, /* lpReserved */
639 NULL, /* lpcSubKeys */
640 NULL, /* lpcMaxSubKeyLen */
641 NULL, /* lpcMaxClassLen */
642 &dwMappings, /* lpcValues */
643 NULL, /* lpcMaxValueNameLen */
644 NULL, /* lpcMaxValueLen */
645 NULL, /* lpcbSecurityDescriptor */
646 NULL /* lpftLastWriteTime */
649 if ( dwMappings > 0 ) {
650 for ( long dwIndex = dwMappings - 1; dwIndex >= 0; dwIndex-- ) {
651 TCHAR drive[MAX_PATH];
652 DWORD driveLen = MAX_PATH;
654 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL, NULL, NULL, NULL);
655 RegDeleteValue( hkMappings, drive );
659 for (size_t iDrive = 0; iDrive < 26; ++iDrive)
661 if (pList->aDriveMap[iDrive].szMapping[0] != TEXT('\0'))
663 TCHAR szLHS[] = TEXT("*");
664 szLHS[0] = pList->aDriveMap[iDrive].chDrive;
666 TCHAR szRHS[MAX_PATH];
667 AdjustAfsPath (szRHS, pList->aDriveMap[iDrive].szMapping, TRUE, TRUE);
668 if (!pList->aDriveMap[iDrive].fPersistent)
669 lstrcat (szRHS, TEXT("*"));
671 RegSetValueEx( hkMappings, szLHS, 0, REG_EXPAND_SZ, (const BYTE *)szRHS, lstrlen(szRHS) + 1);
674 RegCloseKey( hkMappings );
677 BOOL DriveIsGlobalAfsDrive(TCHAR chDrive)
679 TCHAR szKeyName[128];
680 TCHAR szValueName[128];
684 _stprintf(szKeyName, TEXT("%s\\GlobalAutoMapper"), AFSREG_CLT_SVC_PARAM_SUBKEY);
686 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
689 _stprintf(szValueName, TEXT("%c:"), chDrive);
691 DWORD dwSize = sizeof(szValue);
692 BOOL bIsGlobal = (RegQueryValueEx (hKey, szValueName, NULL, NULL, (PBYTE)szValue, &dwSize) == ERROR_SUCCESS);
700 void QueryDriveMapList_FindNetworkDrives (PDRIVEMAPLIST pList, BOOL *pfFoundNew)
702 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
704 TCHAR szSubmount[ MAX_PATH ];
705 if (!GetDriveSubmount (chDrive, szSubmount))
708 // We've got a mapping! Drive {chDrive} is mapped to submount
709 // {szSubmount}. See if that submount makes sense.
713 size_t iDrive = chDrive - chDRIVE_A;
714 if (pList->aDriveMap[ iDrive ].szMapping[0] != TEXT('\0'))
716 pList->aDriveMap[ iDrive ].fActive = TRUE;
717 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
721 else // (IsWindowsNT())
723 TCHAR szAfsPath[ MAX_PATH ];
724 if (!SubmountToPath (pList, szAfsPath, szSubmount, TRUE))
727 // Okay, we know that drive {chDrive} is mapped to afs path {szAfsPath}.
728 // If this drive is a global afs drive, then reject it. Otherwise, look
729 // at pList->aDriveMap, to see if this drive mapping is already in our
730 // list. If not, add it and set pfFoundNew.
732 if (DriveIsGlobalAfsDrive(chDrive))
735 size_t iDrive = chDrive - chDRIVE_A;
736 if (lstrcmpi (pList->aDriveMap[ iDrive ].szMapping, szAfsPath))
739 pList->aDriveMap[ iDrive ].fPersistent = TRUE;
741 pList->aDriveMap[ iDrive ].fActive = TRUE;
742 pList->aDriveMap[ iDrive ].chDrive = chDrive;
743 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
744 AdjustAfsPath (pList->aDriveMap[ iDrive ].szMapping, szAfsPath, TRUE, TRUE);
750 void QueryDriveMapList (PDRIVEMAPLIST pList)
752 // Initialize the data structure
754 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
755 for (size_t ii = 0; ii < 26; ++ii)
756 pList->aDriveMap[ii].chDrive = chDRIVE_A + ii;
758 // Read the current lists of submounts and drive letter mappings
760 QueryDriveMapList_ReadSubmounts (pList);
761 QueryDriveMapList_ReadMappings (pList);
763 // Look through the current list of network drives, and see if
764 // any are currently mapped to AFS. If we find any which are mapped
765 // into AFS unexpectedly, we'll have to rewrite the mappings list.
767 BOOL fFoundNew = FALSE;
768 QueryDriveMapList_FindNetworkDrives (pList, &fFoundNew);
772 QueryDriveMapList_WriteMappings (pList);
777 void FreeDriveMapList (PDRIVEMAPLIST pList)
779 if (pList->aSubmounts)
780 Free (pList->aSubmounts);
781 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
785 BOOL PathToSubmount (LPTSTR pszSubmount, LPTSTR pszMapping, LPTSTR pszSubmountReq, ULONG *pStatus)
787 if (pszSubmountReq && !IsValidSubmountName (pszSubmountReq))
788 pszSubmountReq = NULL;
790 TCHAR szAfsPath[ MAX_PATH ];
791 AdjustAfsPath (szAfsPath, pszMapping, TRUE, TRUE);
793 // Try to ask AFSD for a new submount name.
795 if (!fCanIssuePIOCTL())
798 BYTE InData[ PIOCTL_MAXSIZE ];
799 memset (InData, 0x00, sizeof(InData));
801 LPTSTR pszInData = (LPTSTR)InData;
802 lstrcpy (pszInData, pszMapping);
803 pszInData += 1+lstrlen(pszInData);
805 lstrcpy (pszInData, pszSubmountReq);
807 BYTE OutData[ PIOCTL_MAXSIZE ];
808 memset (OutData, 0x00, sizeof(OutData));
810 struct ViceIoctl IOInfo;
811 IOInfo.in = (char *)InData;
812 IOInfo.in_size = PIOCTL_MAXSIZE;
813 IOInfo.out = (char *)OutData;
814 IOInfo.out_size = PIOCTL_MAXSIZE;
816 ULONG status = pioctl (0, VIOC_MAKESUBMOUNT, &IOInfo, 1);
823 lstrcpy (pszSubmount, (LPCTSTR)OutData);
824 return (pszSubmount[0] != TEXT('\0')) ? TRUE : FALSE;
828 BOOL ActivateDriveMap (TCHAR chDrive, LPTSTR pszMapping, LPTSTR pszSubmountReq, BOOL fPersistent, DWORD *pdwStatus)
830 // We can only map drives to places in AFS using this function.
832 if ( (lstrncmpi (pszMapping, cm_slash_mount_root, lstrlen(cm_slash_mount_root))) &&
833 (lstrncmpi (pszMapping, cm_back_slash_mount_root, lstrlen(cm_back_slash_mount_root))) )
836 *pdwStatus = ERROR_BAD_NETPATH;
840 // First we have to translate {pszMapping} into a submount, and if there is
841 // no current submount associated with this path, we'll have to make one.
844 TCHAR szSubmount[ MAX_PATH ];
845 if (!PathToSubmount (szSubmount, pszMapping, pszSubmountReq, &status))
852 // We now have a submount name and drive letter--map the network drive.
855 rc=MountDOSDrive(chDrive,szSubmount,fPersistent,NULL);
857 rc=MountDOSDrive(chDrive,/*szSubmount*/pszMapping,fPersistent,NULL);
868 BOOL InactivateDriveMap (TCHAR chDrive, DWORD *pdwStatus)
870 DWORD rc = DisMountDOSDrive(chDrive, FALSE);
880 void AddSubMount (LPTSTR pszSubmount, LPTSTR pszMapping)
882 TCHAR szRHS[ MAX_PATH ];
883 AdjustAfsPath (szRHS, pszMapping, FALSE, TRUE);
885 lstrcpy (szRHS, TEXT("/"));
887 WriteExpandedRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount, szRHS);
891 void RemoveSubMount (LPTSTR pszSubmount)
893 DeleteRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount);
897 void AdjustAfsPath (LPTSTR pszTarget, LPCTSTR pszSource, BOOL fWantAFS, BOOL fWantForwardSlashes)
900 lstrcpy (pszTarget, (fWantAFS) ? cm_slash_mount_root : TEXT(""));
901 else if ((*pszSource != TEXT('/')) && (*pszSource != TEXT('\\')))
902 wsprintf (pszTarget, TEXT("%s/%s"),cm_slash_mount_root, pszSource);
903 // We don't want to strip afs off the start if it is part of something for example afscell.company.com
904 else if (fWantAFS && (lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root))) || !((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
905 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
906 (lstrlen(pszSource) == strlen(cm_slash_mount_root))))
907 wsprintf (pszTarget, TEXT("%s%s"),cm_slash_mount_root, pszSource);
908 else if (!fWantAFS && (!lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root)) && ((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
909 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
910 (lstrlen(pszSource) == strlen(cm_slash_mount_root)))))
911 lstrcpy (pszTarget, &pszSource[strlen(cm_slash_mount_root)]);
913 lstrcpy (pszTarget, pszSource);
915 for (LPTSTR pch = pszTarget; *pch; ++pch)
917 if (fWantForwardSlashes)
919 *pch = (*pch == TEXT('\\')) ? TEXT('/') : (*pch);
921 else // (!fWantForwardSlashes)
923 *pch = (*pch == TEXT('/')) ? TEXT('\\') : (*pch);
927 if (lstrlen(pszTarget) &&
928 ((pszTarget[lstrlen(pszTarget)-1] == TEXT('/')) ||
929 (pszTarget[lstrlen(pszTarget)-1] == TEXT('\\'))))
931 pszTarget[lstrlen(pszTarget)-1] = TEXT('\0');
935 BOOL GetDriveSubmount (TCHAR chDrive, LPTSTR pszSubmountNow)
937 BOOL isWinNT = IsWindowsNT();
939 TCHAR szDrive[] = TEXT("*:");
940 szDrive[0] = chDrive;
942 TCHAR szMapping[ _MAX_PATH ] = TEXT("");
944 if (isWinNT && !QueryDosDevice (szDrive, szMapping, MAX_PATH))
947 LPTSTR pszSubmount = szMapping;
949 TCHAR szNetBiosName[32];
950 memset(szNetBiosName, '\0', sizeof(szNetBiosName));
951 GetClientNetbiosName(szNetBiosName);
952 _tcscat(szNetBiosName, TEXT("\\"));
956 // Now if this is an AFS network drive mapping, {szMapping} will be:
958 // \Device\LanmanRedirector\<Drive>:\<netbiosname>\submount
960 // on Windows NT. On Windows 2000, it will be:
962 // \Device\LanmanRedirector\;<Drive>:0\<netbiosname>\submount
964 // (This is presumably to support multiple drive mappings with
967 // on Windows XP and 2003, it will be :
968 // \Device\LanmanRedirector\;<Drive>:<AuthID>\<netbiosname>\submount
970 // where : <Drive> : DOS drive letter
971 // <AuthID>: Authentication ID, 16 char hex.
972 // <netbiosname>: Netbios name of server
976 b = _tcsnicmp(szMapping, cszLANMANDEVICE, _tcslen(cszLANMANDEVICE));
978 const TCHAR ker_sub_path[] = "\\Device\\afsrdr\\";
979 b = _tcsnicmp(szMapping, ker_sub_path, _tcslen(ker_sub_path));
984 pszSubmount = &szMapping[ _tcslen(cszLANMANDEVICE) ];
986 pszSubmount = &szMapping[ _tcslen(ker_sub_path) ];
990 if (*(pszSubmount) < '0' ||
991 *(pszSubmount) > '9')
997 if (*(pszSubmount) != TEXT(';'))
1002 if (toupper(*(++pszSubmount)) != chDrive)
1005 if (*(++pszSubmount) != TEXT(':'))
1009 // No longer a safe assumption on XP
1010 if (IsWindows2000())
1011 if (*(++pszSubmount) != TEXT('0'))
1015 // scan for next "\"
1016 while (*(++pszSubmount) != TEXT('\\'))
1018 if (*pszSubmount==0)
1022 // note that szNetBiosName has a '\\' tagged in the end earlier
1023 for (++pszSubmount; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1024 if (!_tcsncicmp(pszSubmount, szNetBiosName, _tcslen(szNetBiosName)))
1026 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1029 pszSubmount += _tcslen(szNetBiosName);
1032 else // (!IsWindowsNT())
1034 DWORD dwSize = MAX_PATH;
1035 if (WNetGetConnection (szDrive, szMapping, &dwSize) != NO_ERROR)
1037 if (*(pszSubmount++) != TEXT('\\'))
1039 if (*(pszSubmount++) != TEXT('\\'))
1041 for ( ; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1042 if (!lstrncmpi (pszSubmount, szNetBiosName, lstrlen(szNetBiosName)))
1044 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1046 pszSubmount += lstrlen(szNetBiosName);
1049 if (!pszSubmount || !*pszSubmount)
1053 lstrcpy (pszSubmountNow, pszSubmount);
1055 lstrcpy (pszSubmountNow, "\\afs");
1056 lstrcat (pszSubmountNow, pszSubmount);
1061 /* Generate Random User name random acording to time*/
1063 TCHAR pUserName[MAXRANDOMNAMELEN]=TEXT("");
1064 BOOL fUserName=FALSE;
1065 #define AFSLogonOptionName TEXT(AFSREG_CLT_SVC_PROVIDER_SUBKEY)
1067 void SetBitLogonOption(BOOL set,DWORD value)
1070 RWLogonOption(FALSE,((set)?value | RWLogonOption(TRUE,0):RWLogonOption(TRUE,0) & ~value) );
1073 DWORD RWLogonOption(BOOL read,DWORD value)
1075 // if read is true then if value==0 return registry value
1076 // if read and value!=0 then use value to test registry, return TRUE if value bits match value read
1079 DWORD LSPtype, LSPsize;
1085 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, KEY_QUERY_VALUE, &hk)==ERROR_SUCCESS)
1087 LSPsize=sizeof(rval);
1088 RegQueryValueEx(hk, "LogonOptions", NULL,
1089 &LSPtype, (LPBYTE)&rval, &LSPsize);
1092 return (value==0)?rval:((rval & value)==value);
1094 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, NULL, 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
1096 RegSetValueEx(hk,TEXT("LogonOptions"),NULL,REG_DWORD,(LPBYTE)&value,sizeof(value));
1103 void MapShareName(char *pszCmdLineA)
1108 while (*pszCmdLineA && (*pszCmdLineA != ' '))
1110 *p++=*pszCmdLineA++;
1114 void GenRandomName(TCHAR *pname,int len)
1117 { //user name was passed through command line, use once
1121 srand( (unsigned)time( NULL ) );
1122 for (int i=0;i<len;i++)
1123 pname[i]='a'+(rand() % 26);
1129 Make a connection using users name
1130 if fUserName then force a connection
1133 BOOL TestAndDoMapShare(DWORD dwState)
1135 if ((dwState!=SERVICE_RUNNING) || (dwOldState!=SERVICE_START_PENDING))
1140 dwOldState=SERVICE_RUNNING;
1141 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1142 return (DoMapShare() && GlobalMountDrive());
1143 return GlobalMountDrive();
1146 BOOL IsServiceActive()
1149 SERVICE_STATUS Status;
1150 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
1153 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
1155 QueryServiceStatus (hService, &Status);
1156 CloseServiceHandle (hService);
1159 CloseServiceHandle (hManager);
1162 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
1165 void TestAndDoUnMapShare()
1167 if (!RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1169 DoUnMapShare(FALSE);
1172 void DoUnMapShare(BOOL drivemap) //disconnect drivemap
1174 TCHAR szMachine[MAX_PATH],szPath[MAX_PATH];
1177 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1179 DWORD cbBuffer=16384;
1183 memset(szMachine, '\0', sizeof(szMachine));
1184 GetClientNetbiosName(szMachine);
1186 // Initialize the data structure
1187 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1189 sprintf(szPath,"\\\\%s\\",szMachine);
1191 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1193 memset(lpnrLocal,0,cbBuffer);
1194 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1196 for (DWORD i=0;i<cEntries;i++)
1198 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath))
1200 if ((lpnrLocal[i].lpLocalName) && (strlen(lpnrLocal[i].lpLocalName)>0))
1203 DisMountDOSDrive(*lpnrLocal[i].lpLocalName);
1204 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Local=%x",res);
1207 DisMountDOSDriveFull(lpnrLocal[i].lpRemoteName);
1208 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Remote=%x",res);
1213 } while (res!=ERROR_NO_MORE_ITEMS);
1214 GlobalFree((HGLOBAL)lpnrLocal);
1215 WNetCloseEnum(hEnum);
1218 BOOL DoMapShareChange(BOOL removeUnknown)
1221 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1224 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1227 DWORD cbBuffer=16384;
1229 memset(szMachine, '\0', sizeof(szMachine));
1230 GetClientNetbiosName(szMachine);
1232 // Initialize the data structure
1233 if (!IsServiceActive())
1235 memset (&List, 0x00, sizeof(DRIVEMAPLIST));
1236 for (size_t ii = 0; ii < 26; ++ii)
1237 List.aDriveMap[ii].chDrive = chDRIVE_A + ii;
1238 QueryDriveMapList_ReadSubmounts (&List);
1239 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1241 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1242 sprintf(szPath,"\\\\%s\\",szMachine);
1245 memset(lpnrLocal,0,cbBuffer);
1246 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1248 for (DWORD i=0;i<cEntries;i++)
1250 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)==NULL)
1251 continue; //only look at real afs mappings
1252 CHAR * pSubmount=strrchr(lpnrLocal[i].lpRemoteName,'\\')+1;
1253 if (lstrcmpi(pSubmount,"all")==0)
1254 continue; // do not remove 'all'
1255 for (DWORD j=0;j<List.cSubmounts;j++)
1257 if ((List.aSubmounts[j].szSubmount[0]) &&
1258 (lstrcmpi(List.aSubmounts[j].szSubmount,pSubmount)==0)
1261 List.aSubmounts[j].fInUse=TRUE;
1265 // wasn't on list so lets remove
1266 DisMountDOSDrive(pSubmount);
1270 } while (res!=ERROR_NO_MORE_ITEMS);
1271 GlobalFree((HGLOBAL)lpnrLocal);
1272 WNetCloseEnum(hEnum);
1273 sprintf(szPath,"\\\\%s\\all",szMachine);
1275 // Lets connect all submounts that weren't connectd
1276 DWORD cbUser=MAXRANDOMNAMELEN-1;
1277 CHAR szUser[MAXRANDOMNAMELEN];
1278 CHAR * pUser = NULL;
1279 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1280 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1281 if (!pUserName[0]) {
1282 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1289 if ((pUser=strchr(szUser,'\\'))!=NULL)
1293 for (DWORD j=0;j<List.cSubmounts;j++)
1295 if (List.aSubmounts[j].fInUse)
1297 DWORD res=MountDOSDrive(0,List.aSubmounts[j].szSubmount,FALSE,pUser);
1306 BOOL bMappedAll=FALSE;
1308 // Initialize the data structure
1309 DEBUG_EVENT0("AFS DoMapShare");
1310 QueryDriveMapList (&List);
1312 // All connections have been removed
1313 // Lets restore them after making the connection from the random name
1315 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1316 memset(szMachine, '\0', sizeof(szMachine));
1317 GetClientNetbiosName(szMachine);
1318 sprintf(szPath,"\\\\%s\\all",szMachine);
1320 // Lets connect all submounts that weren't connectd
1321 DWORD cbUser=MAXRANDOMNAMELEN-1;
1322 CHAR szUser[MAXRANDOMNAMELEN];
1323 CHAR * pUser = NULL;
1324 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)!=NO_ERROR) {
1325 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY)) {
1326 if (!pUserName[0]) {
1327 GenRandomName(szUser,MAXRANDOMNAMELEN-1);
1334 if ((pUser=strchr(szUser,'\\'))!=NULL)
1338 for (DWORD i=0;i<List.cSubmounts;i++)
1340 if (List.aSubmounts[i].szSubmount[0])
1342 DWORD res=MountDOSDrive(0,List.aSubmounts[i].szSubmount,FALSE,pUser);
1343 if (lstrcmpi("all",List.aSubmounts[i].szSubmount)==0)
1347 if (!bMappedAll) //make sure all is mapped also
1349 DWORD res=MountDOSDrive(0,"all",FALSE,pUser);
1350 if (res==ERROR_SESSION_CREDENTIAL_CONFLICT)
1352 DisMountDOSDrive("all");
1353 MountDOSDrive(0,"all",FALSE,pUser);
1356 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
1358 if (List.aDriveMap[chDrive-chDRIVE_A].fActive ||
1359 ForceMapActive(chDrive))
1361 TCHAR szSubmount[ MAX_PATH ];
1362 if (List.aDriveMap[chDrive-chDRIVE_A].szSubmount[0])
1363 lstrcpy(szSubmount,List.aDriveMap[chDrive-chDRIVE_A].szSubmount);
1364 else if (!PathToSubmount (szSubmount, List.aDriveMap[chDrive-chDRIVE_A].szMapping, NULL, NULL))
1367 BOOL fPersistent = List.aDriveMap[chDrive-chDRIVE_A].fPersistent;
1368 if (RWLogonOption(TRUE,LOGON_OPTION_HIGHSECURITY))
1369 fPersistent = FALSE;
1370 DWORD res=MountDOSDrive(chDrive
1372 ,fPersistent,pUser);
1378 BOOL GlobalMountDrive()
1380 char szDriveToMapTo[5];
1382 char szKeyName[256];
1386 DWORD dwSubMountSize;
1387 char unsigned szSubMount[256];
1388 char cm_HostName[200];
1389 DWORD dwType=sizeof(cm_HostName);
1390 if (!IsServiceActive())
1392 if (!GetComputerName(cm_HostName, &dwType))
1394 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSREG_CLT_SVC_PARAM_SUBKEY);
1396 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE,
1398 if (dwResult != ERROR_SUCCESS)
1402 dwDriveSize = sizeof(szDriveToMapTo);
1403 dwSubMountSize = sizeof(szSubMount);
1404 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize,
1405 0, &dwType, szSubMount, &dwSubMountSize);
1406 if (dwResult != ERROR_MORE_DATA) {
1407 if (dwResult != ERROR_SUCCESS) {
1408 if (dwResult != ERROR_NO_MORE_ITEMS)
1410 DEBUG_EVENT1("AFS DriveMap","Failed to read GlobalAutoMapper values: %d",dwResult);
1415 dwResult=MountDOSDrive(*szDriveToMapTo,(const char *)szSubMount,FALSE,NULL);
1421 DWORD MountDOSDrive(char chDrive,const char *szSubmount,BOOL bPersistent,const char * pUsername)
1425 TCHAR szPath[MAX_PATH], szTokens[MAX_PATH], *tok;
1426 TCHAR szClient[MAX_PATH];
1427 TCHAR szDrive[3] = TEXT("?:");
1430 int pathCount, currPos, lastPos, x;
1435 strcpy(szTokens, szSubmount);
1436 tok = strtok(szTokens, "/\\");
1440 if (pathCount || stricmp(tok, "afs"))
1442 strcat(szPath, "\\");
1443 strcat(szPath, tok);
1446 tok = strtok(NULL, "/\\");
1449 sprintf(szDrive,"%c:",chDrive);
1450 strcpy(szTokens, szPath);
1451 sprintf(szPath,"\\Device\\afsrdr\\%d%s",pathCount,szTokens);
1452 //succ = DefineDosDevice(DDD_RAW_TARGET_PATH, "J:", "\\Device\\afsrdr\\2\\ericjw\\test");
1453 succ = DefineDosDevice(DDD_RAW_TARGET_PATH, szDrive, szPath);
1454 err = GetLastError();
1456 return succ ? NO_ERROR : ERROR_DEVICE_IN_USE;
1458 sprintf(szDrive,"%c:",chDrive);
1459 GetClientNetbiosName (szClient);
1460 sprintf(szPath,"\\\\%s\\%s",szClient,szSubmount);
1462 memset (&nr, 0x00, sizeof(NETRESOURCE));
1463 nr.dwType=RESOURCETYPE_DISK;
1464 nr.lpLocalName=szDrive;
1465 nr.lpRemoteName=szPath;
1466 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
1467 DWORD res=WNetAddConnection2(&nr,NULL,pUsername,(bPersistent)?CONNECT_UPDATE_PROFILE:0);
1468 DEBUG_EVENT5("AFS DriveMap","Mount %s Local[%s] Remote[%s] User[%s]=%x",
1469 (bPersistent)?"Persistant" : "NonPresistant",
1470 szDrive,szPath,pUsername?pUsername:"NULL",res);
1475 DWORD DisMountDOSDriveFull(const char *szPath,BOOL bForce)
1478 DWORD res=WNetCancelConnection(szPath,bForce);
1481 res = ERROR_DEVICE_IN_USE;
1482 // must handle drive letters and afs paths
1483 // DDD_REMOVE_DEFINITION
1485 DEBUG_EVENT3("AFS DriveMap","%sDismount Remote[%s]=%x",
1486 bForce ? "Forced " : "",szPath,res);
1487 return (res==ERROR_NOT_CONNECTED)?NO_ERROR:res;
1490 DWORD DisMountDOSDrive(const char *pSubmount,BOOL bForce)
1492 TCHAR szPath[MAX_PATH];
1493 TCHAR szClient[MAX_PATH];
1494 GetClientNetbiosName (szClient);
1495 sprintf(szPath,"\\\\%s\\%s",szClient,pSubmount);
1496 return DisMountDOSDriveFull(szPath,bForce);
1500 DWORD DisMountDOSDrive(const char chDrive,BOOL bForce)
1502 TCHAR szPath[MAX_PATH];
1505 sprintf(szPath,"%c:",chDrive);
1507 succ = DefineDosDevice(DDD_REMOVE_DEFINITION, szPath, NULL);
1508 return (!succ) ? GetLastError() : 0;
1510 return DisMountDOSDriveFull(szPath,bForce);