Exemple #1
0
        private static NativeMethods.SECURITY_INFORMATION ToSecurityInfo(PreserveSMBPermissions preserveSMBPermissions)
        {
            uint securityInfo = 0;

            if (PreserveSMBPermissions.Owner == (preserveSMBPermissions & PreserveSMBPermissions.Owner))
            {
                securityInfo |= (uint)NativeMethods.SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION;
            }

            if (PreserveSMBPermissions.Group == (preserveSMBPermissions & PreserveSMBPermissions.Group))
            {
                securityInfo |= (uint)NativeMethods.SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION;
            }

            if (PreserveSMBPermissions.DACL == (preserveSMBPermissions & PreserveSMBPermissions.DACL))
            {
                securityInfo |= (uint)NativeMethods.SECURITY_INFORMATION.DACL_SECURITY_INFORMATION;
            }

            if (PreserveSMBPermissions.SACL == (preserveSMBPermissions & PreserveSMBPermissions.SACL))
            {
                securityInfo |= (uint)NativeMethods.SECURITY_INFORMATION.SACL_SECURITY_INFORMATION;
            }

            return((NativeMethods.SECURITY_INFORMATION)(securityInfo));
        }
 public static void SetFileSecurityInfo(string path, string portableSDDL, PreserveSMBPermissions preserveSMBPermissions)
 {
     try
     {
         path = DMLibTestConstants.SupportUNCPath ?
                LongPath.GetFullPath(LongPath.ToUncPath(path)) :
                LongPath.GetFullPath(path);
     }
     catch (Exception)
     { }
     FileSecurityOperations.SetFileSecurity(path, portableSDDL, preserveSMBPermissions);
 }
        /// <summary>
        /// Restore privileges enabled before for getting/setting local file permissions.
        /// </summary>
        /// <param name="preserveSMBPermissions">Permissions types to be preserved.</param>
        /// <param name="setLocalFilePermission">Indicating whether to set permission to local file.
        /// Setting owner info to local file would need specific privilege, while getting owner info doesn't require this privilege.</param>
        public static void RestorePrivileges(PreserveSMBPermissions preserveSMBPermissions, bool setLocalFilePermission)
        {
            if (PreserveSMBPermissions.SACL == (preserveSMBPermissions & PreserveSMBPermissions.SACL))
            {
                if (!SACLPrivilegeEnabledOriginal)
                {
                    try
                    {
                        SetPrivilege(FileSecurityNativeMethods.SACLPrivilegeName, false);
                    }
                    catch (Win32Exception)
                    {
                        // Ignore the exception
                        // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                        // Failure on disabling the privilege won't impact transfer result.
                    }
                    catch (COMException)
                    {
                        // Ignore the exception
                        // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                        // Failure on disabling the privilege won't impact transfer result.
                    }
                }
            }

            if (!setLocalFilePermission)
            {
                return;
            }

            if (PreserveSMBPermissions.Owner == (preserveSMBPermissions & PreserveSMBPermissions.Owner))
            {
                if (!OwnerPrivilegeEnabledOriginal)
                {
                    try
                    {
                        SetPrivilege(FileSecurityNativeMethods.OwnerPrivilegeName, false);
                    }
                    catch (Win32Exception)
                    {
                        // Ignore the exception
                        // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                        // Failure on disabling the privilege won't impact transfer result.
                    }
                    catch (COMException)
                    {
                        // Ignore the exception
                        // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                        // Failure on disabling the privilege won't impact transfer result.
                    }
                }
            }
        }
 public static string GetFilePortableSDDL(string path, PreserveSMBPermissions preserveSMBPermissions)
 {
     try
     {
         path = DMLibTestConstants.SupportUNCPath ?
                LongPath.GetFullPath(LongPath.ToUncPath(path)) :
                LongPath.GetFullPath(path);
     }
     catch (Exception)
     { }
     return(FileSecurityOperations.GetFilePortableSDDL(path, preserveSMBPermissions));
 }
        public static void SetFileSecurity(string filePath, string portableSDDL, PreserveSMBPermissions preserveSMBPermissions)
        {
            if (PreserveSMBPermissions.None == preserveSMBPermissions)
            {
                return;
            }

            if (string.IsNullOrEmpty(portableSDDL))
            {
                return;
            }

            IntPtr  pSecurityDescriptor      = new IntPtr();
            UIntPtr securityDescriptorLength = new UIntPtr();

            if (!FileSecurityNativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(portableSDDL,
                                                                                               FileSecurityNativeMethods.SDDL_REVISION_1,
                                                                                               out pSecurityDescriptor,
                                                                                               out securityDescriptorLength))
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            try
            {
                FileSecurityNativeMethods.SetFileSecurity(filePath,
                                                          (int)(ToSecurityInfo(preserveSMBPermissions)),
                                                          pSecurityDescriptor);

                int errorCode = Marshal.GetLastWin32Error();
                int hresult   = Marshal.GetHRForLastWin32Error();

                if ((errorCode == FileSecurityNativeMethods.ERROR_PRIVILEGE_NOT_HELD) ||
                    (errorCode == FileSecurityNativeMethods.ERROR_ACCESS_DENIED) ||
                    (errorCode == FileSecurityNativeMethods.ERROR_INVALID_OWNER))
                {
                    throw new Win32Exception(errorCode);
                }

                if (errorCode != 0)
                {
                    Marshal.ThrowExceptionForHR(hresult);
                }
            }
            finally
            {
                FileSecurityNativeMethods.LocalFree(pSecurityDescriptor);
            }
        }
        public static string GetFilePortableSDDL(
            string filePath,
            PreserveSMBPermissions preserveSMBPermissions)
        {
            if (preserveSMBPermissions == PreserveSMBPermissions.None)
            {
                return(null);
            }

            string sddl      = GetFileSDDL(filePath, ToSecurityInfo(preserveSMBPermissions));
            string userName  = GetUserName();
            string domainSid = GetDomainSid(userName);

            return(GetPortableSDDL(sddl, domainSid));
        }
        /// <summary>
        /// Enable privileges required for getting/setting premissions from/to local file.
        /// </summary>
        /// <param name="preserveSMBPermissions">Permissions types to be preserved.</param>
        /// <param name="setLocalFilePermission">Indicating whether to set permission to local file.
        /// Setting owner info to local file would need specific privilege, while getting owner info doesn't require this privilege.</param>
        public static void EnableRequiredPrivileges(PreserveSMBPermissions preserveSMBPermissions, bool setLocalFilePermission)
        {
            if (PreserveSMBPermissions.SACL == (preserveSMBPermissions & PreserveSMBPermissions.SACL))
            {
                if (!SACLPrivilegeEnabledOriginal)
                {
                    try
                    {
                        SACLPrivilegeEnabledOriginal = SetPrivilege(FileSecurityNativeMethods.SACLPrivilegeName, true);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }

            if (!setLocalFilePermission)
            {
                return;
            }

            if (PreserveSMBPermissions.Owner == (preserveSMBPermissions & PreserveSMBPermissions.Owner))
            {
                if (!OwnerPrivilegeEnabledOriginal)
                {
                    try
                    {
                        OwnerPrivilegeEnabledOriginal = SetPrivilege(FileSecurityNativeMethods.OwnerPrivilegeName, true);
                    }
                    catch (COMException)
                    {
                        // Ignore exception here
                        // Under some condition, setting owner info to local file will still success even when there's no SeRestorePrivilege privilege.
                        // So here only try to enable the privilege. Later, if it fails to set owner info to local file, reports error for the specific file.
                        return;
                    }
                    catch (TransferException)
                    {
                        // Ignore exception here
                        // Under some condition, setting owner info to local file will still success even when there's no SeRestorePrivilege privilege.
                        // So here only try to enable the privilege. Later, if it fails to set owner info to local file, reports error for the specific file.
                        return;
                    }
                }
            }
        }
Exemple #8
0
        public static string GetFilePortableSDDL(
            string filePath,
            PreserveSMBPermissions preserveSMBPermissions)
        {
#if DEBUG
            if (null != TestHookCallbacks.GetFilePermissionsCallback)
            {
                return(TestHookCallbacks.GetFilePermissionsCallback(filePath, preserveSMBPermissions));
            }
#endif

            if (preserveSMBPermissions == PreserveSMBPermissions.None)
            {
                return(null);
            }

            string sddl      = GetFileSDDL(filePath, ToSecurityInfo(preserveSMBPermissions));
            string userName  = GetUserName();
            string domainSid = GetDomainSid(userName);
            return(GetPortableSDDL(sddl, domainSid));
        }
Exemple #9
0
        public void TestDirectoryPreserveSMBPermissionsResume()
        {
            if (!CrossPlatformHelpers.IsWindows)
            {
                return;
            }

            PreserveSMBPermissions preserveSMBPermissions =
                PreserveSMBPermissions.Owner
                | PreserveSMBPermissions.Group
                | PreserveSMBPermissions.DACL;

            string sampleSDDL = "O:S-1-5-21-2146773085-903363285-719344707-1375029G:S-1-5-21-2146773085-903363285-719344707-513D:(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)(A;OICIIOID;GA;;;SY)(A;ID;0x1301bf;;;AU)(A;OICIIOID;SDGXGWGR;;;AU)(A;ID;0x1200a9;;;BU)(A;OICIIOID;GXGR;;;BU)";
            CancellationTokenSource tokenSource  = new CancellationTokenSource();
            TransferItem            transferItem = null;

            bool IsStreamJournal = random.Next(0, 2) == 0;

            using (Stream journalStream = new MemoryStream())
            {
                // Prepare data
                DMLibDataInfo sourceDataInfo = new DMLibDataInfo("");
                GenerateDirNodeWithPermissions(sourceDataInfo.RootNode, 2, sampleSDDL);

                DirectoryTransferContext dirTransferContext = null;

                if (IsStreamJournal)
                {
                    dirTransferContext = new DirectoryTransferContext(journalStream);
                }
                else
                {
                    dirTransferContext = new DirectoryTransferContext();
                }

                var progressChecker = new ProgressChecker(14, 14 * 1024);
                dirTransferContext.ProgressHandler = progressChecker.GetProgressHandler();

                var options = new TestExecutionOptions <DMLibDataInfo>();
                options.IsDirectoryTransfer = true;

                options.TransferItemModifier = (fileNode, item) =>
                {
                    item.TransferContext = dirTransferContext;

                    dynamic transferOptions = DefaultTransferDirectoryOptions;
                    transferOptions.Recursive = true;
                    transferOptions.PreserveSMBPermissions = preserveSMBPermissions;
                    item.Options           = transferOptions;
                    item.CancellationToken = tokenSource.Token;
                    transferItem           = item;
                };

                TransferCheckpoint checkpoint = null;

                options.AfterAllItemAdded = () =>
                {
                    // Wait until there are data transferred
                    progressChecker.DataTransferred.WaitOne();

                    if (!IsStreamJournal)
                    {
                        checkpoint = dirTransferContext.LastCheckpoint;
                    }

                    // Cancel the transfer and store the second checkpoint
                    tokenSource.Cancel();
                };

#if DEBUG
                TestHookCallbacks.UnderTesting = true;
                TestHookCallbacks.GetFilePermissionsCallback = (path, SMBPermissionType) =>
                {
                    Test.Assert(SMBPermissionType == preserveSMBPermissions, "The SMB permission type should be expected.");
                    return(sampleSDDL);
                };

                TestHookCallbacks.SetFilePermissionsCallback = (path, portableSDDL, SMBPermissionType) =>
                {
                    Test.Assert(SMBPermissionType == preserveSMBPermissions, "The SMB permission type should be expected.");
                    Test.Assert(portableSDDL.StartsWith(sampleSDDL),
                                "The SDDL value should be expected.");
                };
#endif

                try
                {
                    // Execute test case
                    var result = this.ExecuteTestCase(sourceDataInfo, options);

                    Test.Assert(result.Exceptions.Count == 1, "Verify job is cancelled");
                    Exception exception = result.Exceptions[0];
                    Helper.VerifyCancelException(exception);

                    TransferItem             resumeItem    = transferItem.Clone();
                    DirectoryTransferContext resumeContext = null;
                    journalStream.Position = 0;
                    if (IsStreamJournal)
                    {
                        resumeContext = new DirectoryTransferContext(journalStream);
                    }
                    else
                    {
                        resumeContext = new DirectoryTransferContext(DMLibTestHelper.RandomReloadCheckpoint(checkpoint));
                    }

                    resumeItem.TransferContext = resumeContext;

                    result = this.RunTransferItems(new List <TransferItem>()
                    {
                        resumeItem
                    }, new TestExecutionOptions <DMLibDataInfo>());
                    VerificationHelper.VerifyTransferSucceed(result, sourceDataInfo);

                    if (DMLibTestContext.DestType == DMLibDataType.CloudFile)
                    {
                        Helper.CompareSMBPermissions(sourceDataInfo.RootNode, result.DataInfo.RootNode, preserveSMBPermissions);
                    }
                }
                finally
                {
#if DEBUG
                    TestHookCallbacks.UnderTesting = false;
                    TestHookCallbacks.GetFilePermissionsCallback = null;
                    TestHookCallbacks.SetFilePermissionsCallback = null;
#endif
                }
            }
        }
Exemple #10
0
        public void TestPreserveSMBPermissions()
        {
            if (!CrossPlatformHelpers.IsWindows)
            {
                return;
            }

            try
            {
                PreserveSMBPermissions preserveSMBPermissions =
                    PreserveSMBPermissions.Owner
                    | PreserveSMBPermissions.Group
                    | PreserveSMBPermissions.DACL;
                string sampleSDDL = "O:S-1-5-21-2146773085-903363285-719344707-1375029G:S-1-5-21-2146773085-903363285-719344707-513D:(A;ID;FA;;;BA)(A;OICIIOID;GA;;;BA)(A;ID;FA;;;SY)(A;OICIIOID;GA;;;SY)(A;ID;0x1301bf;;;AU)(A;OICIIOID;SDGXGWGR;;;AU)(A;ID;0x1200a9;;;BU)(A;OICIIOID;GXGR;;;BU)";

#if DEBUG
                TestHookCallbacks.UnderTesting = true;
                TestHookCallbacks.GetFilePermissionsCallback = (path, SMBPermissionType) =>
                {
                    Test.Assert(SMBPermissionType == preserveSMBPermissions, "The SMB permission type should be expected.");
                    return(sampleSDDL);
                };

                TestHookCallbacks.SetFilePermissionsCallback = (path, portableSDDL, SMBPermissionType) =>
                {
                    Test.Assert(SMBPermissionType == preserveSMBPermissions, "The SMB permission type should be expected.");
                    Test.Assert(portableSDDL.StartsWith(sampleSDDL),
                                "The SDDL value should be expected.");
                };
#endif

                // Prepare data
                DMLibDataInfo sourceDataInfo = new DMLibDataInfo("");
                FileNode      fileNode       = new FileNode(DMLibTestBase.FileName);
                fileNode.SizeInByte   = 1024;
                fileNode.PortableSDDL = sampleSDDL;
                sourceDataInfo.RootNode.AddFileNode(fileNode);

                SingleTransferContext transferContext = new SingleTransferContext();

                var options = new TestExecutionOptions <DMLibDataInfo>();

                options.TransferItemModifier = (fileNodeVar, transferItem) =>
                {
                    transferItem.TransferContext = transferContext;

                    dynamic transferOptions = DefaultTransferOptions;
                    transferOptions.PreserveSMBPermissions = preserveSMBPermissions;
                    transferItem.Options = transferOptions;
                };

                // Execute test case
                var result = this.ExecuteTestCase(sourceDataInfo, options);

                VerificationHelper.VerifyTransferSucceed(result, sourceDataInfo);

                if (DMLibTestContext.DestType == DMLibDataType.CloudFile)
                {
                    Helper.CompareSMBPermissions(sourceDataInfo.RootNode, result.DataInfo.RootNode, preserveSMBPermissions);
                }
            }
            finally
            {
#if DEBUG
                TestHookCallbacks.UnderTesting = false;
                TestHookCallbacks.GetFilePermissionsCallback = null;
                TestHookCallbacks.SetFilePermissionsCallback = null;
#endif
            }
        }
Exemple #11
0
        private void GenerateFile(FileNode fileNode, string parentPath, bool handleSMBAttributes = false, PreserveSMBPermissions getPermissions = PreserveSMBPermissions.None)
        {
            this.CheckFileNode(fileNode);

            string localFilePath = Path.Combine(parentPath, fileNode.Name);

            DMLibDataHelper.CreateLocalFile(fileNode, localFilePath);

            if (handleSMBAttributes)
            {
                LongPathFileExtension.SetAttributes(localFilePath, Helper.ToFileAttributes(fileNode.SMBAttributes.Value));
            }

#if DOTNET5_4
            FileInfo fileInfo = new FileInfo(localFilePath);

            this.BuildFileNode(fileInfo, fileNode, handleSMBAttributes, getPermissions);
#else
            this.BuildFileNode(localFilePath, fileNode, handleSMBAttributes, getPermissions);
#endif
        }
Exemple #12
0
        /// <summary>
        /// This method should be invoked at the end of transfer job handling, to disable privileges which are enabled at the beginning of the transfer job.
        /// Getting/setting premissions from/to local file may need some specific privileges.
        /// These privileges should be enabled at the beginning of a transfer job, and disbled at the end of the transfer job.
        /// </summary>
        /// <param name="preserveSMBPermissions">Permissions types to be preserved.</param>
        /// <param name="setLocalFilePermission">Indicating whether to set permission to local file.
        /// Setting owner info to local file would need specific privilege, while getting owner info doesn't require this privilege.</param>
        public static void EnableRequiredPrivileges(PreserveSMBPermissions preserveSMBPermissions, bool setLocalFilePermission)
        {
#if DEBUG
            if (TestHookCallbacks.UnderTesting)
            {
                return;
            }
#endif

            if (PreserveSMBPermissions.SACL == (preserveSMBPermissions & PreserveSMBPermissions.SACL))
            {
                if (!SACLPrivilegeEnabledOriginal)
                {
                    lock (SACLPrivilegeLock)
                    {
                        if (SACLPrivilegeEnabledOriginal)
                        {
                            return;
                        }

                        ++SACLPrivilegeJobCount;

                        if (SACLPrivilegeEnabled)
                        {
                            return;
                        }

                        try
                        {
                            SACLPrivilegeEnabledOriginal = SetPrivilege(NativeMethods.SACLPrivilegeName, true);
                        }
                        catch (Exception)
                        {
                            --SACLPrivilegeJobCount;
                            throw;
                        }

                        SACLPrivilegeEnabled = true;

                        if (SACLPrivilegeEnabledOriginal)
                        {
                            --SACLPrivilegeJobCount;
                        }
                    }
                }
            }

            if (!setLocalFilePermission)
            {
                return;
            }

            if (PreserveSMBPermissions.Owner == (preserveSMBPermissions & PreserveSMBPermissions.Owner))
            {
                if (!OwnerPrivilegeEnabledOriginal)
                {
                    lock (OwnerPrivilegeLock)
                    {
                        if (OwnerPrivilegeEnabledOriginal)
                        {
                            return;
                        }

                        ++OwnerPrivilegeJobCount;

                        if (OwnerPrivilegeEnabled)
                        {
                            return;
                        }

                        try
                        {
                            OwnerPrivilegeEnabledOriginal = SetPrivilege(NativeMethods.OwnerPrivilegeName, true);
                        }
                        catch (COMException)
                        {
                            // Ignore exception here
                            // Under some condition, setting owner info to local file will still success even when there's no SeRestorePrivilege privilege.
                            // So here only try to enable the privilege. Later, if it fails to set owner info to local file, reports error for the specific file.
                            --OwnerPrivilegeJobCount;
                            return;
                        }
                        catch (TransferException)
                        {
                            // Ignore exception here
                            // Under some condition, setting owner info to local file will still success even when there's no SeRestorePrivilege privilege.
                            // So here only try to enable the privilege. Later, if it fails to set owner info to local file, reports error for the specific file.
                            --OwnerPrivilegeJobCount;
                            return;
                        }

                        OwnerPrivilegeEnabled = true;

                        if (OwnerPrivilegeEnabledOriginal)
                        {
                            --OwnerPrivilegeJobCount;
                        }
                    }
                }
            }
        }
Exemple #13
0
        public static void SetFileSecurity(string filePath, string portableSDDL, PreserveSMBPermissions preserveSMBPermissions)
        {
#if DEBUG
            if (null != TestHookCallbacks.SetFilePermissionsCallback)
            {
                TestHookCallbacks.SetFilePermissionsCallback(filePath, portableSDDL, preserveSMBPermissions);
                return;
            }
#endif

            filePath = LongPath.ToUncPath(filePath);

            if (PreserveSMBPermissions.None == preserveSMBPermissions)
            {
                return;
            }

            if (string.IsNullOrEmpty(portableSDDL))
            {
                return;
            }

            IntPtr  pSecurityDescriptor      = new IntPtr();
            UIntPtr securityDescriptorLength = new UIntPtr();

            if (!NativeMethods.ConvertStringSecurityDescriptorToSecurityDescriptor(portableSDDL,
                                                                                   NativeMethods.SDDL_REVISION_1,
                                                                                   out pSecurityDescriptor,
                                                                                   out securityDescriptorLength))
            {
                throw Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            try
            {
                NativeMethods.SetFileSecurity(filePath,
                                              (int)(ToSecurityInfo(preserveSMBPermissions)),
                                              pSecurityDescriptor);

                int errorCode = Marshal.GetLastWin32Error();
                int hresult   = Marshal.GetHRForLastWin32Error();

                if ((errorCode == NativeMethods.ERROR_PRIVILEGE_NOT_HELD) ||
                    (errorCode == NativeMethods.ERROR_ACCESS_DENIED) ||
                    (errorCode == NativeMethods.ERROR_INVALID_OWNER))
                {
#if !DMLIB_TEST
                    string privilegeName = null;

                    if ((preserveSMBPermissions & PreserveSMBPermissions.Owner) == PreserveSMBPermissions.Owner)
                    {
                        privilegeName = NativeMethods.OwnerPrivilegeName;
                    }

                    if ((preserveSMBPermissions & PreserveSMBPermissions.SACL) == PreserveSMBPermissions.SACL)
                    {
                        if (null == privilegeName)
                        {
                            privilegeName = NativeMethods.SACLPrivilegeName;
                        }
                        else
                        {
                            privilegeName += " ";
                            privilegeName += NativeMethods.SACLPrivilegeName;
                        }
                    }

                    if (null != privilegeName)
                    {
                        throw new TransferException(
                                  string.Format(
                                      CultureInfo.CurrentCulture,
                                      Resources.PrivilegeRequiredException,
                                      privilegeName));
                    }
#else
                    throw new Win32Exception(errorCode);
#endif
                }

                if (errorCode != 0)
                {
                    Marshal.ThrowExceptionForHR(hresult);
                }
            }
            finally
            {
                NativeMethods.LocalFree(pSecurityDescriptor);
            }
        }
Exemple #14
0
        /// <summary>
        /// This method should be invoked at the end of transfer job handling, to disable privileges which are enabled at the beginning of the transfer job.
        /// Getting/setting premissions from/to local file may need some specific privileges.
        /// These privileges should be enabled at the beginning of a transfer job, and disbled at the end of the transfer job.
        /// </summary>
        /// <param name="preserveSMBPermissions">Permissions types to be preserved.</param>
        /// <param name="setLocalFilePermission">Indicating whether to set permission to local file.
        /// Setting owner info to local file would need specific privilege, while getting owner info doesn't require this privilege.</param>
        public static void DisablePrivileges(PreserveSMBPermissions preserveSMBPermissions, bool setLocalFilePermission)
        {
#if DEBUG
            if (TestHookCallbacks.UnderTesting)
            {
                return;
            }
#endif

            if (PreserveSMBPermissions.SACL == (preserveSMBPermissions & PreserveSMBPermissions.SACL))
            {
                if (!SACLPrivilegeEnabledOriginal)
                {
                    lock (SACLPrivilegeLock)
                    {
                        if (SACLPrivilegeEnabledOriginal)
                        {
                            return;
                        }

                        --SACLPrivilegeJobCount;

                        if (0 == SACLPrivilegeJobCount)
                        {
                            try
                            {
                                SetPrivilege(NativeMethods.SACLPrivilegeName, false);
                            }
                            catch (TransferException)
                            {
                                // Ignore the exception
                                // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                                // Failure on disabling the privilege won't impact transfer result.
                            }
                            catch (COMException)
                            {
                                // Ignore the exception
                                // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                                // Failure on disabling the privilege won't impact transfer result.
                            }

                            SACLPrivilegeEnabled = false;
                        }
                    }
                }
            }

            if (!setLocalFilePermission)
            {
                return;
            }

            if (PreserveSMBPermissions.Owner == (preserveSMBPermissions & PreserveSMBPermissions.Owner))
            {
                if (!OwnerPrivilegeEnabledOriginal)
                {
                    lock (OwnerPrivilegeLock)
                    {
                        if (!OwnerPrivilegeEnabled ||
                            OwnerPrivilegeEnabledOriginal)
                        {
                            return;
                        }

                        --OwnerPrivilegeJobCount;

                        if (0 == OwnerPrivilegeJobCount)
                        {
                            try
                            {
                                SetPrivilege(NativeMethods.OwnerPrivilegeName, false);
                            }
                            catch (TransferException)
                            {
                                // Ignore the exception
                                // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                                // Failure on disabling the privilege won't impact transfer result.
                            }
                            catch (COMException)
                            {
                                // Ignore the exception
                                // Here just try to clear up the privileges which may have been enabled at the very beginning of a tranfer job.
                                // Failure on disabling the privilege won't impact transfer result.
                            }

                            OwnerPrivilegeEnabled = false;
                        }
                    }
                }
            }
        }
Exemple #15
0
        private void BuildDirNode(DirectoryInfo dirInfo, DirNode parent, bool handleSMBAttributes = false, PreserveSMBPermissions preserveSMBPermissions = PreserveSMBPermissions.None)
        {
            DateTimeOffset?creationTime   = null;
            DateTimeOffset?lastWriteTime  = null;
            FileAttributes?fileAttributes = null;

#if DOTNET5_4
            LongPathFileExtension.GetFileProperties(dirInfo.FullName, out creationTime, out lastWriteTime, out fileAttributes, true);
#else
            LongPathFileExtension.GetFileProperties(dirInfo.FullName, out creationTime, out lastWriteTime, out fileAttributes);
#endif
            parent.CreationTime  = creationTime;
            parent.LastWriteTime = lastWriteTime;

            foreach (FileInfo fileInfo in dirInfo.GetFiles())
            {
                FileNode fileNode = new FileNode(fileInfo.Name);
                this.BuildFileNode(fileInfo, fileNode, handleSMBAttributes, preserveSMBPermissions);
                parent.AddFileNode(fileNode);
            }

            foreach (DirectoryInfo subDirInfo in dirInfo.GetDirectories())
            {
                DirNode subDirNode = new DirNode(subDirInfo.Name);
                this.BuildDirNode(subDirInfo, subDirNode, handleSMBAttributes, preserveSMBPermissions);
                parent.AddDirNode(subDirNode);
            }
        }
Exemple #16
0
        private void GenerateDir(DirNode dirNode, string parentPath, bool handleSMBAttributes = false, PreserveSMBPermissions getPermissions = PreserveSMBPermissions.None)
        {
            string dirPath = Path.Combine(parentPath, dirNode.Name);

            if (!string.IsNullOrEmpty(dirNode.Content))
            {
                CreateSymlink(dirPath, dirNode.Content);

                Test.Info("Building symlinked dir info of {0}", dirPath);
                dirNode.BuildSymlinkedDirNode();
                return;
            }

            DMLibDataHelper.CreateLocalDirIfNotExists(dirPath);

            foreach (var file in dirNode.FileNodes)
            {
                GenerateFile(file, dirPath, handleSMBAttributes, getPermissions);
            }

            foreach (var subDir in dirNode.NormalDirNodes)
            {
                GenerateDir(subDir, dirPath, handleSMBAttributes, getPermissions);
            }

            foreach (var subDir in dirNode.SymlinkedDirNodes)
            {
                CreateSymlink(Path.Combine(dirPath, subDir.Name), subDir.Content);

                Test.Info("Building symlinked dir info of {0}", Path.Combine(dirPath, subDir.Name));
                subDir.BuildSymlinkedDirNode();
            }
        }
Exemple #17
0
 public static string GetFilePortableSDDL(string path, PreserveSMBPermissions preserveSMBPermissions)
 {
     return(FileSecurityOperations.GetFilePortableSDDL(path, preserveSMBPermissions));
 }
Exemple #18
0
        private void BuildDirNode(string dirPath, DirNode parent, bool handleSMBAttributes, PreserveSMBPermissions getSMBPermissions)
        {
            dirPath = AppendDirectorySeparator(dirPath);

            DateTimeOffset?creationTime   = null;
            DateTimeOffset?lastWriteTime  = null;
            FileAttributes?fileAttributes = null;

#if DOTNET5_4
            LongPathFileExtension.GetFileProperties(dirPath, out creationTime, out lastWriteTime, out fileAttributes, true);
#else
            LongPathFileExtension.GetFileProperties(dirPath, out creationTime, out lastWriteTime, out fileAttributes);
#endif

            parent.CreationTime  = creationTime;
            parent.LastWriteTime = lastWriteTime;

            if (PreserveSMBPermissions.None != getSMBPermissions)
            {
                parent.PortableSDDL = LongPathFileExtension.GetFilePortableSDDL(dirPath, getSMBPermissions);
            }

            foreach (var fileInfo in LongPathDirectoryExtension.GetFiles(dirPath))
            {
                FileNode fileNode = new FileNode(fileInfo.Remove(0, dirPath.Length));
                this.BuildFileNode(fileInfo, fileNode, handleSMBAttributes, getSMBPermissions);
                parent.AddFileNode(fileNode);
            }

            foreach (var subDirInfo in LongPathDirectoryExtension.GetDirectories(dirPath))
            {
                DirNode subDirNode = new DirNode(subDirInfo.Remove(0, dirPath.Length));
                this.BuildDirNode(subDirInfo, subDirNode, handleSMBAttributes, getSMBPermissions);
                parent.AddDirNode(subDirNode);
            }
        }
Exemple #19
0
        private void BuildFileNode(FileInfo fileInfo, FileNode fileNode, bool handleSMBAttributes, PreserveSMBPermissions getPermissions)
        {
            fileNode.MD5 = Helper.GetFileContentMD5(fileInfo.FullName);
            fileNode.LastModifiedTime = fileInfo.LastWriteTimeUtc;
            fileNode.SizeInByte       = fileInfo.Length;
            fileNode.Metadata         = new Dictionary <string, string>();

            if (CrossPlatformHelpers.IsWindows)
            {
                DateTimeOffset?creationTime   = null;
                DateTimeOffset?lastWriteTime  = null;
                FileAttributes?fileAttributes = null;
                LongPathFileExtension.GetFileProperties(fileInfo.FullName, out creationTime, out lastWriteTime, out fileAttributes);

                fileNode.CreationTime  = creationTime;
                fileNode.LastWriteTime = lastWriteTime;

                if (handleSMBAttributes)
                {
                    fileNode.SMBAttributes = Helper.ToCloudFileNtfsAttributes(fileAttributes.Value);
                }

                if (PreserveSMBPermissions.None != getPermissions)
                {
                    fileNode.PortableSDDL = LongPathFileExtension.GetFilePortableSDDL(fileInfo.FullName, getPermissions);
                }
            }
        }
Exemple #20
0
 public void GenerateDataInfo(DMLibDataInfo dataInfo, bool handleSMBAttributes, PreserveSMBPermissions getPermissions)
 {
     this.GenerateDir(dataInfo.RootNode, Path.Combine(this.BasePath, dataInfo.RootPath), handleSMBAttributes, getPermissions);
 }
Exemple #21
0
        private void BuildFileNode(string path, FileNode fileNode, bool handleSMBAttributes, PreserveSMBPermissions getPermissions)
        {
            fileNode.MD5 = Helper.GetFileContentMD5(LongPathExtension.GetFullPath(path));
            // fileNode.LastModifiedTime =
            using (FileStream fs = LongPathFileExtension.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                fileNode.SizeInByte = fs.Length;
            }

            DateTimeOffset?creationTime   = null;
            DateTimeOffset?lastWriteTime  = null;
            FileAttributes?fileAttributes = null;

            LongPathFileExtension.GetFileProperties(path, out creationTime, out lastWriteTime, out fileAttributes);

            fileNode.CreationTime  = creationTime;
            fileNode.LastWriteTime = lastWriteTime;

            if (handleSMBAttributes)
            {
                fileNode.SMBAttributes = Helper.ToCloudFileNtfsAttributes(fileAttributes.Value);
            }

            if (PreserveSMBPermissions.None != getPermissions)
            {
                fileNode.PortableSDDL = LongPathFileExtension.GetFilePortableSDDL(path, getPermissions);
            }

            fileNode.Metadata = new Dictionary <string, string>();
        }
Exemple #22
0
 public static void SetFileSecurityInfo(string path, string portableSDDL, PreserveSMBPermissions preserveSMBPermissions)
 {
     FileSecurityOperations.SetFileSecurity(path, portableSDDL, preserveSMBPermissions);
 }
Exemple #23
0
        public DMLibDataInfo GetTransferDataInfo(string rootDir, bool handleSMBAttributes, PreserveSMBPermissions getSMBPermissions)
        {
#if DOTNET5_4
            DirectoryInfo rootDirInfo = new DirectoryInfo(Path.Combine(this.BasePath, rootDir));
            if (!rootDirInfo.Exists)
            {
                return(null);
            }
#else
            string rootDirInfo = rootDir;
            if (rootDir.Length == 0)
            {
                rootDirInfo = LongPathExtension.Combine(this.BasePath, rootDir);
            }
            if (!LongPathDirectoryExtension.Exists(rootDirInfo))
            {
                return(null);
            }
#endif
            DMLibDataInfo dataInfo = new DMLibDataInfo(rootDir);
            this.BuildDirNode(rootDirInfo, dataInfo.RootNode, handleSMBAttributes, getSMBPermissions);

            return(dataInfo);
        }