Exemplo n.º 1
0
		internal static void Init(Scriptable scope, bool @sealed)
		{
			NativeError obj = new NativeError();
			ScriptableObject.PutProperty(obj, "name", "Error");
			ScriptableObject.PutProperty(obj, "message", string.Empty);
			ScriptableObject.PutProperty(obj, "fileName", string.Empty);
			ScriptableObject.PutProperty(obj, "lineNumber", Sharpen.Extensions.ValueOf(0));
			obj.ExportAsJSClass(MAX_PROTOTYPE_ID, scope, @sealed);
		}
Exemplo n.º 2
0
        public BackupStreamInfo ReadStreamInfo()
        {
            var sizeOf = Marshal.SizeOf(typeof(NativeMethods.WIN32_STREAM_ID));

            using (var hBuf = new SafeGlobalMemoryBufferHandle(sizeOf))
            {
                uint numberOfBytesRead;

                var success = NativeMethods.BackupRead(SafeFileHandle, hBuf, (uint)sizeOf, out numberOfBytesRead, false, _processSecurity, ref _context);

                var lastError = Marshal.GetLastWin32Error();
                if (!success)
                {
                    NativeError.ThrowException(lastError);
                }


                if (numberOfBytesRead == 0)
                {
                    return(null);
                }


                if (numberOfBytesRead < sizeOf)
                {
                    throw new IOException(Resources.Read_Incomplete_Header);
                }


                var streamID   = hBuf.PtrToStructure <NativeMethods.WIN32_STREAM_ID>(0);
                var nameLength = (uint)Math.Min(streamID.dwStreamNameSize, hBuf.Capacity);


                success = NativeMethods.BackupRead(SafeFileHandle, hBuf, nameLength, out numberOfBytesRead, false, _processSecurity, ref _context);

                lastError = Marshal.GetLastWin32Error();
                if (!success)
                {
                    NativeError.ThrowException(lastError);
                }


                var name = hBuf.PtrToStringUni(0, (int)nameLength / UnicodeEncoding.CharSize);

                return(new BackupStreamInfo(streamID, name));
            }
        }
Exemplo n.º 3
0
        public FileSecurity GetAccessControl()
        {
            IntPtr pSidOwner, pSidGroup, pDacl, pSacl;
            SafeGlobalMemoryBufferHandle pSecurityDescriptor;

            uint lastError = SecurityNativeMethods.GetSecurityInfo(SafeFileHandle, ObjectType.FileObject,
                                                                   SecurityInformation.Group | SecurityInformation.Owner | SecurityInformation.Label | SecurityInformation.Dacl | SecurityInformation.Sacl,
                                                                   out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor);

            try
            {
                if (lastError != Win32Errors.ERROR_SUCCESS)
                {
                    NativeError.ThrowException((int)lastError);
                }

                if (pSecurityDescriptor != null && pSecurityDescriptor.IsInvalid)
                {
                    pSecurityDescriptor.Close();
                    throw new IOException(Resources.Returned_Invalid_Security_Descriptor);
                }

                uint length = SecurityNativeMethods.GetSecurityDescriptorLength(pSecurityDescriptor);

                byte[] managedBuffer = new byte[length];


                // .CopyTo() does not work there?
                if (pSecurityDescriptor != null)
                {
                    pSecurityDescriptor.CopyTo(managedBuffer, 0, (int)length);
                }


                var fs = new FileSecurity();
                fs.SetSecurityDescriptorBinaryForm(managedBuffer);

                return(fs);
            }
            finally
            {
                if (pSecurityDescriptor != null)
                {
                    pSecurityDescriptor.Close();
                }
            }
        }
        private void ThrowPossibleException(uint lastError, string pathLp)
        {
            switch (lastError)
            {
            case Win32Errors.ERROR_NO_MORE_FILES:
                lastError = Win32Errors.NO_ERROR;
                break;


            case Win32Errors.ERROR_FILE_NOT_FOUND: // On files.
            case Win32Errors.ERROR_PATH_NOT_FOUND: // On folders.
            case Win32Errors.ERROR_NOT_READY:      // DeviceNotReadyException: Floppy device or network drive not ready.
                // MSDN: .NET 3.5+: DirectoryNotFoundException: Path is invalid, such as referring to an unmapped drive.
                // Directory.Delete()

                lastError = IsDirectory ? (int)Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND;
                break;


                //case Win32Errors.ERROR_DIRECTORY:
                //   // MSDN: .NET 3.5+: IOException: path is a file name.
                //   // Directory.EnumerateDirectories()
                //   // Directory.EnumerateFiles()
                //   // Directory.EnumerateFileSystemEntries()
                //   // Directory.GetDirectories()
                //   // Directory.GetFiles()
                //   // Directory.GetFileSystemEntries()
                //   break;

                //case Win32Errors.ERROR_ACCESS_DENIED:
                //   // MSDN: .NET 3.5+: UnauthorizedAccessException: The caller does not have the required permission.
                //   break;
            }


            if (lastError != Win32Errors.NO_ERROR)
            {
                var regularPath = Path.GetCleanExceptionPath(pathLp);

                // Pass control to the ErrorHandler when set.
                if (null == ErrorHandler || !ErrorHandler((int)lastError, new Win32Exception((int)lastError).Message, regularPath))
                {
                    // When the ErrorHandler returns false, thrown the Exception.
                    NativeError.ThrowException(lastError, regularPath);
                }
            }
        }
        internal static void ImportEncryptedFileRawCore(System.IO.Stream inputStream, string destinationFilePath, PathFormat pathFormat, NativeMethods.EncryptedFileRawMode mode)
        {
            string lpPath = Path.GetExtendedLengthPathCore(null, destinationFilePath, pathFormat, GetFullPathOptions.FullCheck | GetFullPathOptions.TrimEnd);
            SafeEncryptedFileRawHandle context = null;
            int errorCode = NativeMethods.OpenEncryptedFileRaw(lpPath, mode, out context);

            try
            {
                if (errorCode != Win32Errors.ERROR_SUCCESS)
                {
                    NativeError.ThrowException(errorCode, null, destinationFilePath);
                }

                errorCode = NativeMethods.WriteEncryptedFileRaw((IntPtr pbData, IntPtr pvCallbackContext, ref uint ulLength) =>
                {
                    try
                    {
                        byte[] buffer = new byte[ulLength];
                        ulLength      = (uint)inputStream.Read(buffer, 0, (int)ulLength);
                        if (ulLength == 0)
                        {
                            return((int)Win32Errors.ERROR_SUCCESS);
                        }

                        Marshal.Copy(buffer, 0, pbData, (int)ulLength);
                    }
                    catch (Exception ex)
                    {
                        return(Marshal.GetHRForException(ex));
                    }

                    return((int)Win32Errors.ERROR_SUCCESS);
                }, IntPtr.Zero, context);

                if (errorCode != Win32Errors.ERROR_SUCCESS)
                {
                    NativeError.ThrowException(errorCode, null, destinationFilePath);
                }
            }
            finally
            {
                if (context != null)
                {
                    context.Dispose();
                }
            }
        }
        public static void SetVolumeMountPoint(string volumeMountPoint, string volumeGuid)
        {
            if (Utils.IsNullOrWhiteSpace(volumeMountPoint))
            {
                throw new ArgumentNullException("volumeMountPoint");
            }

            if (Utils.IsNullOrWhiteSpace(volumeGuid))
            {
                throw new ArgumentNullException("volumeGuid");
            }

            if (!volumeGuid.StartsWith(Path.VolumePrefix + "{", StringComparison.OrdinalIgnoreCase))
            {
                throw new ArgumentException(Resources.Not_A_Valid_Guid, "volumeGuid");
            }


            volumeMountPoint = Path.GetFullPathCore(null, volumeMountPoint, GetFullPathOptions.AsLongPath | GetFullPathOptions.AddTrailingDirectorySeparator | GetFullPathOptions.FullCheck);


            // This string must be of the form "\\?\Volume{GUID}\"
            volumeGuid = Path.AddTrailingDirectorySeparator(volumeGuid, false);


            // ChangeErrorMode is for the Win32 SetThreadErrorMode() method, used to suppress possible pop-ups.
            using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            {
                // SetVolumeMountPoint()
                // 2014-01-29: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

                // The string must end with a trailing backslash.
                var success = NativeMethods.SetVolumeMountPoint(volumeMountPoint, volumeGuid);

                var lastError = Marshal.GetLastWin32Error();
                if (!success)
                {
                    // If the lpszVolumeMountPoint parameter contains a path to a mounted folder,
                    // GetLastError returns ERROR_DIR_NOT_EMPTY, even if the directory is empty.

                    if (lastError != Win32Errors.ERROR_DIR_NOT_EMPTY)
                    {
                        NativeError.ThrowException(lastError, volumeGuid);
                    }
                }
            }
        }
Exemplo n.º 7
0
        public FileSecurity GetAccessControl()
        {
            IntPtr pSidOwner, pSidGroup, pDacl, pSacl;
            SafeGlobalMemoryBufferHandle pSecurityDescriptor;

            var lastError = (int)SecurityNativeMethods.GetSecurityInfo(SafeFileHandle, SE_OBJECT_TYPE.SE_FILE_OBJECT, SECURITY_INFORMATION.GROUP_SECURITY_INFORMATION | SECURITY_INFORMATION.OWNER_SECURITY_INFORMATION | SECURITY_INFORMATION.LABEL_SECURITY_INFORMATION | SECURITY_INFORMATION.DACL_SECURITY_INFORMATION | SECURITY_INFORMATION.SACL_SECURITY_INFORMATION, out pSidOwner, out pSidGroup, out pDacl, out pSacl, out pSecurityDescriptor);

            try
            {
                if (lastError != Win32Errors.ERROR_SUCCESS)
                {
                    NativeError.ThrowException(lastError);
                }

                if (null != pSecurityDescriptor && pSecurityDescriptor.IsInvalid)
                {
                    pSecurityDescriptor.Close();
                    pSecurityDescriptor = null;

                    throw new IOException(new Win32Exception((int)Win32Errors.ERROR_INVALID_SECURITY_DESCR).Message);
                }


                var length        = SecurityNativeMethods.GetSecurityDescriptorLength(pSecurityDescriptor);
                var managedBuffer = new byte[length];


                // .CopyTo() does not work there?
                if (null != pSecurityDescriptor)
                {
                    pSecurityDescriptor.CopyTo(managedBuffer, 0, (int)length);
                }


                var fs = new FileSecurity();
                fs.SetSecurityDescriptorBinaryForm(managedBuffer);

                return(fs);
            }
            finally
            {
                if (null != pSecurityDescriptor)
                {
                    pSecurityDescriptor.Close();
                }
            }
        }
Exemplo n.º 8
0
        internal static void SetFsoDateTimeInternal(bool isFolder, KernelTransaction transaction, string path, DateTime?creationTimeUtc, DateTime?lastAccessTimeUtc, DateTime?lastWriteTimeUtc, PathFormat pathFormat)
        {
            // Because we already check here, use false for CreateFileInternal() to prevent another check.
            if (pathFormat == PathFormat.RelativePath)
            {
                Path.CheckValidPath(path, false, false);
            }

            using (SafeGlobalMemoryBufferHandle creationTime = SafeGlobalMemoryBufferHandle.FromLong(creationTimeUtc.HasValue ? creationTimeUtc.Value.ToFileTimeUtc() : (long?)null))
                using (SafeGlobalMemoryBufferHandle lastAccessTime = SafeGlobalMemoryBufferHandle.FromLong(lastAccessTimeUtc.HasValue ? lastAccessTimeUtc.Value.ToFileTimeUtc() : (long?)null))
                    using (SafeGlobalMemoryBufferHandle lastWriteTime = SafeGlobalMemoryBufferHandle.FromLong(lastWriteTimeUtc.HasValue ? lastWriteTimeUtc.Value.ToFileTimeUtc() : (long?)null))
                        using (SafeFileHandle safeHandle = CreateFileInternal(transaction, path, isFolder ? ExtendedFileAttributes.BackupSemantics : ExtendedFileAttributes.Normal, null, FileMode.Open, FileSystemRights.WriteAttributes, FileShare.Delete | FileShare.Write, false, pathFormat))
                            if (!NativeMethods.SetFileTime(safeHandle, creationTime, lastAccessTime, lastWriteTime))
                            {
                                NativeError.ThrowException(path);
                            }
        }
Exemplo n.º 9
0
        public static void SetCurrentVolumeLabel(string volumeName)
        {
            if (Utils.IsNullOrWhiteSpace(volumeName))
            {
                throw new ArgumentNullException("volumeName");
            }


            var success = NativeMethods.SetVolumeLabel(null, volumeName);

            var lastError = Marshal.GetLastWin32Error();

            if (!success)
            {
                NativeError.ThrowException(lastError, volumeName);
            }
        }
Exemplo n.º 10
0
Arquivo: Path.cs Projeto: CDEApp/CDE
        public static string GetLongFrom83ShortPath(string path)
        {
            System.Text.StringBuilder buffer = new System.Text.StringBuilder(path.Length);
            int actualLength = NativeMethods.GetShortPathNameW(path, buffer, buffer.Capacity);

            while (actualLength > buffer.Capacity)
            {
                buffer       = new System.Text.StringBuilder(actualLength);
                actualLength = NativeMethods.GetLongPathNameW(path, buffer, buffer.Capacity);
            }
            if (actualLength <= 0)
            {
                NativeError.ThrowException(path, path);
            }

            return(buffer.ToString());
        }
Exemplo n.º 11
0
        public virtual void Unlock(long position, long length)
        {
            if (position < 0)
            {
                throw new ArgumentOutOfRangeException("position", position, Resources.BackupFileStream_Unlock_Backup_FileStream_Unlock_Position_must_not_be_negative_);
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", length, Resources.BackupFileStream_Unlock_Backup_FileStream_Lock_Length_must_not_be_negative_);
            }

            if (!NativeMethods.UnlockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length)))
            {
                NativeError.ThrowException(Marshal.GetLastWin32Error());
            }
        }
Exemplo n.º 12
0
        public long Skip(long bytes)
        {
            uint lowSought, highSought;

            if (!NativeMethods.BackupSeek(SafeFileHandle, NativeMethods.GetLowOrderDword(bytes), NativeMethods.GetHighOrderDword(bytes), out lowSought, out highSought, ref _context))
            {
                int lastError = Marshal.GetLastWin32Error();

                // Error Code 25 indicates a seek error, we just skip that here.
                if (lastError != Win32Errors.NO_ERROR && lastError != Win32Errors.ERROR_SEEK)
                {
                    NativeError.ThrowException(lastError);
                }
            }

            return(NativeMethods.ToLong(highSought, lowSought));
        }
Exemplo n.º 13
0
        internal static void ReplaceCore(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors, PathFormat pathFormat)
        {
            const GetFullPathOptions options = GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck;

            var sourceFileNameLp      = sourceFileName;
            var destinationFileNameLp = destinationFileName;


            if (pathFormat != PathFormat.LongFullPath)
            {
                sourceFileNameLp      = Path.GetExtendedLengthPathCore(null, sourceFileName, pathFormat, options);
                destinationFileNameLp = Path.GetExtendedLengthPathCore(null, destinationFileName, pathFormat, options);
            }


            // Pass null to the destinationBackupFileName parameter if you do not want to create a backup of the file being replaced.
            var destinationBackupFileNameLp = null == destinationBackupFileName
            ? null
            : Path.GetExtendedLengthPathCore(null, destinationBackupFileName, pathFormat, options);


            const int replacefileWriteThrough      = 1;
            const int replacefileIgnoreMergeErrors = 2;


            var dwReplaceFlags = (FileSystemRights)replacefileWriteThrough;

            if (ignoreMetadataErrors)
            {
                dwReplaceFlags |= (FileSystemRights)replacefileIgnoreMergeErrors;
            }


            // ReplaceFile()
            // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.
            // 2017-05-30: MSDN confirms LongPath usage: Starting with Windows 10, version 1607

            var success = NativeMethods.ReplaceFile(destinationFileNameLp, sourceFileNameLp, destinationBackupFileNameLp, dwReplaceFlags, IntPtr.Zero, IntPtr.Zero);

            var lastError = (uint)Marshal.GetLastWin32Error();

            if (!success)
            {
                NativeError.ThrowException(lastError, sourceFileNameLp, destinationFileNameLp);
            }
        }
Exemplo n.º 14
0
        private static void InvokeIoControlUnknownSize <T>(SafeFileHandle handle, uint controlCode, T input, uint increment = 128)
        {
            //byte[] output;
            //uint bytesReturned;
            var inputSize    = (uint)Marshal.SizeOf(input);
            var outputLength = increment;

            do
            {
                var  output = new byte[outputLength];
                uint bytesReturned;

                var success = NativeMethods.DeviceIoControlUnknownSize(handle, controlCode, input, inputSize, output, outputLength, out bytesReturned, IntPtr.Zero);

                var lastError = Marshal.GetLastWin32Error();
                if (!success)
                {
                    switch ((uint)lastError)
                    {
                    case Win32Errors.ERROR_MORE_DATA:
                    case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
                        outputLength += increment;
                        break;

                    default:
                        NativeError.ThrowException(lastError);
                        break;
                    }
                }
                else
                {
                    break;
                }
            } while (true);


            // 2017-06-28: Disabled; results are currently not used.

            //// Return the result.
            //if (output.Length == bytesReturned)
            //   return output;

            //var res = new byte[bytesReturned];
            //Array.Copy(output, res, bytesReturned);
            //return res;
        }
Exemplo n.º 15
0
        public long Skip(long bytes)
        {
            uint lowSought, highSought;

            if (!NativeMethods.BackupSeek(mFileHandle, NativeMethods.GetLowOrderDword(bytes), NativeMethods.GetHighOrderDword(bytes),
                                          out lowSought, out highSought, ref mContext))
            {
                int errorCode = Marshal.GetLastWin32Error();

                // Error Code 25 indicates a seek error, we just skip that here.
                if (errorCode != 0 && errorCode != 25)
                {
                    NativeError.ThrowException(errorCode);
                }
            }
            return(((long)lowSought & 0xFFFFFFFF) | ((long)highSought << 32));
        }
Exemplo n.º 16
0
        public void Unlock(long position, long length)
        {
            if (position < 0)
            {
                throw new ArgumentOutOfRangeException("position", position, Resources.Unlock_Position_Negative);
            }

            if (length < 0)
            {
                throw new ArgumentOutOfRangeException("length", length, Resources.Negative_Lock_Length);
            }

            if (!NativeMethods.UnlockFile(SafeFileHandle, NativeMethods.GetLowOrderDword(position), NativeMethods.GetHighOrderDword(position), NativeMethods.GetLowOrderDword(length), NativeMethods.GetHighOrderDword(length)))
            {
                NativeError.ThrowException(Marshal.GetLastWin32Error());
            }
        }
		/// <summary>
		/// This method is called by the <see cref="AppenderSkeleton.DoAppend"/> method.
		/// </summary>
		/// <param name="loggingEvent">The event to log.</param>
		/// <remarks>
		/// <para>
		/// Sends the event using a network message.
		/// </para>
		/// </remarks>
		protected override void Append(LoggingEvent loggingEvent) 
		{
			string renderedLoggingEvent = RenderLoggingEvent(loggingEvent);

			// Send the message
			int returnValue = NetMessageBufferSend(this.Server, this.Recipient, this.Sender, renderedLoggingEvent, renderedLoggingEvent.Length * Marshal.SystemDefaultCharSize);   

			// Log the error if the message could not be sent
			if (returnValue != 0) 
			{
				// Lookup the native error
				NativeError nativeError = NativeError.GetError(returnValue);

				// Handle the error over to the ErrorHandler
				ErrorHandler.Error(nativeError.ToString() + " (Params: Server=" + this.Server + ", Recipient=" + this.Recipient + ", Sender=" + this.Sender + ")");
			}
		}
Exemplo n.º 18
0
        private static NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA GetDeviceInterfaceDetail(SafeHandle safeHandle, ref NativeMethods.SP_DEVICE_INTERFACE_DATA interfaceData, ref NativeMethods.SP_DEVINFO_DATA infoData)
        {
            var didd = new NativeMethods.SP_DEVICE_INTERFACE_DETAIL_DATA {
                cbSize = (uint)(IntPtr.Size == 4 ? 6 : 8)
            };

            var success = NativeMethods.SetupDiGetDeviceInterfaceDetail(safeHandle, ref interfaceData, ref didd, (uint)Marshal.SizeOf(didd), IntPtr.Zero, ref infoData);

            var lastError = Marshal.GetLastWin32Error();

            if (!success)
            {
                NativeError.ThrowException(lastError);
            }

            return(didd);
        }
Exemplo n.º 19
0
        public static string GetVolumePathName(string path)
        {
            if (Utils.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }


            using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
            {
                var volumeRootPath = new StringBuilder(NativeMethods.MaxPathUnicode / 32);
                var pathLp         = Path.GetFullPathCore(null, path, GetFullPathOptions.AsLongPath | GetFullPathOptions.FullCheck);


                // GetVolumePathName()
                // 2013-07-18: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

                var success = NativeMethods.GetVolumePathName(pathLp, volumeRootPath, (uint)volumeRootPath.Capacity);

                var lastError = Marshal.GetLastWin32Error();

                if (success)
                {
                    return(Path.GetRegularPathCore(volumeRootPath.ToString(), GetFullPathOptions.None, false));
                }


                switch ((uint)lastError)
                {
                // Don't throw exception on these errors.
                case Win32Errors.ERROR_NO_MORE_FILES:
                case Win32Errors.ERROR_INVALID_PARAMETER:
                case Win32Errors.ERROR_INVALID_NAME:
                    break;

                default:
                    NativeError.ThrowException(lastError, path);
                    break;
                }


                // Return original path.
                return(path);
            }
        }
        private static T GetSecurityDescriptor <T>(uint lastError, bool isFolder, string path, SafeGlobalMemoryBufferHandle securityDescriptor)
        {
            ObjectSecurity objectSecurity;

            using (securityDescriptor)
            {
                if (lastError == Win32Errors.ERROR_FILE_NOT_FOUND || lastError == Win32Errors.ERROR_PATH_NOT_FOUND)
                {
                    lastError = isFolder ? Win32Errors.ERROR_PATH_NOT_FOUND : Win32Errors.ERROR_FILE_NOT_FOUND;
                }


                // If the function fails, the return value is zero.
                if (lastError != Win32Errors.ERROR_SUCCESS)
                {
                    if (!Utils.IsNullOrWhiteSpace(path))
                    {
                        NativeError.ThrowException(lastError, path);
                    }
                    else
                    {
                        NativeError.ThrowException((int)lastError);
                    }
                }

                if (!NativeMethods.IsValidHandle(securityDescriptor, false))
                {
                    throw new IOException(Resources.Returned_Invalid_Security_Descriptor);
                }


                uint length = Security.NativeMethods.GetSecurityDescriptorLength(securityDescriptor);

                // Seems not to work: Method .CopyTo: length > Capacity, so an Exception is thrown.
                //byte[] managedBuffer = new byte[length];
                //pSecurityDescriptor.CopyTo(managedBuffer, 0, (int) length);

                byte[] managedBuffer = securityDescriptor.ToByteArray(0, (int)length);

                objectSecurity = isFolder ? (ObjectSecurity) new DirectorySecurity() : new FileSecurity();
                objectSecurity.SetSecurityDescriptorBinaryForm(managedBuffer);
            }

            return((T)(object)objectSecurity);
        }
Exemplo n.º 21
0
        public static ByHandleFileInfo GetFileInfoByHandle(SafeFileHandle handle)
        {
            NativeMethods.IsValidHandle(handle);

            NativeMethods.BY_HANDLE_FILE_INFORMATION info;

            var success = NativeMethods.GetFileInformationByHandle(handle, out info);

            var lastError = Marshal.GetLastWin32Error();

            if (!success)
            {
                NativeError.ThrowException(lastError);
            }


            return(new ByHandleFileInfo(info));
        }
Exemplo n.º 22
0
        private static SafeGlobalMemoryBufferHandle GetLinkTargetData(SafeFileHandle safeHandle, string reparsePath)
        {
            var safeBuffer = new SafeGlobalMemoryBufferHandle(NativeMethods.MAXIMUM_REPARSE_DATA_BUFFER_SIZE);

            while (true)
            {
                uint bytesReturned;
                var  success = NativeMethods.DeviceIoControl(safeHandle, NativeMethods.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, safeBuffer, (uint)safeBuffer.Capacity, out bytesReturned, IntPtr.Zero);

                var lastError = Marshal.GetLastWin32Error();
                if (!success)
                {
                    switch ((uint)lastError)
                    {
                    case Win32Errors.ERROR_MORE_DATA:
                    case Win32Errors.ERROR_INSUFFICIENT_BUFFER:

                        // Should not happen since we already use the maximum size.

                        if (safeBuffer.Capacity < bytesReturned)
                        {
                            safeBuffer.Close();
                        }
                        break;


                    default:
                        if (lastError != Win32Errors.ERROR_SUCCESS)
                        {
                            NativeError.ThrowException(lastError, reparsePath);
                        }
                        break;
                    }
                }

                else
                {
                    break;
                }
            }


            return(safeBuffer);
        }
Exemplo n.º 23
0
        private static byte[] InvokeIoControlUnknownSize <TV>(SafeFileHandle handle, uint controlCode, TV input, uint increment = 128)
        {
            byte[] output;
            uint   bytesReturned;

            var inputSize    = (uint)Marshal.SizeOf(input);
            var outputLength = increment;

            do
            {
                output = new byte[outputLength];
                if (!NativeMethods.DeviceIoControl(handle, controlCode, input, inputSize, output, outputLength, out bytesReturned, IntPtr.Zero))
                {
                    var lastError = Marshal.GetLastWin32Error();
                    switch ((uint)lastError)
                    {
                    case Win32Errors.ERROR_MORE_DATA:
                    case Win32Errors.ERROR_INSUFFICIENT_BUFFER:
                        outputLength += increment;
                        break;

                    default:
                        NativeError.ThrowException(lastError);
                        break;
                    }
                }
                else
                {
                    break;
                }
            } while (true);

            // Return the result
            if (output.Length == bytesReturned)
            {
                return(output);
            }

            var res = new byte[bytesReturned];

            Array.Copy(output, res, bytesReturned);

            return(res);
        }
        internal static void SetAttributesCore(KernelTransaction transaction, bool isFolder, string path, FileAttributes fileAttributes, PathFormat pathFormat)
        {
            if (pathFormat != PathFormat.LongFullPath)
            {
                path = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);
            }


            var success = null == transaction || !NativeMethods.IsAtLeastWindowsVista

                          // SetFileAttributes()
                          // 2013-01-13: MSDN confirms LongPath usage.

            ? NativeMethods.SetFileAttributes(path, fileAttributes)
            : NativeMethods.SetFileAttributesTransacted(path, fileAttributes, transaction.SafeHandle);


            var lastError = Marshal.GetLastWin32Error();

            if (!success)
            {
                switch ((uint)lastError)
                {
                // MSDN: .NET 3.5+: ArgumentException: FileSystemInfo().Attributes
                case Win32Errors.ERROR_INVALID_PARAMETER:
                    throw new ArgumentException(Resources.Invalid_File_Attribute, "fileAttributes");


                case Win32Errors.ERROR_PATH_NOT_FOUND:
                case Win32Errors.ERROR_FILE_NOT_FOUND:
                    if (isFolder)
                    {
                        lastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND;
                    }

                    // MSDN: .NET 3.5+: DirectoryNotFoundException: The specified path is invalid, (for example, it is on an unmapped drive).
                    // MSDN: .NET 3.5+: FileNotFoundException: The file cannot be found.
                    NativeError.ThrowException(lastError, path);
                    break;
                }

                NativeError.ThrowException(lastError, path);
            }
        }
Exemplo n.º 25
0
        internal static T GetAttributesExCore <T>(KernelTransaction transaction, string path, PathFormat pathFormat)
        {
            if (pathFormat == PathFormat.RelativePath)
            {
                Path.CheckSupportedPathFormat(path, true, true);
            }

            string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars);

            var data            = new NativeMethods.WIN32_FILE_ATTRIBUTE_DATA();
            int dataInitialised = FillAttributeInfoCore(transaction, pathLp, ref data, false, true);

            if (dataInitialised != Win32Errors.ERROR_SUCCESS)
            {
                NativeError.ThrowException(dataInitialised, pathLp);
            }

            return((T)(typeof(T) == typeof(FileAttributes) ? (object)data.dwFileAttributes : data));
        }
Exemplo n.º 26
0
        internal static void EnableDisableEncryptionCore(string path, bool enable, PathFormat pathFormat)
        {
            if (Utils.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentNullException("path");
            }

            string pathLp = Path.GetExtendedLengthPathCore(null, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            // EncryptionDisable()
            // In the ANSI version of this function, the name is limited to 248 characters.
            // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
            // 2013-01-13: MSDN does not confirm LongPath usage but a Unicode version of this function exists.

            if (!NativeMethods.EncryptionDisable(pathLp, !enable))
            {
                NativeError.ThrowException(pathLp);
            }
        }
Exemplo n.º 27
0
        /// <summary>Check is the current handle is not null, not closed and not invalid.</summary>
        /// <param name="handle">The current handle to check.</param>
        /// <param name="lastError">The result of Marshal.GetLastWin32Error()</param>
        /// <param name="path">The path on which the Exception occurred.</param>
        /// <param name="throwException"><c>true</c> will throw an <exception cref="Resources.Handle_Is_Invalid_Win32Error"/>, <c>false</c> will not raise this exception..</param>
        /// <returns><c>true</c> on success, <c>false</c> otherwise.</returns>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="Exception"/>
        internal static bool IsValidHandle(SafeHandle handle, int lastError, string path, bool throwException = true)
        {
            if (null == handle || handle.IsClosed || handle.IsInvalid)
            {
                if (null != handle)
                {
                    handle.Close();
                }

                if (throwException)
                {
                    NativeError.ThrowException(lastError, path);
                }

                return(false);
            }

            return(true);
        }
Exemplo n.º 28
0
        public int Read(byte[] buffer, int offset, int count, bool processSecurity)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (!CanRead)
            {
                throw new NotSupportedException("Stream does not support reading");
            }

            if (offset + count > buffer.Length)
            {
                throw new ArgumentException("The sum of offset and count is larger than the size of the buffer.");
            }

            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset", offset, Resources.Negative_Offset);
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count", count, Resources.Negative_Count);
            }


            using (var safeBuffer = new SafeGlobalMemoryBufferHandle(count))
            {
                uint numberOfBytesRead;

                if (!NativeMethods.BackupRead(SafeFileHandle, safeBuffer, (uint)safeBuffer.Capacity, out numberOfBytesRead, false, processSecurity, ref _context))
                {
                    NativeError.ThrowException(Marshal.GetLastWin32Error());
                }

                // See File.GetAccessControlCore(): .CopyTo() does not work there?
                safeBuffer.CopyTo(buffer, offset, count);

                return((int)numberOfBytesRead);
            }
        }
Exemplo n.º 29
0
        internal static void SetAttributesCore(bool isFolder, KernelTransaction transaction, string path, FileAttributes fileAttributes, bool continueOnNotExist, PathFormat pathFormat)
        {
            string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck);

            if (!(transaction == null || !NativeMethods.IsAtLeastWindowsVista

                  // SetFileAttributes()
                  // In the ANSI version of this function, the name is limited to MAX_PATH characters.
                  // To extend this limit to 32,767 wide characters, call the Unicode version of the function and prepend "\\?\" to the path.
                  // 2013-01-13: MSDN confirms LongPath usage.

            ? NativeMethods.SetFileAttributes(pathLp, fileAttributes)
            : NativeMethods.SetFileAttributesTransacted(pathLp, fileAttributes, transaction.SafeHandle)))
            {
                if (continueOnNotExist)
                {
                    return;
                }

                uint lastError = (uint)Marshal.GetLastWin32Error();

                switch (lastError)
                {
                // MSDN: .NET 3.5+: ArgumentException: FileSystemInfo().Attributes
                case Win32Errors.ERROR_INVALID_PARAMETER:
                    throw new ArgumentException(Resources.Invalid_File_Attribute);

                case Win32Errors.ERROR_FILE_NOT_FOUND:
                    if (isFolder)
                    {
                        lastError = (int)Win32Errors.ERROR_PATH_NOT_FOUND;
                    }

                    // MSDN: .NET 3.5+: DirectoryNotFoundException: The specified path is invalid, (for example, it is on an unmapped drive).
                    // MSDN: .NET 3.5+: FileNotFoundException: The file cannot be found.
                    NativeError.ThrowException(lastError, pathLp);
                    break;
                }

                NativeError.ThrowException(lastError, pathLp);
            }
        }
Exemplo n.º 30
0
        /// <summary>[AlphaFS] Enumerates the streams of type :$DATA from the specified file or directory.</summary>
        /// <param name="transaction">The transaction.</param>
        /// <param name="path">The path to the file or directory to enumerate streams of.</param>
        /// <param name="pathFormat">Indicates the format of the path parameter(s).</param>
        /// <returns>The streams of type :$DATA in the specified file or directory.</returns>
        internal static IEnumerable <AlternateDataStreamInfo> EnumerateAlternateDataStreamsCore(KernelTransaction transaction, string path, PathFormat pathFormat)
        {
            using (var buffer = new SafeGlobalMemoryBufferHandle(Marshal.SizeOf(typeof(NativeMethods.WIN32_FIND_STREAM_DATA))))
            {
                string pathLp = Path.GetExtendedLengthPathCore(transaction, path, pathFormat,
                                                               GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars |
                                                               GetFullPathOptions.CheckAdditional);

                using (SafeFindFileHandle handle = transaction == null
               ? NativeMethods.FindFirstStreamW(pathLp, NativeMethods.STREAM_INFO_LEVELS.FindStreamInfoStandard, buffer, 0)
               : NativeMethods.FindFirstStreamTransactedW(pathLp, NativeMethods.STREAM_INFO_LEVELS.FindStreamInfoStandard, buffer, 0, transaction.SafeHandle))
                {
                    int errorCode = Marshal.GetLastWin32Error();

                    if (handle.IsInvalid)
                    {
                        if (errorCode == Win32Errors.ERROR_HANDLE_EOF)
                        {
                            yield break;
                        }

                        NativeError.ThrowException(errorCode);
                    }

                    while (true)
                    {
                        yield return(new AlternateDataStreamInfo(pathLp, buffer.PtrToStructure <NativeMethods.WIN32_FIND_STREAM_DATA>(0)));

                        if (!NativeMethods.FindNextStreamW(handle, buffer))
                        {
                            int lastError = Marshal.GetLastWin32Error();
                            if (lastError == Win32Errors.ERROR_HANDLE_EOF)
                            {
                                break;
                            }

                            NativeError.ThrowException(lastError, pathLp);
                        }
                    }
                }
            }
        }
        internal static void DefineDosDeviceCore(bool isDefine, string deviceName, string targetPath, DosDeviceAttributes deviceAttributes, bool exactMatch)
        {
            if (Utils.IsNullOrWhiteSpace(deviceName))
            {
                throw new ArgumentNullException("deviceName");
            }

            if (isDefine)
            {
                // targetPath is allowed to be null.

                // In no case is a trailing backslash ("\") allowed.
                deviceName = Path.GetRegularPathCore(deviceName, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.CheckInvalidPathChars, false);

                using (new NativeMethods.ChangeErrorMode(NativeMethods.ErrorMode.FailCriticalErrors))
                {
                    var success = NativeMethods.DefineDosDevice(deviceAttributes, deviceName, targetPath);

                    var lastError = Marshal.GetLastWin32Error();
                    if (!success)
                    {
                        NativeError.ThrowException(lastError, deviceName, targetPath);
                    }
                }
            }

            else
            {
                // A pointer to a path string that will implement this device.
                // The string is an MS-DOS path string unless the DDD_RAW_TARGET_PATH flag is specified, in which case this string is a path string.

                if (exactMatch && !Utils.IsNullOrWhiteSpace(targetPath))
                {
                    deviceAttributes = deviceAttributes | DosDeviceAttributes.ExactMatchOnRemove | DosDeviceAttributes.RawTargetPath;
                }

                // Remove the MS-DOS device name. First, get the name of the Windows NT device
                // from the symbolic link and then delete the symbolic link from the namespace.

                DefineDosDevice(deviceName, targetPath, deviceAttributes);
            }
        }
Exemplo n.º 32
0
		internal static NativeError Make(Context cx, Scriptable scope, IdFunctionObject ctorObj, object[] args)
		{
			Scriptable proto = (Scriptable)(ctorObj.Get("prototype", ctorObj));
			NativeError obj = new NativeError();
			obj.SetPrototype(proto);
			obj.SetParentScope(scope);
			int arglen = args.Length;
			if (arglen >= 1)
			{
				ScriptableObject.PutProperty(obj, "message", ScriptRuntime.ToString(args[0]));
				if (arglen >= 2)
				{
					ScriptableObject.PutProperty(obj, "fileName", args[1]);
					if (arglen >= 3)
					{
						int line = ScriptRuntime.ToInt32(args[2]);
						ScriptableObject.PutProperty(obj, "lineNumber", Sharpen.Extensions.ValueOf(line));
					}
				}
			}
			return obj;
		}