private void CreateStreams(string filePath, string streamName, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, Encoding fileEncoding)
        {
            if (File.Exists(filePath) && (this.provider.Force != 0))
            {
                this.oldAttributes     = File.GetAttributes(filePath);
                this.haveOldAttributes = true;
                System.IO.FileAttributes hidden = System.IO.FileAttributes.Hidden;
                if ((fileAccess & FileAccess.Write) != 0)
                {
                    hidden |= System.IO.FileAttributes.ReadOnly;
                }
                File.SetAttributes(this.path, File.GetAttributes(filePath) & ~hidden);
            }
            FileAccess access = fileAccess;

            if ((fileAccess & FileAccess.Write) != 0)
            {
                fileAccess = FileAccess.ReadWrite;
            }
            try
            {
                if (!string.IsNullOrEmpty(streamName))
                {
                    this.stream = AlternateDataStreamUtilities.CreateFileStream(filePath, streamName, fileMode, fileAccess, fileShare);
                }
                else
                {
                    this.stream = new FileStream(filePath, fileMode, fileAccess, fileShare);
                }
            }
            catch (IOException)
            {
                if (!string.IsNullOrEmpty(streamName))
                {
                    this.stream = AlternateDataStreamUtilities.CreateFileStream(filePath, streamName, fileMode, access, fileShare);
                }
                else
                {
                    this.stream = new FileStream(filePath, fileMode, access, fileShare);
                }
            }
            if (!this.usingByteEncoding)
            {
                if ((fileAccess & FileAccess.Read) != 0)
                {
                    this.reader      = new StreamReader(this.stream, fileEncoding);
                    this._backReader = new FileStreamBackReader(this.stream, fileEncoding);
                }
                if ((fileAccess & FileAccess.Write) != 0)
                {
                    if ((this.reader != null) && ((fileAccess & FileAccess.Read) != 0))
                    {
                        this.reader.Peek();
                        fileEncoding = this.reader.CurrentEncoding;
                    }
                    this.writer = new StreamWriter(this.stream, fileEncoding);
                }
            }
        }
Esempio n. 2
0
        /// <summary>
        /// Generate the type(s)
        /// </summary>
        protected override void ProcessRecord()
        {
            List <string> pathsToProcess = new List <string>();
            ProviderInfo  provider       = null;

            if (String.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase))
            {
                foreach (string path in _paths)
                {
                    string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);

                    if (IsValidFileForUnblocking(newPath))
                    {
                        pathsToProcess.Add(newPath);
                    }
                }
            }
            else
            {
                // Resolve paths
                foreach (string path in _paths)
                {
                    try
                    {
                        Collection <string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);

                        foreach (string currentFilepath in newPaths)
                        {
                            if (IsValidFileForUnblocking(currentFilepath))
                            {
                                pathsToProcess.Add(currentFilepath);
                            }
                        }
                    }
                    catch (ItemNotFoundException e)
                    {
                        if (!WildcardPattern.ContainsWildcardCharacters(path))
                        {
                            ErrorRecord errorRecord = new ErrorRecord(e,
                                                                      "FileNotFound",
                                                                      ErrorCategory.ObjectNotFound,
                                                                      path);
                            WriteError(errorRecord);
                        }
                    }
                }
            }

            // Unblock files
            foreach (string path in pathsToProcess)
            {
                if (ShouldProcess(path))
                {
                    AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier");
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Read the 'Zone.Identifier' alternate data stream to determin SecurityZone of the file.
        /// </summary>
        private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath)
        {
            if (!AlternateDataStreamUtilities.TryCreateFileStream(filePath, "Zone.Identifier", FileMode.Open, FileAccess.Read, FileShare.Read, out var zoneDataStream))
            {
                return(SecurityZone.NoZone);
            }

            // If we successfully get the zone data stream, try to read the ZoneId information
            using (StreamReader zoneDataReader = new StreamReader(zoneDataStream, GetDefaultEncoding()))
            {
                string line = null;
                bool   zoneTransferMatched = false;

                // After a lot experiments with Zone.CreateFromUrl/Zone.SecurityZone, the way it handles the alternate
                // data stream 'Zone.Identifier' is observed as follows:
                //    1. Read content of the data stream line by line. Each line is trimmed.
                //    2. Try to match the current line with '^\[ZoneTransfer\]'.
                //           - if matching, then do step #3 starting from the next line
                //           - if not matching, then continue to do step #2 with the next line.
                //    3. Try to match the current line with '^ZoneId\s*=\s*(.*)'
                //           - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if valid, or 'NoZone' if invalid.
                //           - if not matching, then continue to do step #3 with the next line.
                //    4. Reach EOF, then return 'NoZone'.
                while ((line = zoneDataReader.ReadLine()) != null)
                {
                    line = line.Trim();
                    if (!zoneTransferMatched)
                    {
                        zoneTransferMatched = Regex.IsMatch(line, @"^\[ZoneTransfer\]", RegexOptions.IgnoreCase);
                    }
                    else
                    {
                        Match match = Regex.Match(line, @"^ZoneId\s*=\s*(.*)", RegexOptions.IgnoreCase);
                        if (!match.Success)
                        {
                            continue;
                        }

                        // Match found. Validate ZoneId value.
                        string zoneIdRawValue = match.Groups[1].Value;
                        match = Regex.Match(zoneIdRawValue, @"^[+-]?\d+", RegexOptions.IgnoreCase);
                        if (!match.Success)
                        {
                            return(SecurityZone.NoZone);
                        }

                        string       zoneId = match.Groups[0].Value;
                        SecurityZone result;
                        return(LanguagePrimitives.TryConvertTo(zoneId, out result) ? result : SecurityZone.NoZone);
                    }
                }
            }

            return(SecurityZone.NoZone);
        }
Esempio n. 4
0
        protected override void ProcessRecord()
        {
            List <string> list     = new List <string>();
            ProviderInfo  provider = null;

            if (string.Equals(base.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase))
            {
                foreach (string str in this.paths)
                {
                    string unresolvedProviderPathFromPSPath = base.Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(str);
                    if (this.IsValidFileForUnblocking(unresolvedProviderPathFromPSPath))
                    {
                        list.Add(unresolvedProviderPathFromPSPath);
                    }
                }
            }
            else
            {
                foreach (string str3 in this.paths)
                {
                    try
                    {
                        foreach (string str4 in base.Context.SessionState.Path.GetResolvedProviderPathFromPSPath(str3, out provider))
                        {
                            if (this.IsValidFileForUnblocking(str4))
                            {
                                list.Add(str4);
                            }
                        }
                    }
                    catch (ItemNotFoundException exception)
                    {
                        if (!WildcardPattern.ContainsWildcardCharacters(str3))
                        {
                            ErrorRecord errorRecord = new ErrorRecord(exception, "FileNotFound", ErrorCategory.ObjectNotFound, str3);
                            base.WriteError(errorRecord);
                        }
                    }
                }
            }
            foreach (string str5 in list)
            {
                if (base.ShouldProcess(str5))
                {
                    AlternateDataStreamUtilities.DeleteFileStream(str5, "Zone.Identifier");
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Generate the type(s)
        /// </summary>
        protected override void ProcessRecord()
        {
            List <string> pathsToProcess = new();
            ProviderInfo  provider       = null;

            if (string.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase))
            {
                foreach (string path in _paths)
                {
                    string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);

                    if (IsValidFileForUnblocking(newPath))
                    {
                        pathsToProcess.Add(newPath);
                    }
                }
            }
            else
            {
                // Resolve paths
                foreach (string path in _paths)
                {
                    try
                    {
                        Collection <string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);

                        foreach (string currentFilepath in newPaths)
                        {
                            if (IsValidFileForUnblocking(currentFilepath))
                            {
                                pathsToProcess.Add(currentFilepath);
                            }
                        }
                    }
                    catch (ItemNotFoundException e)
                    {
                        if (!WildcardPattern.ContainsWildcardCharacters(path))
                        {
                            ErrorRecord errorRecord = new(e,
                                                          "FileNotFound",
                                                          ErrorCategory.ObjectNotFound,
                                                          path);
                            WriteError(errorRecord);
                        }
                    }
                }
            }
#if !UNIX
            // Unblock files
            foreach (string path in pathsToProcess)
            {
                if (ShouldProcess(path))
                {
                    try
                    {
                        AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier");
                    }
                    catch (Exception e)
                    {
                        WriteError(new ErrorRecord(exception: e, errorId: "RemoveItemUnableToAccessFile", ErrorCategory.ResourceUnavailable, targetObject: path));
                    }
                }
            }
#else
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
            {
                string    errorMessage = UnblockFileStrings.LinuxNotSupported;
                Exception e            = new PlatformNotSupportedException(errorMessage);
                ThrowTerminatingError(new ErrorRecord(exception: e, errorId: "LinuxNotSupported", ErrorCategory.NotImplemented, targetObject: null));
                return;
            }

            foreach (string path in pathsToProcess)
            {
                if (IsBlocked(path))
                {
                    UInt32 result = RemoveXattr(path, MacBlockAttribute, RemovexattrFollowSymLink);
                    if (result != 0)
                    {
                        string    errorMessage = string.Format(CultureInfo.CurrentUICulture, UnblockFileStrings.UnblockError, path);
                        Exception e            = new InvalidOperationException(errorMessage);
                        WriteError(new ErrorRecord(exception: e, errorId: "UnblockError", ErrorCategory.InvalidResult, targetObject: path));
                    }
                }
            }
#endif
        }
Esempio n. 6
0
        /// <summary>
        /// Generate the type(s)
        /// </summary>
        protected override void ProcessRecord()
        {
            List <string> pathsToProcess = new List <string>();
            ProviderInfo  provider       = null;

            if (String.Equals(this.ParameterSetName, "ByLiteralPath", StringComparison.OrdinalIgnoreCase))
            {
                foreach (string path in _paths)
                {
                    string newPath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);

                    if (IsValidFileForUnblocking(newPath))
                    {
                        pathsToProcess.Add(newPath);
                    }
                }
            }
            else
            {
                // Resolve paths
                foreach (string path in _paths)
                {
                    try
                    {
                        Collection <string> newPaths = Context.SessionState.Path.GetResolvedProviderPathFromPSPath(path, out provider);

                        foreach (string currentFilepath in newPaths)
                        {
                            if (IsValidFileForUnblocking(currentFilepath))
                            {
                                pathsToProcess.Add(currentFilepath);
                            }
                        }
                    }
                    catch (ItemNotFoundException e)
                    {
                        if (!WildcardPattern.ContainsWildcardCharacters(path))
                        {
                            ErrorRecord errorRecord = new ErrorRecord(e,
                                                                      "FileNotFound",
                                                                      ErrorCategory.ObjectNotFound,
                                                                      path);
                            WriteError(errorRecord);
                        }
                    }
                }
            }

            // Unblock files
            foreach (string path in pathsToProcess)
            {
                if (ShouldProcess(path))
                {
                    try
                    {
                        AlternateDataStreamUtilities.DeleteFileStream(path, "Zone.Identifier");
                    }
                    catch (Win32Exception accessException)
                    {
                        // NativeErrorCode=2 - File not found.
                        // If the block stream not found the 'path' was not blocked and we successfully return.
                        if (accessException.NativeErrorCode != 2)
                        {
                            WriteError(new ErrorRecord(accessException, "RemoveItemUnauthorizedAccessError", ErrorCategory.PermissionDenied, path));
                        }
                        else
                        {
                            WriteVerbose(StringUtil.Format(UtilityCommonStrings.NoZoneIdentifierFileStream, path));
                        }
                    }
                }
            }
        }