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 <afsconfig.h>
39 #include <afs/param.h>
43 #include <afs/fs_utils.h>
48 #include <WINNT/TaLocale.h>
49 #include <WINNT/afsreg.h>
58 #include <lanahelper.h>
61 extern void Config_GetLanAdapter (ULONG *pnLanAdapter);
64 * REGISTRY ___________________________________________________________________
70 * PROFILE SECTIONS ___________________________________________________________
74 #define cREALLOC_SUBMOUNTS 4
76 static TCHAR cszSECTION_SUBMOUNTS[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Submounts");
77 static TCHAR cszSECTION_MAPPINGS[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Mappings");
78 static TCHAR cszSECTION_ACTIVE[] = TEXT(AFSREG_CLT_OPENAFS_SUBKEY "\\Active Maps");
80 static TCHAR cszAUTOSUBMOUNT[] = TEXT("Auto");
81 static TCHAR cszLANMANDEVICE[] = TEXT("\\Device\\LanmanRedirector\\");
85 WriteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
92 REG_OPTION_NON_VOLATILE,
98 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
101 RegCloseKey( hkSub );
103 return (status == ERROR_SUCCESS);
107 WriteExpandedRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs)
114 REG_OPTION_NON_VOLATILE,
120 DWORD status = RegSetValueEx( hkSub, lhs, 0, REG_EXPAND_SZ, (const BYTE *)rhs, strlen(rhs)+1 );
123 RegCloseKey( hkSub );
125 return (status == ERROR_SUCCESS);
129 ReadRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs, LPTSTR rhs, DWORD * size)
136 REG_OPTION_NON_VOLATILE,
143 DWORD localSize = *size;
145 DWORD status = RegQueryValueEx( hkSub, lhs, 0, &dwType, (LPBYTE)rhs, &localSize);
146 if (status == 0 && dwType == REG_EXPAND_SZ) {
147 TCHAR * buf = (TCHAR *)malloc((*size) * sizeof(TCHAR));
148 memcpy(buf, rhs, (*size) * sizeof(TCHAR));
149 localSize = ExpandEnvironmentStrings(buf, rhs, *size);
151 if ( localSize > *size )
152 status = !ERROR_SUCCESS;
157 RegCloseKey( hkSub );
159 return (status == ERROR_SUCCESS);
163 DeleteRegistryString(HKEY key, TCHAR * subkey, LPTSTR lhs)
170 REG_OPTION_NON_VOLATILE,
176 DWORD status = RegDeleteValue( hkSub, lhs );
179 RegCloseKey( hkSub );
181 return (status == ERROR_SUCCESS);
185 * STRINGS ____________________________________________________________________
189 static LPTSTR AllocateStringMemory (size_t cch)
191 LPTSTR psz = (LPTSTR)Allocate (sizeof(TCHAR) * (cch+1));
192 memset (psz, 0x00, sizeof(TCHAR) * (cch+1));
196 static void FreeStringMemory (LPTSTR pszString)
202 * REALLOC ____________________________________________________________________
207 #define REALLOC(_a,_c,_r,_i) DriveMapReallocFunction ((LPVOID*)&_a,sizeof(*_a),&_c,_r,_i)
208 BOOL DriveMapReallocFunction (LPVOID *ppTarget, size_t cbElement, size_t *pcTarget, size_t cReq, size_t cInc)
213 if (cReq <= *pcTarget)
216 if ((cNew = cInc * ((cReq + cInc-1) / cInc)) <= 0)
219 if ((pNew = Allocate (cbElement * cNew)) == NULL)
221 memset (pNew, 0x00, cbElement * cNew);
225 memcpy (pNew, *ppTarget, cbElement * (*pcTarget));
237 * WINDOWS NT STUFF ___________________________________________________________
241 static BOOL IsWindowsNT (void)
243 static BOOL fChecked = FALSE;
244 static BOOL fIsWinNT = FALSE;
250 OSVERSIONINFO Version;
251 memset (&Version, 0x00, sizeof(Version));
252 Version.dwOSVersionInfoSize = sizeof(Version);
254 if (GetVersionEx (&Version))
256 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT)
264 /* Check if the OS is Windows 2000 or higher.
266 BOOL IsWindows2000 (void)
268 static BOOL fChecked = FALSE;
269 static BOOL fIsWin2K = FALSE;
275 OSVERSIONINFO Version;
276 memset (&Version, 0x00, sizeof(Version));
277 Version.dwOSVersionInfoSize = sizeof(Version);
279 if (GetVersionEx (&Version))
281 if (Version.dwPlatformId == VER_PLATFORM_WIN32_NT &&
282 Version.dwMajorVersion >= 5)
291 * GENERAL ____________________________________________________________________
295 void GetClientNetbiosName (LPTSTR pszName)
297 static TCHAR szNetbiosName[32] = "";
299 if ( szNetbiosName[0] == 0 ) {
300 lana_GetNetbiosName(szNetbiosName, LANA_NETBIOS_NAME_FULL);
302 _tcscpy(pszName, szNetbiosName);
306 BOOL SubmountToPath (PDRIVEMAPLIST pList, LPTSTR pszPath, LPTSTR pszSubmount, BOOL fMarkInUse)
308 // We can't do this translation unless we're under Windows NT.
313 // \\computer-afs\all always maps to "/afs"
315 if (!lstrcmpi (pszSubmount, TEXT("all")))
317 lstrcpy (pszPath, cm_slash_mount_root);
321 // Otherwise, look up our list of submounts.
324 AdjustAfsPath (pszPath, pszSubmount, TRUE, TRUE);
326 for (size_t ii = 0; ii < pList->cSubmounts; ++ii)
330 b = !lstrcmpi (pList->aSubmounts[ii].szSubmount, pszSubmount);
332 b = !lstrcmpi (pList->aSubmounts[ii].szMapping, pszPath);
337 pList->aSubmounts[ii].fInUse = TRUE;
338 AdjustAfsPath (pszPath, pList->aSubmounts[ii].szMapping, TRUE, TRUE);
347 BOOL IsValidSubmountName (LPTSTR pszSubmount)
351 if (lstrlen (pszSubmount) > 12)
354 for ( ; *pszSubmount; ++pszSubmount)
356 if (!isprint(*pszSubmount))
358 if (*pszSubmount == TEXT(' '))
360 if (*pszSubmount == TEXT('/'))
362 if (*pszSubmount == TEXT('\\'))
364 if (*pszSubmount == TEXT('\t'))
373 * PIOCTL SUPPORT _____________________________________________________________
379 #include "../afsd/fs_utils.h"
381 #define __CM_CONFIG_INTERFACES_ONLY__
382 #include "../afsd/cm_config.h"
384 #include "../afsd/cm_nls.h"
385 #define __CM_IOCTL_INTERFACES_ONLY__
386 #include "../afsd/cm_ioctl.h"
390 #define PIOCTL_MAXSIZE 2048
393 BOOL fCanIssuePIOCTL (void)
397 TCHAR szGateway[ 256 ] = TEXT("");
398 GetClientNetbiosName (szGateway);
399 return (szGateway[0]) ? TRUE : FALSE;
402 SERVICE_STATUS Status;
403 memset (&Status, 0x00, sizeof(Status));
404 Status.dwCurrentState = SERVICE_STOPPED;
407 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
410 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
412 QueryServiceStatus (hService, &Status);
413 CloseServiceHandle (hService);
416 CloseServiceHandle (hManager);
419 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
424 * QUERYDRIVEMAPLIST __________________________________________________________
428 void QueryDriveMapList_ReadSubmounts (PDRIVEMAPLIST pList)
434 RegCreateKeyEx( HKEY_LOCAL_MACHINE,
435 cszSECTION_SUBMOUNTS,
438 REG_OPTION_NON_VOLATILE,
439 KEY_READ|KEY_QUERY_VALUE,
445 RegQueryInfoKey( hkSubmounts,
448 NULL, /* lpReserved */
449 NULL, /* lpcSubKeys */
450 NULL, /* lpcMaxSubKeyLen */
451 NULL, /* lpcMaxClassLen */
452 &dwSubmounts, /* lpcValues */
453 NULL, /* lpcMaxValueNameLen */
454 NULL, /* lpcMaxValueLen */
455 NULL, /* lpcbSecurityDescriptor */
456 NULL /* lpftLastWriteTime */
459 for ( DWORD dwIndex = 0; dwIndex < dwSubmounts; dwIndex ++ ) {
460 TCHAR submountPath[MAX_PATH] = "";
461 DWORD submountPathLen = MAX_PATH;
462 TCHAR submountName[MAX_PATH];
463 DWORD submountNameLen = MAX_PATH;
466 RegEnumValue( hkSubmounts, dwIndex, submountName, &submountNameLen, NULL,
467 &dwType, (LPBYTE)submountPath, &submountPathLen);
469 if (dwType == REG_EXPAND_SZ) {
471 StringCbCopyA(buf, MAX_PATH, submountPath);
472 submountPathLen = ExpandEnvironmentStrings(buf, submountPath, MAX_PATH);
473 if (submountPathLen > MAX_PATH)
478 memset (&Submount, 0x00, sizeof(SUBMOUNT));
479 lstrcpy (Submount.szSubmount, submountName);
481 if ( submountPath[0] != TEXT('\0') ) {
482 AdjustAfsPath (Submount.szMapping, submountPath, FALSE, TRUE);
485 for (ii = 0; ii < pList->cSubmounts; ++ii)
487 if (!pList->aSubmounts[ii].szSubmount[0])
490 if (REALLOC (pList->aSubmounts, pList->cSubmounts, 1+ii, cREALLOC_SUBMOUNTS))
492 memcpy (&pList->aSubmounts[ii], &Submount, sizeof(SUBMOUNT));
497 RegCloseKey(hkSubmounts);
502 void QueryDriveMapList_ReadMappings (PDRIVEMAPLIST pList)
505 RegCreateKeyEx( HKEY_CURRENT_USER,
509 REG_OPTION_NON_VOLATILE,
510 KEY_READ|KEY_QUERY_VALUE,
516 RegQueryInfoKey( hkMappings,
519 NULL, /* lpReserved */
520 NULL, /* lpcSubKeys */
521 NULL, /* lpcMaxSubKeyLen */
522 NULL, /* lpcMaxClassLen */
523 &dwMappings, /* lpcValues */
524 NULL, /* lpcMaxValueNameLen */
525 NULL, /* lpcMaxValueLen */
526 NULL, /* lpcbSecurityDescriptor */
527 NULL /* lpftLastWriteTime */
530 for ( DWORD dwIndex = 0; dwIndex < dwMappings; dwIndex ++ ) {
531 TCHAR mapping[MAX_PATH] = "";
532 DWORD mappingLen = MAX_PATH;
533 TCHAR drive[MAX_PATH];
534 DWORD driveLen = MAX_PATH;
537 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL,
538 &dwType, (LPBYTE)mapping, &mappingLen);
539 if ( dwType == REG_EXPAND_SZ ) {
541 DWORD dummyLen = ExpandEnvironmentStrings(mapping, buf, MAX_PATH);
542 if (dummyLen > MAX_PATH)
544 _tcsncpy(mapping, buf, MAX_PATH);
548 memset (&DriveMap, 0x00, sizeof(DRIVEMAP));
549 DriveMap.chDrive = toupper(*drive);
550 DriveMap.fPersistent = TRUE;
551 if ((DriveMap.chDrive < chDRIVE_A) || (DriveMap.chDrive > chDRIVE_Z))
554 if (mapping[0] != TEXT('\0'))
556 AdjustAfsPath (DriveMap.szMapping, mapping, TRUE, TRUE);
557 if (DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] == TEXT('*'))
559 DriveMap.fPersistent = FALSE;
560 DriveMap.szMapping[ lstrlen(DriveMap.szMapping)-1 ] = TEXT('\0');
562 size_t iDrive = DriveMap.chDrive - chDRIVE_A;
563 memcpy (&pList->aDriveMap[ iDrive ], &DriveMap, sizeof(DRIVEMAP));
567 RegCloseKey(hkMappings);
570 BOOL ForceMapActive (TCHAR chDrive)
575 szDrive[0] = chDrive;
578 DWORD len = sizeof(szActive);
579 ReadRegistryString( HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, szActive, &len);
581 if ( !lstrcmp(szActive,"1") || !lstrcmpi(szActive,"true") || !lstrcmpi(szActive,"on") || !lstrcmpi(szActive,"yes") )
587 void WriteActiveMap (TCHAR chDrive, BOOL on)
591 szDrive[0] = chDrive;
594 WriteRegistryString(HKEY_CURRENT_USER, cszSECTION_ACTIVE, szDrive, on ? "1" : "0");
597 void QueryDriveMapList_WriteMappings (PDRIVEMAPLIST pList)
599 WriteDriveMappings (pList);
603 void WriteDriveMappings (PDRIVEMAPLIST pList)
606 RegCreateKeyEx( HKEY_CURRENT_USER,
610 REG_OPTION_NON_VOLATILE,
611 KEY_READ|KEY_QUERY_VALUE|KEY_WRITE,
617 RegQueryInfoKey( hkMappings,
620 NULL, /* lpReserved */
621 NULL, /* lpcSubKeys */
622 NULL, /* lpcMaxSubKeyLen */
623 NULL, /* lpcMaxClassLen */
624 &dwMappings, /* lpcValues */
625 NULL, /* lpcMaxValueNameLen */
626 NULL, /* lpcMaxValueLen */
627 NULL, /* lpcbSecurityDescriptor */
628 NULL /* lpftLastWriteTime */
631 if ( dwMappings > 0 ) {
632 for ( long dwIndex = dwMappings - 1; dwIndex >= 0; dwIndex-- ) {
633 TCHAR drive[MAX_PATH];
634 DWORD driveLen = MAX_PATH;
636 RegEnumValue( hkMappings, dwIndex, drive, &driveLen, NULL, NULL, NULL, NULL);
637 RegDeleteValue( hkMappings, drive );
641 for (size_t iDrive = 0; iDrive < 26; ++iDrive)
643 if (pList->aDriveMap[iDrive].szMapping[0] != TEXT('\0'))
645 TCHAR szLHS[] = TEXT("*");
646 szLHS[0] = pList->aDriveMap[iDrive].chDrive;
648 TCHAR szRHS[MAX_PATH];
649 AdjustAfsPath (szRHS, pList->aDriveMap[iDrive].szMapping, TRUE, TRUE);
650 if (!pList->aDriveMap[iDrive].fPersistent)
651 lstrcat (szRHS, TEXT("*"));
653 RegSetValueEx( hkMappings, szLHS, 0, REG_EXPAND_SZ, (const BYTE *)szRHS, lstrlen(szRHS) + 1);
656 RegCloseKey( hkMappings );
659 BOOL DriveIsGlobalAfsDrive(TCHAR chDrive)
661 TCHAR szKeyName[128];
662 TCHAR szValueName[128];
666 _stprintf(szKeyName, TEXT("%s\\GlobalAutoMapper"), AFSREG_CLT_SVC_PARAM_SUBKEY);
668 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
671 _stprintf(szValueName, TEXT("%c:"), chDrive);
673 DWORD dwSize = sizeof(szValue);
674 BOOL bIsGlobal = (RegQueryValueEx (hKey, szValueName, NULL, NULL, (PBYTE)szValue, &dwSize) == ERROR_SUCCESS);
682 void QueryDriveMapList_FindNetworkDrives (PDRIVEMAPLIST pList, BOOL *pfFoundNew)
684 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
686 TCHAR szSubmount[ MAX_PATH ];
687 if (!GetDriveSubmount (chDrive, szSubmount))
690 // We've got a mapping! Drive {chDrive} is mapped to submount
691 // {szSubmount}. See if that submount makes sense.
695 size_t iDrive = chDrive - chDRIVE_A;
696 if (pList->aDriveMap[ iDrive ].szMapping[0] != TEXT('\0'))
698 pList->aDriveMap[ iDrive ].fActive = TRUE;
699 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
703 else // (IsWindowsNT())
705 TCHAR szAfsPath[ MAX_PATH ];
706 if (!SubmountToPath (pList, szAfsPath, szSubmount, TRUE))
709 // Okay, we know that drive {chDrive} is mapped to afs path {szAfsPath}.
710 // If this drive is a global afs drive, then reject it. Otherwise, look
711 // at pList->aDriveMap, to see if this drive mapping is already in our
712 // list. If not, add it and set pfFoundNew.
714 if (DriveIsGlobalAfsDrive(chDrive))
717 size_t iDrive = chDrive - chDRIVE_A;
718 if (lstrcmpi (pList->aDriveMap[ iDrive ].szMapping, szAfsPath))
721 pList->aDriveMap[ iDrive ].fPersistent = TRUE;
723 pList->aDriveMap[ iDrive ].fActive = TRUE;
724 pList->aDriveMap[ iDrive ].chDrive = chDrive;
725 lstrcpy (pList->aDriveMap[ iDrive ].szSubmount, szSubmount);
726 AdjustAfsPath (pList->aDriveMap[ iDrive ].szMapping, szAfsPath, TRUE, TRUE);
732 void QueryDriveMapList (PDRIVEMAPLIST pList)
734 // Initialize the data structure
736 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
737 for (size_t ii = 0; ii < 26; ++ii)
738 pList->aDriveMap[ii].chDrive = chDRIVE_A + ii;
740 // Read the current lists of submounts and drive letter mappings
742 QueryDriveMapList_ReadSubmounts (pList);
743 QueryDriveMapList_ReadMappings (pList);
745 // Look through the current list of network drives, and see if
746 // any are currently mapped to AFS. If we find any which are mapped
747 // into AFS unexpectedly, we'll have to rewrite the mappings list.
749 BOOL fFoundNew = FALSE;
750 QueryDriveMapList_FindNetworkDrives (pList, &fFoundNew);
754 QueryDriveMapList_WriteMappings (pList);
759 void FreeDriveMapList (PDRIVEMAPLIST pList)
761 if (pList->aSubmounts)
762 Free (pList->aSubmounts);
763 memset (pList, 0x00, sizeof(DRIVEMAPLIST));
768 BOOL PathToSubmount (LPTSTR pszSubmount, LPTSTR pszMapping, LPTSTR pszSubmountReq, ULONG *pStatus)
770 // pszSubmount is MAX_PATH in length
772 if (pszSubmountReq && !IsValidSubmountName (pszSubmountReq))
773 pszSubmountReq = NULL;
775 TCHAR szAfsPath[ MAX_PATH ];
776 AdjustAfsPath (szAfsPath, pszMapping, TRUE, TRUE);
778 // Try to ask AFSD for a new submount name.
780 if (!fCanIssuePIOCTL())
783 BYTE InData[ PIOCTL_MAXSIZE ];
784 memset (InData, 0x00, sizeof(InData));
786 LPTSTR pszInData = (LPTSTR)InData;
787 lstrcpy (pszInData, pszMapping);
788 pszInData += 1+lstrlen(pszInData);
790 lstrcpy (pszInData, pszSubmountReq);
792 BYTE OutData[ PIOCTL_MAXSIZE ];
793 memset (OutData, 0x00, sizeof(OutData));
795 struct ViceIoctl IOInfo;
796 IOInfo.in = (char *)InData;
797 IOInfo.in_size = PIOCTL_MAXSIZE;
798 IOInfo.out = (char *)OutData;
799 IOInfo.out_size = PIOCTL_MAXSIZE;
801 ULONG status = pioctl (0, VIOC_MAKESUBMOUNT, &IOInfo, 1);
809 OutData[min(PIOCTL_MAXSIZE, MAX_PATH) - 1] = '\0';
810 lstrcpy (pszSubmount, (LPCTSTR)OutData);
811 return (pszSubmount[0] != TEXT('\0')) ? TRUE : FALSE;
815 BOOL ActivateDriveMap (TCHAR chDrive, LPTSTR pszMapping, LPTSTR pszSubmountReq, BOOL fPersistent, DWORD *pdwStatus)
817 // We can only map drives to places in AFS using this function.
819 if ( (lstrncmpi (pszMapping, cm_slash_mount_root, lstrlen(cm_slash_mount_root))) &&
820 (lstrncmpi (pszMapping, cm_back_slash_mount_root, lstrlen(cm_back_slash_mount_root))) )
823 *pdwStatus = ERROR_BAD_NETPATH;
827 // First we have to translate {pszMapping} into a submount, and if there is
828 // no current submount associated with this path, we'll have to make one.
831 TCHAR szSubmount[ MAX_PATH ];
832 if (!PathToSubmount (szSubmount, pszMapping, pszSubmountReq, &status))
839 // We now have a submount name and drive letter--map the network drive.
842 rc=MountDOSDrive(chDrive,szSubmount,fPersistent,NULL);
844 rc=MountDOSDrive(chDrive,/*szSubmount*/pszMapping,fPersistent,NULL);
855 BOOL InactivateDriveMap (TCHAR chDrive, DWORD *pdwStatus)
857 DWORD rc = DisMountDOSDrive(chDrive, FALSE);
867 void AddSubMount (LPTSTR pszSubmount, LPTSTR pszMapping)
869 TCHAR szRHS[ MAX_PATH ];
870 AdjustAfsPath (szRHS, pszMapping, FALSE, TRUE);
872 lstrcpy (szRHS, TEXT("/"));
874 WriteExpandedRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount, szRHS);
878 void RemoveSubMount (LPTSTR pszSubmount)
880 DeleteRegistryString(HKEY_LOCAL_MACHINE, cszSECTION_SUBMOUNTS, pszSubmount);
884 void AdjustAfsPath (LPTSTR pszTarget, LPCTSTR pszSource, BOOL fWantAFS, BOOL fWantForwardSlashes)
887 lstrcpy (pszTarget, (fWantAFS) ? cm_slash_mount_root : TEXT(""));
888 else if ((*pszSource != TEXT('/')) && (*pszSource != TEXT('\\')))
889 wsprintf (pszTarget, TEXT("%s/%s"),cm_slash_mount_root, pszSource);
890 // We don't want to strip afs off the start if it is part of something for example afscell.company.com
891 else if (fWantAFS && (lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root))) || !((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
892 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
893 (lstrlen(pszSource) == strlen(cm_slash_mount_root))))
894 wsprintf (pszTarget, TEXT("%s%s"),cm_slash_mount_root, pszSource);
895 else if (!fWantAFS && (!lstrncmpi (&pszSource[1], cm_mount_root, strlen(cm_mount_root)) && ((pszSource[strlen(cm_slash_mount_root)] == TEXT('/')) ||
896 (pszSource[strlen(cm_slash_mount_root)] == TEXT('\\')) ||
897 (lstrlen(pszSource) == strlen(cm_slash_mount_root)))))
898 lstrcpy (pszTarget, &pszSource[strlen(cm_slash_mount_root)]);
900 lstrcpy (pszTarget, pszSource);
902 for (LPTSTR pch = pszTarget; *pch; ++pch)
904 if (fWantForwardSlashes)
906 *pch = (*pch == TEXT('\\')) ? TEXT('/') : (*pch);
908 else // (!fWantForwardSlashes)
910 *pch = (*pch == TEXT('/')) ? TEXT('\\') : (*pch);
914 if (lstrlen(pszTarget) &&
915 ((pszTarget[lstrlen(pszTarget)-1] == TEXT('/')) ||
916 (pszTarget[lstrlen(pszTarget)-1] == TEXT('\\'))))
918 pszTarget[lstrlen(pszTarget)-1] = TEXT('\0');
922 BOOL GetDriveSubmount (TCHAR chDrive, LPTSTR pszSubmountNow)
924 BOOL isWinNT = IsWindowsNT();
926 TCHAR szDrive[] = TEXT("*:");
927 szDrive[0] = chDrive;
929 TCHAR szMapping[ _MAX_PATH ] = TEXT("");
931 if (isWinNT && !QueryDosDevice (szDrive, szMapping, MAX_PATH))
934 LPTSTR pszSubmount = szMapping;
936 TCHAR szNetBiosName[32];
937 memset(szNetBiosName, '\0', sizeof(szNetBiosName));
938 GetClientNetbiosName(szNetBiosName);
939 _tcscat(szNetBiosName, TEXT("\\"));
943 // Now if this is an AFS network drive mapping, {szMapping} will be:
945 // \Device\LanmanRedirector\<Drive>:\<netbiosname>\submount
947 // on Windows NT. On Windows 2000, it will be:
949 // \Device\LanmanRedirector\;<Drive>:0\<netbiosname>\submount
951 // (This is presumably to support multiple drive mappings with
954 // on Windows XP and 2003, it will be :
955 // \Device\LanmanRedirector\;<Drive>:<AuthID>\<netbiosname>\submount
957 // where : <Drive> : DOS drive letter
958 // <AuthID>: Authentication ID, 16 char hex.
959 // <netbiosname>: Netbios name of server
963 b = _tcsnicmp(szMapping, cszLANMANDEVICE, _tcslen(cszLANMANDEVICE));
965 const TCHAR ker_sub_path[] = "\\Device\\afsrdr\\";
966 b = _tcsnicmp(szMapping, ker_sub_path, _tcslen(ker_sub_path));
971 pszSubmount = &szMapping[ _tcslen(cszLANMANDEVICE) ];
973 pszSubmount = &szMapping[ _tcslen(ker_sub_path) ];
977 if (*(pszSubmount) < '0' ||
978 *(pszSubmount) > '9')
984 if (*(pszSubmount) != TEXT(';'))
989 if (toupper(*(++pszSubmount)) != chDrive)
992 if (*(++pszSubmount) != TEXT(':'))
996 // No longer a safe assumption on XP
998 if (*(++pszSubmount) != TEXT('0'))
1002 // scan for next "\"
1003 while (*(++pszSubmount) != TEXT('\\'))
1005 if (*pszSubmount==0)
1009 // note that szNetBiosName has a '\\' tagged in the end earlier
1010 for (++pszSubmount; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1011 if (!_tcsncicmp(pszSubmount, szNetBiosName, _tcslen(szNetBiosName)))
1013 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1016 pszSubmount += _tcslen(szNetBiosName);
1019 else // (!IsWindowsNT())
1021 DWORD dwSize = MAX_PATH;
1022 if (WNetGetConnection (szDrive, szMapping, &dwSize) != NO_ERROR)
1024 if (*(pszSubmount++) != TEXT('\\'))
1026 if (*(pszSubmount++) != TEXT('\\'))
1028 for ( ; *pszSubmount && (*pszSubmount != TEXT('\\')); ++pszSubmount)
1029 if (!lstrncmpi (pszSubmount, szNetBiosName, lstrlen(szNetBiosName)))
1031 if ((!*pszSubmount) || (*pszSubmount == TEXT('\\')))
1033 pszSubmount += lstrlen(szNetBiosName);
1036 if (!pszSubmount || !*pszSubmount)
1040 lstrcpy (pszSubmountNow, pszSubmount);
1042 lstrcpy (pszSubmountNow, "\\afs");
1043 lstrcat (pszSubmountNow, pszSubmount);
1048 /* Generate Random User name random acording to time*/
1050 TCHAR pUserName[MAXRANDOMNAMELEN]=TEXT("");
1051 BOOL fUserName=FALSE;
1052 #define AFSLogonOptionName TEXT(AFSREG_CLT_SVC_PROVIDER_SUBKEY)
1054 void SetBitLogonOption(BOOL set,DWORD value)
1057 RWLogonOption(FALSE,((set)?value | RWLogonOption(TRUE,0):RWLogonOption(TRUE,0) & ~value) );
1060 DWORD RWLogonOption(BOOL read,DWORD value)
1062 // if read is true then if value==0 return registry value
1063 // if read and value!=0 then use value to test registry, return TRUE if value bits match value read
1066 DWORD LSPtype, LSPsize;
1072 if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, KEY_QUERY_VALUE, &hk)==ERROR_SUCCESS)
1074 LSPsize=sizeof(rval);
1075 RegQueryValueEx(hk, "LogonOptions", NULL,
1076 &LSPtype, (LPBYTE)&rval, &LSPsize);
1079 return (value==0)?rval:((rval & value)==value);
1081 if (RegCreateKeyEx (HKEY_LOCAL_MACHINE, AFSLogonOptionName, 0, NULL, 0, KEY_SET_VALUE, NULL, &hk, &dwDisp) == ERROR_SUCCESS)
1083 RegSetValueEx(hk,TEXT("LogonOptions"),NULL,REG_DWORD,(LPBYTE)&value,sizeof(value));
1090 void MapShareName(char *pszCmdLineA)
1095 while (*pszCmdLineA && (*pszCmdLineA != ' '))
1097 *p++=*pszCmdLineA++;
1101 void GenRandomName(TCHAR *pname,int len)
1104 { //user name was passed through command line, use once
1108 srand( (unsigned)time( NULL ) );
1109 for (int i=0;i<len;i++)
1110 pname[i]='a'+(rand() % 26);
1116 Make a connection using users name
1117 if fUserName then force a connection
1120 BOOL TestAndDoMapShare(DWORD dwState)
1122 if ((dwState!=SERVICE_RUNNING) || (dwOldState!=SERVICE_START_PENDING))
1127 dwOldState=SERVICE_RUNNING;
1128 return GlobalMountDrive();
1131 BOOL IsServiceActive()
1134 SERVICE_STATUS Status;
1135 if ((hManager = OpenSCManager (NULL, NULL, GENERIC_READ)) != NULL)
1138 if ((hService = OpenService (hManager, TEXT("TransarcAFSDaemon"), GENERIC_READ)) != NULL)
1140 QueryServiceStatus (hService, &Status);
1141 CloseServiceHandle (hService);
1144 CloseServiceHandle (hManager);
1147 return (Status.dwCurrentState == SERVICE_RUNNING) ? TRUE : FALSE;
1150 void TestAndDoUnMapShare()
1155 void DoUnMapShare(BOOL drivemap) //disconnect drivemap
1157 TCHAR szMachine[MAX_PATH],szPath[MAX_PATH];
1160 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1162 DWORD cbBuffer=16384;
1166 memset(szMachine, '\0', sizeof(szMachine));
1167 GetClientNetbiosName(szMachine);
1169 // Initialize the data structure
1170 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1172 sprintf(szPath,"\\\\%s\\",szMachine);
1174 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1176 /* Reset lpnrLocal and cEntries before each call */
1177 memset(lpnrLocal,0,cbBuffer);
1180 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1182 for (DWORD i=0;i<cEntries;i++)
1184 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath))
1186 if ((lpnrLocal[i].lpLocalName) && (strlen(lpnrLocal[i].lpLocalName)>0))
1189 DisMountDOSDrive(*lpnrLocal[i].lpLocalName);
1190 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Local=%x",res);
1193 DisMountDOSDriveFull(lpnrLocal[i].lpRemoteName);
1194 DEBUG_EVENT1("AFS DriveUnMap","UnMap-Remote=%x",res);
1199 } while (res == NO_ERROR);
1200 GlobalFree((HGLOBAL)lpnrLocal);
1201 WNetCloseEnum(hEnum);
1204 BOOL DoMapShareChange(BOOL removeUnknown)
1207 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1210 LPNETRESOURCE lpnrLocal,lpnr=NULL;
1213 DWORD cbBuffer=16384;
1215 memset(szMachine, '\0', sizeof(szMachine));
1216 GetClientNetbiosName(szMachine);
1218 // Initialize the data structure
1219 if (!IsServiceActive())
1221 memset (&List, 0x00, sizeof(DRIVEMAPLIST));
1222 for (size_t ii = 0; ii < 26; ++ii)
1223 List.aDriveMap[ii].chDrive = chDRIVE_A + ii;
1224 QueryDriveMapList_ReadSubmounts (&List);
1225 if ((res=WNetOpenEnum(RESOURCE_CONNECTED,RESOURCETYPE_DISK,RESOURCEUSAGE_CONNECTABLE,lpnr,&hEnum))!=NO_ERROR)
1227 lpnrLocal=(LPNETRESOURCE) GlobalAlloc(GPTR,cbBuffer);
1228 sprintf(szPath,"\\\\%s\\",szMachine);
1231 /* Reset lpnrLocal and cEntries before each call */
1232 memset(lpnrLocal,0,cbBuffer);
1235 if ((res = WNetEnumResource(hEnum,&cEntries,lpnrLocal,&cbBuffer))==NO_ERROR)
1237 for (DWORD i=0;i<cEntries;i++)
1239 if (strstr(_strlwr(lpnrLocal[i].lpRemoteName),szPath)==NULL)
1240 continue; //only look at real afs mappings
1241 CHAR * pSubmount=strrchr(lpnrLocal[i].lpRemoteName,'\\')+1;
1242 if (lstrcmpi(pSubmount,"all")==0)
1243 continue; // do not remove 'all'
1244 for (DWORD j=0;j<List.cSubmounts;j++)
1246 if ((List.aSubmounts[j].szSubmount[0]) &&
1247 (lstrcmpi(List.aSubmounts[j].szSubmount,pSubmount)==0)
1250 List.aSubmounts[j].fInUse=TRUE;
1254 // wasn't on list so lets remove
1255 DisMountDOSDrive(pSubmount);
1259 } while (res == NO_ERROR);
1260 GlobalFree((HGLOBAL)lpnrLocal);
1261 WNetCloseEnum(hEnum);
1262 sprintf(szPath,"\\\\%s\\all",szMachine);
1264 // Lets connect all submounts that weren't connectd
1265 DWORD cbUser=MAXRANDOMNAMELEN-1;
1266 CHAR szUser[MAXRANDOMNAMELEN];
1267 CHAR * pUser = NULL;
1268 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)==NO_ERROR) {
1269 if ((pUser=strchr(szUser,'\\'))!=NULL)
1273 for (DWORD j=0;j<List.cSubmounts;j++)
1275 if (List.aSubmounts[j].fInUse)
1277 DWORD res=MountDOSDrive(0,List.aSubmounts[j].szSubmount,FALSE,pUser);
1286 BOOL bMappedAll=FALSE;
1288 // Initialize the data structure
1289 DEBUG_EVENT0("AFS DoMapShare");
1290 QueryDriveMapList (&List);
1292 // All connections have been removed
1293 // Lets restore them after making the connection from the random name
1295 TCHAR szMachine[ MAX_PATH],szPath[MAX_PATH];
1296 memset(szMachine, '\0', sizeof(szMachine));
1297 GetClientNetbiosName(szMachine);
1298 sprintf(szPath,"\\\\%s\\all",szMachine);
1300 // Lets connect all submounts that weren't connectd
1301 DWORD cbUser=MAXRANDOMNAMELEN-1;
1302 CHAR szUser[MAXRANDOMNAMELEN];
1303 CHAR * pUser = NULL;
1304 if (WNetGetUser(szPath,(LPSTR)szUser,&cbUser)==NO_ERROR) {
1305 if ((pUser=strchr(szUser,'\\'))!=NULL)
1309 for (DWORD i=0;i<List.cSubmounts;i++)
1311 if (List.aSubmounts[i].szSubmount[0])
1313 DWORD res=MountDOSDrive(0,List.aSubmounts[i].szSubmount,FALSE,pUser);
1314 if (lstrcmpi("all",List.aSubmounts[i].szSubmount)==0)
1318 if (!bMappedAll) //make sure all is mapped also
1320 DWORD res=MountDOSDrive(0,"all",FALSE,pUser);
1321 if (res==ERROR_SESSION_CREDENTIAL_CONFLICT)
1323 DisMountDOSDrive("all");
1324 MountDOSDrive(0,"all",FALSE,pUser);
1327 for (TCHAR chDrive = chDRIVE_A; chDrive <= chDRIVE_Z; ++chDrive)
1329 if (List.aDriveMap[chDrive-chDRIVE_A].fActive ||
1330 ForceMapActive(chDrive))
1332 TCHAR szSubmount[ MAX_PATH ];
1333 if (List.aDriveMap[chDrive-chDRIVE_A].szSubmount[0])
1334 lstrcpy(szSubmount,List.aDriveMap[chDrive-chDRIVE_A].szSubmount);
1335 else if (!PathToSubmount (szSubmount, List.aDriveMap[chDrive-chDRIVE_A].szMapping, NULL, NULL))
1338 BOOL fPersistent = List.aDriveMap[chDrive-chDRIVE_A].fPersistent;
1339 DWORD res=MountDOSDrive(chDrive
1341 ,fPersistent,pUser);
1347 BOOL GlobalMountDrive()
1349 char szDriveToMapTo[5];
1351 char szKeyName[256];
1355 DWORD dwSubMountSize;
1356 char unsigned szSubMount[256];
1357 char cm_HostName[200];
1358 DWORD dwType=sizeof(cm_HostName);
1359 if (!IsServiceActive())
1361 if (!GetComputerName(cm_HostName, &dwType))
1363 sprintf(szKeyName, "%s\\GlobalAutoMapper", AFSREG_CLT_SVC_PARAM_SUBKEY);
1365 dwResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, szKeyName, 0, KEY_QUERY_VALUE,
1367 if (dwResult != ERROR_SUCCESS)
1371 dwDriveSize = sizeof(szDriveToMapTo);
1372 dwSubMountSize = sizeof(szSubMount);
1373 dwResult = RegEnumValue(hKey, dwIndex++, szDriveToMapTo, &dwDriveSize,
1374 0, &dwType, szSubMount, &dwSubMountSize);
1375 if (dwResult != ERROR_MORE_DATA) {
1376 if (dwResult != ERROR_SUCCESS) {
1377 if (dwResult != ERROR_NO_MORE_ITEMS)
1379 DEBUG_EVENT1("AFS DriveMap","Failed to read GlobalAutoMapper values: %d",dwResult);
1384 dwResult=MountDOSDrive(*szDriveToMapTo,(const char *)szSubMount,FALSE,NULL);
1390 DWORD MountDOSDrive(char chDrive,const char *szSubmount,BOOL bPersistent,const char * pUsername)
1395 TCHAR szTokens[MAX_PATH], *tok;
1397 TCHAR szPath[MAX_PATH];
1398 TCHAR szClient[MAX_PATH];
1399 TCHAR szDrive[3] = TEXT("?:");
1402 int pathCount, currPos, lastPos, x;
1407 strcpy(szTokens, szSubmount);
1408 tok = strtok(szTokens, "/\\");
1412 if (pathCount || stricmp(tok, "afs"))
1414 strcat(szPath, "\\");
1415 strcat(szPath, tok);
1418 tok = strtok(NULL, "/\\");
1421 sprintf(szDrive,"%c:",chDrive);
1422 strcpy(szTokens, szPath);
1423 sprintf(szPath,"\\Device\\afsrdr\\%d%s",pathCount,szTokens);
1424 //succ = DefineDosDevice(DDD_RAW_TARGET_PATH, "J:", "\\Device\\afsrdr\\2\\ericjw\\test");
1425 succ = DefineDosDevice(DDD_RAW_TARGET_PATH, szDrive, szPath);
1426 err = GetLastError();
1428 return succ ? NO_ERROR : ERROR_DEVICE_IN_USE;
1430 sprintf(szDrive,"%c:",chDrive);
1431 GetClientNetbiosName (szClient);
1432 sprintf(szPath,"\\\\%s\\%s",szClient,szSubmount);
1434 memset (&nr, 0x00, sizeof(NETRESOURCE));
1435 nr.dwType=RESOURCETYPE_DISK;
1436 nr.lpLocalName=szDrive;
1437 nr.lpRemoteName=szPath;
1438 nr.dwDisplayType = RESOURCEDISPLAYTYPE_SHARE; /* ignored parameter */
1439 DWORD res=WNetAddConnection2(&nr,NULL,pUsername,(bPersistent)?CONNECT_UPDATE_PROFILE:0);
1440 DEBUG_EVENT5("AFS DriveMap","Mount %s Local[%s] Remote[%s] User[%s]=%x",
1441 (bPersistent)?"Persistant" : "NonPresistant",
1442 szDrive,szPath,pUsername?pUsername:"NULL",res);
1447 DWORD DisMountDOSDriveFull(const char *szPath,BOOL bForce)
1450 DWORD res=WNetCancelConnection(szPath,bForce);
1453 res = ERROR_DEVICE_IN_USE;
1454 // must handle drive letters and afs paths
1455 // DDD_REMOVE_DEFINITION
1457 DEBUG_EVENT3("AFS DriveMap","%sDismount Remote[%s]=%x",
1458 bForce ? "Forced " : "",szPath,res);
1459 return (res==ERROR_NOT_CONNECTED)?NO_ERROR:res;
1462 DWORD DisMountDOSDrive(const char *pSubmount,BOOL bForce)
1464 TCHAR szPath[MAX_PATH];
1465 TCHAR szClient[MAX_PATH];
1466 GetClientNetbiosName (szClient);
1467 sprintf(szPath,"\\\\%s\\%s",szClient,pSubmount);
1468 return DisMountDOSDriveFull(szPath,bForce);
1472 DWORD DisMountDOSDrive(const char chDrive,BOOL bForce)
1474 TCHAR szPath[MAX_PATH];
1478 sprintf(szPath,"%c:",chDrive);
1480 succ = DefineDosDevice(DDD_REMOVE_DEFINITION, szPath, NULL);
1481 return (!succ) ? GetLastError() : 0;
1483 return DisMountDOSDriveFull(szPath,bForce);