static CheckResult CheckDevice(string name, bool writable, EaBuffer ea_buffer)
        {
            CheckResult result = new CheckResult(name, NtStatus.STATUS_INVALID_PARAMETER, FileDeviceType.UNKNOWN);

            try
            {
                using (var imp = NtToken.Impersonate(_pid,
                                                     _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                {
                    FileAccessRights access_mask = FileAccessRights.GenericRead;
                    if (writable)
                    {
                        access_mask |= FileAccessRights.GenericWrite;
                    }

                    FileOpenOptions opts = _open_as_dir ? FileOpenOptions.DirectoryFile : FileOpenOptions.NonDirectoryFile;
                    using (NtFile file = NtFile.Create(name, null, access_mask, NtApiDotNet.FileAttributes.Normal,
                                                       FileShareMode.All, opts, FileDisposition.Open, ea_buffer))
                    {
                        result = new CheckResult(name, NtStatus.STATUS_SUCCESS, file.DeviceType);
                    }
                }
            }
            catch (NtException ex)
            {
                result = new CheckResult(name, ex.Status, FileDeviceType.UNKNOWN);
            }

            return(result);
        }
Пример #2
0
 public static extern NtStatus NtOpenFile(
     out SafeKernelObjectHandle FileHandle,
     FileAccessRights DesiredAccess,
     ObjectAttributes ObjAttr,
     [Out] IoStatus IoStatusBlock,
     FileShareMode ShareAccess,
     FileOpenOptions OpenOptions);
Пример #3
0
        static bool CheckDevice(string name, bool writable)
        {
            bool success = false;

            try
            {
                using (var imp = NtToken.Impersonate(_pid,
                                                     _identify_only ? SecurityImpersonationLevel.Identification : SecurityImpersonationLevel.Impersonation))
                {
                    FileAccessRights access_mask = FileAccessRights.GenericRead;
                    if (writable)
                    {
                        access_mask |= FileAccessRights.GenericWrite;
                    }

                    FileOpenOptions opts = _open_as_dir ? FileOpenOptions.DirectoryFile : FileOpenOptions.NonDirectoryFile;
                    using (NtFile file = NtFile.Open(name, null, access_mask, FileShareMode.All, opts))
                    {
                        success = true;
                    }
                }
            }
            catch (Win32Exception ex)
            {
                // Ignore access denied and invalid function (indicates there's no IRP_MJ_CREATE handler)
                PrintError(name, ex);
            }
            catch (NtException ex)
            {
                PrintError(name, ex.AsWin32Exception());
            }

            return(success);
        }
Пример #4
0
        private protected override void RunAccessCheckPath(IEnumerable <TokenEntry> tokens, string path)
        {
            FileOpenOptions options = _open_for_backup ? FileOpenOptions.OpenForBackupIntent : FileOpenOptions.None;

            if (!FollowLink)
            {
                options |= FileOpenOptions.OpenReparsePoint;
            }
            NtType     type              = NtType.GetTypeByType <NtFile>();
            AccessMask access_rights     = type.MapGenericRights(Access);
            AccessMask dir_access_rights = type.MapGenericRights(DirectoryAccess);

            using (var result = OpenFile(path, null, options))
            {
                NtFile file = result.GetResultOrThrow();
                if (FollowPath(file, GetFilePath))
                {
                    DumpFile(tokens,
                             access_rights,
                             dir_access_rights,
                             null,
                             result.Result);
                    if (IsDirectoryNoThrow(result.Result))
                    {
                        DumpDirectory(tokens, access_rights, dir_access_rights, file, options, GetMaxDepth());
                    }
                }
            }
        }
Пример #5
0
        public static PhpResource fopen(Context ctx, string path, string mode, FileOpenOptions flags = FileOpenOptions.Empty, PhpResource context = null)
        {
            StreamContext sc = StreamContext.GetValid(context, true);

            if (sc == null)
            {
                return(null);
            }

            if (string.IsNullOrEmpty(path))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "path"));
                //return null;
                throw new ArgumentException(nameof(path));
            }

            if (string.IsNullOrEmpty(mode))
            {
                //PhpException.Throw(PhpError.Warning, LibResources.GetString("arg_empty", "mode"));
                //return null;
                throw new ArgumentException(nameof(mode));
            }

            return(PhpStream.Open(ctx, path, mode, ProcessOptions(ctx, flags), sc));
        }
Пример #6
0
 public static extern int NtOpenFile(
     out IntPtr FileHandle,
     FileAccessRights DesiredAccess,
     ObjectAttributes ObjAttr,
     [In][Out] IoStatus IoStatusBlock,
     ShareMode ShareAccess,
     FileOpenOptions OpenOptions);
Пример #7
0
 /// <summary>
 /// Create a new file
 /// </summary>
 /// <param name="name">The path to the file</param>
 /// <param name="root">A root object to parse relative filenames</param>
 /// <param name="desired_access">Desired access for the file</param>
 /// <param name="file_attributes">Attributes for the file</param>
 /// <param name="share_access">Share access for the file</param>
 /// <param name="open_options">Open options for file</param>
 /// <param name="disposition">Disposition when opening the file</param>
 /// <param name="ea_buffer">Extended Attributes buffer</param>
 /// <returns>The created/opened file object.</returns>
 public static NtFile Create(string name, NtObject root, FileAccessRights desired_access, FileAttributes file_attributes, FileShareMode share_access,
                             FileOpenOptions open_options, FileDisposition disposition, EaBuffer ea_buffer)
 {
     using (ObjectAttributes obja = new ObjectAttributes(name, AttributeFlags.CaseInsensitive, root))
     {
         return(Create(obja, desired_access, file_attributes, share_access, open_options, disposition, ea_buffer));
     }
 }
        private static String ShowDialogInner(IFileOpenDialog dialog, IntPtr parentHWnd, String title, String initialDirectory)
#endif
        {
            //IFileDialog ifd = dialog;
            FileOpenOptions flags =
                FileOpenOptions.NoTestFileCreate |
                FileOpenOptions.PathMustExist |
                FileOpenOptions.PickFolders |
                FileOpenOptions.ForceFilesystem;

            dialog.SetOptions(flags);

            if (title != null)
            {
                dialog.SetTitle(title);
            }

            if (initialDirectory != null)
            {
#if NETCOREAPP3_1_OR_GREATER
                IShellItem2?initialDirectoryShellItem = Utility.ParseShellItem2Name(initialDirectory);
#else
                IShellItem2 initialDirectoryShellItem = Utility.ParseShellItem2Name(initialDirectory);
#endif
                if (initialDirectoryShellItem != null)
                {
                    dialog.SetFolder(initialDirectoryShellItem);
                }
            }

            //

            HResult hr = dialog.Show(parentHWnd);
            if (hr.ValidateDialogShowHResult())
            {
                dialog.GetResults(out IShellItemArray resultsArray);

#if NETCOREAPP3_1_OR_GREATER
                IReadOnlyList <String?> fileNames = Utility.GetFileNames(resultsArray);
#else
                IReadOnlyList <String> fileNames = Utility.GetFileNames(resultsArray);
#endif
                if (fileNames.Count == 0)
                {
                    return(null);
                }
                else
                {
                    return(fileNames[0]);
                }
            }
            else
            {
                // User cancelled.
                return(null);
            }
        }
Пример #9
0
 public static extern NtStatus NtCreateMailslotFile(
     out SafeKernelObjectHandle FileHandle,
     FileAccessRights DesiredAccess,
     [In] ObjectAttributes ObjectAttributes,
     [Out] IoStatus IoStatusBlock,
     FileOpenOptions CreateOptions,
     int MailslotQuota,
     int MaximumMessageSize,
     LargeInteger ReadTimeout
     );
Пример #10
0
        private void DumpDirectory(IEnumerable <TokenEntry> tokens, AccessMask access_rights,
                                   AccessMask dir_access_rights, NtFile file, FileOpenOptions options, int current_depth)
        {
            if (Stopping || current_depth <= 0)
            {
                return;
            }

            var parent_sd = GetSecurityDescriptor(file);

            if (Recurse)
            {
                using (var result = file.ReOpen(FileAccessRights.Synchronize | FileAccessRights.ReadData | FileAccessRights.ReadAttributes,
                                                FileShareMode.Read | FileShareMode.Delete, options | FileOpenOptions.DirectoryFile | FileOpenOptions.SynchronousIoNonAlert,
                                                GetAttributeFlags(), false))
                {
                    if (result.Status.IsSuccess())
                    {
                        foreach (var entry in result.Result.QueryDirectoryInfo(Filter, FileTypeMask.All))
                        {
                            if (CheckMode == FileCheckMode.DirectoriesOnly && !entry.IsDirectory)
                            {
                                continue;
                            }

                            NtFile base_file = result.Result;
                            string filename  = entry.FileName;
                            if (filename.Contains(@"\"))
                            {
                                filename  = base_file.FullPath + filename;
                                base_file = null;
                            }

                            using (var new_file = OpenFile(filename, base_file, options))
                            {
                                if (new_file.IsSuccess)
                                {
                                    if (FollowPath(new_file.Result, GetFilePath))
                                    {
                                        DumpFile(tokens, access_rights, dir_access_rights,
                                                 parent_sd.IsSuccess ? parent_sd.Result : null, new_file.Result);
                                        if (IsDirectoryNoThrow(new_file.Result))
                                        {
                                            DumpDirectory(tokens, access_rights, dir_access_rights,
                                                          new_file.Result, options, current_depth - 1);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #11
0
 public static extern NtStatus NtCreateFile(
     out SafeKernelObjectHandle FileHandle,
     FileAccessRights DesiredAccess,
     ObjectAttributes ObjAttr,
     [Out] IoStatus IoStatusBlock,
     LargeInteger AllocationSize,
     FileAttributes FileAttributes,
     FileShareMode ShareAccess,
     FileDisposition CreateDisposition,
     FileOpenOptions CreateOptions,
     byte[] EaBuffer,
     int EaLength);
Пример #12
0
        /// <summary>
        /// Create a new file
        /// </summary>
        /// <param name="obj_attributes">The object attributes</param>
        /// <param name="desired_access">Desired access for the file</param>
        /// <param name="file_attributes">Attributes for the file</param>
        /// <param name="share_access">Share access for the file</param>
        /// <param name="open_options">Open options for file</param>
        /// <param name="disposition">Disposition when opening the file</param>
        /// <param name="ea_buffer">Extended Attributes buffer</param>
        /// <returns>The created/opened file object.</returns>
        public static NtFile Create(ObjectAttributes obj_attributes, FileAccessRights desired_access, FileAttributes file_attributes, FileShareMode share_access,
                                    FileOpenOptions open_options, FileDisposition disposition, EaBuffer ea_buffer)
        {
            SafeKernelObjectHandle handle;
            IoStatus iostatus = new IoStatus();

            byte[] buffer = ea_buffer != null?ea_buffer.ToByteArray() : null;

            NtSystemCalls.NtCreateFile(out handle, desired_access, obj_attributes, iostatus, null, FileAttributes.Normal,
                                       share_access, disposition, open_options, buffer, buffer != null ? buffer.Length : 0).ToNtException();
            return(new NtFile(handle));
        }
Пример #13
0
        private FileOpenOptions CalculateNativeDialogOptionFlags()
        {
            // We start with only a few flags set by default,
            // then go from there based on the current state
            // of the managed dialog's property values.
            FileOpenOptions flags = FileOpenOptions.NoTestFileCreate;

            // Call to derived (concrete) dialog to
            // set dialog-specific flags.
            flags = GetDerivedOptionFlags(flags);

            // Apply other optional flags.
            if (ensureFileExists)
            {
                flags |= FileOpenOptions.FileMustExist;
            }
            if (ensurePathExists)
            {
                flags |= FileOpenOptions.PathMustExist;
            }
            if (!ensureValidNames)
            {
                flags |= FileOpenOptions.NoValidate;
            }
            if (!EnsureReadOnly)
            {
                flags |= FileOpenOptions.NoReadOnlyReturn;
            }
            if (restoreDirectory)
            {
                flags |= FileOpenOptions.NoChangeDirectory;
            }
            if (!showPlacesList)
            {
                flags |= FileOpenOptions.HidePinnedPlaces;
            }
            if (!addToMruList)
            {
                flags |= FileOpenOptions.DontAddToRecent;
            }
            if (showHiddenItems)
            {
                flags |= FileOpenOptions.ForceShowHidden;
            }
            if (!navigateToShortcut)
            {
                flags |= FileOpenOptions.NoDereferenceLinks;
            }
            return(flags);
        }
Пример #14
0
        /// <summary>
        /// Prevents invalid options from the the options argument for StreamWrapper.Open().
        /// </summary>
        /// <param name="ctx">Runtime context.</param>
        /// <param name="flags">Flags passed to stream opening functions.</param>
        /// <returns>The StreamOpenFlags combination for the given arguments.</returns>
        static StreamOpenOptions ProcessOptions(Context ctx, FileOpenOptions flags)
        {
            StreamOpenOptions options = 0;

            if ((flags & FileOpenOptions.UseIncludePath) > 0)
            {
                options |= StreamOpenOptions.UseIncludePath;
            }

            if (!ctx.ErrorReportingDisabled)
            {
                options |= StreamOpenOptions.ReportErrors;
            }

            return(options);
        }
Пример #15
0
 public static extern NtStatus NtCreateNamedPipeFile(
     out SafeKernelObjectHandle FileHandle,
     FileAccessRights DesiredAccess,
     [In] ObjectAttributes ObjectAttributes,
     [Out] IoStatus IoStatusBlock,
     FileShareMode ShareAccess,
     FileDisposition CreateDisposition,
     FileOpenOptions CreateOptions,
     NamedPipeType NamedPipeType,
     NamedPipeReadMode ReadMode,
     NamedPipeCompletionMode CompletionMode,
     int MaximumInstances,
     int InboundQuota,
     int OutboundQuota,
     LargeInteger DefaultTimeout
     );
Пример #16
0
        private NtResult <NtFile> OpenFile(string name, NtFile root, FileOpenOptions options)
        {
            using (ObjectAttributes obja = new ObjectAttributes(name, GetAttributeFlags(), root))
            {
                var result = NtFile.Open(obja, GetMaximumAccess(FileAccessRights.Synchronize | FileAccessRights.ReadAttributes | FileAccessRights.ReadControl),
                                         FileShareMode.Read | FileShareMode.Delete, options | FileOpenOptions.SynchronousIoNonAlert, false);
                if (result.IsSuccess || result.Status != NtStatus.STATUS_ACCESS_DENIED)
                {
                    return(result);
                }

                // Try again with just ReadAttributes, if we can't even do this we give up.
                return(NtFile.Open(obja, FileAccessRights.Synchronize | FileAccessRights.ReadAttributes,
                                   FileShareMode.Read | FileShareMode.Delete, options | FileOpenOptions.SynchronousIoNonAlert, false));
            }
        }
Пример #17
0
        private static String ShowDialogInner(IFileOpenDialog dialog, IntPtr parentWindowHandle, String title, String initialDirectory)
        {
            //IFileDialog ifd = dialog;
            FileOpenOptions flags =
                FileOpenOptions.NoTestFileCreate |
                FileOpenOptions.PathMustExist |
                FileOpenOptions.PickFolders |
                FileOpenOptions.ForceFilesystem;

            dialog.SetOptions(flags);

            if (title != null)
            {
                dialog.SetTitle(title);
            }

            if (initialDirectory != null)
            {
                IShellItem2 initialDirectoryShellItem = Utility.ParseShellItem2Name(initialDirectory);
                if (initialDirectoryShellItem != null)
                {
                    dialog.SetFolder(initialDirectoryShellItem);
                }
            }

            HResult result = dialog.Show(parentWindowHandle);

            if (result == HResult.Ok)
            {
                IShellItemArray resultsArray;
                dialog.GetResults(out resultsArray);

                String[] fileNames = Utility.GetFileNames(resultsArray);
                return(fileNames.Length == 0 ? null : fileNames[0]);
            }
            else if (result == HResult_Win32_Canceled)
            {
                // Cancelled by user.
                return(null);
            }
            else
            {
                UInt32 win32ErrorCode = Utility.Win32ErrorFromHResult((UInt32)result);
                throw new Win32Exception(error: (Int32)win32ErrorCode);
            }
        }
 /// <summary>
 /// Method to create an object from a set of object attributes.
 /// </summary>
 /// <param name="obj_attributes">The object attributes to create/open from.</param>
 /// <returns>The newly created object.</returns>
 protected override object CreateObject(ObjectAttributes obj_attributes)
 {
     using (Transaction?.Enable())
     {
         FileOpenOptions opts = Options;
         if (OpenById)
         {
             opts |= FileOpenOptions.OpenByFileId;
         }
         if (Directory)
         {
             opts |= FileOpenOptions.DirectoryFile;
         }
         return(NtFile.Create(obj_attributes, Access, FileAttribute,
                              ShareMode, opts, Disposition, EaBuffer, AllocationSize));
     }
 }
        private static String ShowDialogInner(IFileOpenDialog dialog, IntPtr parentHWnd, String title, String initialDirectory)
        {
            //IFileDialog ifd = dialog;
            FileOpenOptions flags =
                FileOpenOptions.NoTestFileCreate |
                FileOpenOptions.PathMustExist |
                FileOpenOptions.PickFolders |
                FileOpenOptions.ForceFilesystem;

            dialog.SetOptions(flags);

            if (title != null)
            {
                dialog.SetTitle(title);
            }

            if (initialDirectory != null)
            {
                IShellItem2 initialDirectoryShellItem = Utility.ParseShellItem2Name(initialDirectory);
                if (initialDirectoryShellItem != null)
                {
                    dialog.SetFolder(initialDirectoryShellItem);
                }
            }

            HResult result = dialog.Show(parentHWnd);

            HResult cancelledAsHResult = Utility.HResultFromWin32((int)HResult.Win32ErrorCanceled);

            if (result == cancelledAsHResult)
            {
                // Cancelled
                return(null);
            }
            else
            {
                // OK

                IShellItemArray resultsArray;
                dialog.GetResults(out resultsArray);

                String[] fileNames = Utility.GetFileNames(resultsArray);
                return(fileNames.Length == 0 ? null : fileNames[0]);
            }
        }
Пример #20
0
 public static IEnumerable <string> OpenFile(string source, FileOpenOptions options = FileOpenOptions.IgnoreEmptyLines)
 {
     using (StreamReader reader = File.OpenText(source))
     {
         while (!reader.EndOfStream)
         {
             string line = reader.ReadLine();
             if (options == FileOpenOptions.IgnoreEmptyLines && String.IsNullOrWhiteSpace(line))
             {
                 continue;
             }
             if (line != null)
             {
                 yield return(line);
             }
         }
     }
 }
Пример #21
0
 internal override FileOpenOptions GetDerivedOptionFlags(FileOpenOptions flags)
 {
     if (overwritePrompt)
     {
         flags |= FileOpenOptions.OverwritePrompt;
     }
     if (createPrompt)
     {
         flags |= FileOpenOptions.CreatePrompt;
     }
     if (!isExpandedMode)
     {
         flags |= FileOpenOptions.DefaultNoMiniMode;
     }
     if (alwaysAppendDefaultExtension)
     {
         flags |= FileOpenOptions.StrictFileTypes;
     }
     return(flags);
 }
Пример #22
0
        public static int readfile(Context ctx, string path, FileOpenOptions flags = FileOpenOptions.Empty, PhpResource context = null)
        {
            StreamContext sc = StreamContext.GetValid(context, true);

            if (sc == null)
            {
                return(-1);
            }

            using (PhpStream res = PhpStream.Open(ctx, path, "rb", ProcessOptions(ctx, flags), sc))
            {
                if (res == null)
                {
                    return(-1);
                }

                // Note: binary file access is the most efficient (no superfluous filtering
                // and no conversions - PassThrough will write directly to the OutputStream).
                return(fpassthru(ctx, res));
            }
        }
        private void CheckAccessUnderImpersonation(TokenEntry token, string path, bool namespace_path,
                                                   AccessMask access_rights, FileOpenOptions open_options, EaBuffer ea_buffer)
        {
            using (var result = OpenUnderImpersonation(token, path, open_options, ea_buffer))
            {
                if (result.IsSuccess)
                {
                    if (IsAccessGranted(result.Result.GrantedAccessMask, access_rights))
                    {
                        var sd = result.Result.GetSecurityDescriptor(SecurityInformation.AllBasic, false);

                        WriteObject(new DeviceAccessCheckResult(path, namespace_path, GetDeviceType(result.Result), result.Result.GrantedAccess,
                                                                sd.IsSuccess ? sd.Result.ToSddl() : String.Empty, token.Information));
                    }
                }
                else
                {
                    WriteWarning(String.Format("Opening {0} failed: {1}", path, result.Status));
                }
            }
        }
Пример #24
0
        internal override FileOpenOptions GetDerivedOptionFlags(FileOpenOptions flags)
        {
            if (multiselect)
            {
                flags |= FileOpenOptions.AllowMultiSelect;
            }
            if (isFolderPicker)
            {
                flags |= FileOpenOptions.PickFolders;
            }

            if (!allowNonFileSystem)
            {
                flags |= FileOpenOptions.ForceFilesystem;
            }
            else if (allowNonFileSystem)
            {
                flags |= FileOpenOptions.AllNonStorageItems;
            }

            return(flags);
        }
Пример #25
0
        static bool CheckDevice(string name, bool writable)
        {
            bool success = false;

            try
            {
                using (ImpersonateProcess imp = NativeBridge.Impersonate(_pid,
                                                                         _identify_only ? TokenSecurityLevel.Identification : TokenSecurityLevel.Impersonate))
                {
                    uint access_mask = (uint)GenericAccessRights.GenericRead;
                    if (writable)
                    {
                        access_mask |= (uint)GenericAccessRights.GenericWrite;
                    }

                    FileOpenOptions opts = _open_as_dir ? FileOpenOptions.DIRECTORY_FILE : FileOpenOptions.NON_DIRECTORY_FILE;

                    using (NativeHandle handle = NativeBridge.CreateFileNative(name,
                                                                               access_mask, 0, FileShareMode.All, FileCreateDisposition.Open,
                                                                               opts))
                    {
                        success = true;
                    }
                }
            }
            catch (Win32Exception ex)
            {
                // Ignore access denied and invalid function (indicates there's no IRP_MJ_CREATE handler)
                if (_show_errors && (ex.NativeErrorCode != 5) && (ex.NativeErrorCode != 1))
                {
                    Console.Error.WriteLine("Error checking {0} - {1}", name, ex.Message);
                }
            }

            return(success);
        }
Пример #26
0
        private static String[] ShowDialog(IntPtr parentWindowHandle, String title, String initialDirectory, String defaultFileName, IReadOnlyCollection <Filter> filters, Int32 selectedFilterZeroBasedIndex, FileOpenOptions flags)
        {
            NativeFileOpenDialog nfod = new NativeFileOpenDialog();

            try
            {
                return(ShowDialogInner(nfod, parentWindowHandle, title, initialDirectory, defaultFileName, filters, selectedFilterZeroBasedIndex, flags));
            }
            finally
            {
                Marshal.ReleaseComObject(nfod);
            }
        }
Пример #27
0
		public static object ReadContents(ScriptContext scriptcontext, System.Collections.Generic.Dictionary<string, object> definedVariables, string path, FileOpenOptions flags, PhpResource context,
		  int offset, int maxLength)
		{
            StreamContext sc = StreamContext.GetValid(context, true);
            if (sc == null)
                return null;
            
			using (PhpStream stream = PhpStream.Open(path, "rb", ProcessOptions(flags), sc))
			{
				if (stream == null) return null;

                // when HTTP protocol requested, store responded headers into local variable $http_response_header:
                // NOTE: (J) this should be applied by HTTP wrapper itself, not only by this function.
                if (string.Compare(stream.Wrapper.Scheme, "http", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    var headers = stream.WrapperSpecificData as PhpArray;
                    Operators.SetVariable(scriptcontext, definedVariables, HttpResponseHeaderName, headers);                    
                }

                //
				return Core.Convert.Quote(stream.ReadContents(maxLength, offset), ScriptContext.CurrentContext);
			}
		}
Пример #28
0
        public Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
        {
            if (_sharpCifsFileSystem.IsEnabledForPath(path))
            {
                return(_sharpCifsFileSystem.GetFileStream(path, mode, access, share));
            }

            var defaultBufferSize = 4096;

            return(new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), defaultBufferSize, GetFileOptions(fileOpenOptions)));
        }
Пример #29
0
		public static PhpArray GetMetaTags(string fileName, FileOpenOptions flags)
		{
			PhpArray result = new PhpArray();
			ScriptContext context = ScriptContext.CurrentContext;

			if (getMetaTagsRegex == null)
			{
				getMetaTagsRegex = new Regex(@"^meta\s+name\s*=\s*(?:(\w*)|'([^']*)'|\u0022([^\u0022]*)\u0022)\s+" +
					@"content\s*=\s*(?:(\w*)|'([^']*)'|\u0022([^\u0022]*)\u0022)\s*/?$",
					RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
			}

			try
			{
				PhpStream stream = PhpStream.Open(fileName, "rt", PhpFile.ProcessOptions(flags));
				StringBuilder tag = new StringBuilder();

				bool in_brackets = false;
				int in_quotes = 0; // 1 = ', 2 = "
				int in_comment = 0; // 1 = <, 2 = <!, 3 = <!-, 4 = <!--, 5 = <!-- -, 6  <!-- --

				while (!stream.Eof)
				{
					int start_index = 0;

					string line = stream.ReadLine(-1, null);
					for (int i = 0; i < line.Length; i++)
					{
						switch (line[i])
						{
							case '<':
								{
									if (!in_brackets && in_quotes == 0 && in_comment == 0)
									{
										in_brackets = true;
										in_comment = 1;

										start_index = i + 1;
									}
									break;
								}

							case '>':
								{
									if (in_brackets && in_quotes == 0 && in_comment != 4 && in_comment != 5)
									{
										in_brackets = false;
										in_comment = 0;

										if (start_index < i) tag.Append(line, start_index, i - start_index);

										string str = tag.ToString();
										tag.Length = 0;

										// did we reach the end of <head>?
										if (str.Equals("/head", StringComparison.InvariantCultureIgnoreCase)) return result;

										// try to match the tag with the <meta> regex
										Match match = getMetaTagsRegex.Match(str);
										if (match.Success)
										{
											string name = null, value = null;
											for (int j = 1; j <= 3; j++)
												if (match.Groups[j].Success)
												{
													name = match.Groups[j].Value;
													break;
												}

											if (name != null)
											{
												for (int j = 4; j <= 6; j++)
													if (match.Groups[j].Success)
													{
														value = match.Groups[j].Value;
														break;
													}

												result[name] = (value == null ? String.Empty : Core.Convert.Quote(value, context));
											}
										}
									}
									break;
								}

							case '\'':
								{
									if (in_quotes == 0) in_quotes = 1;
									else if (in_quotes == 1) in_quotes = 0;
									break;
								}

							case '"':
								{
									if (in_quotes == 0) in_quotes = 2;
									else if (in_quotes == 2) in_quotes = 0;
									break;
								}

							case '!': if (in_comment == 1) in_comment = 2; break;
							case '-': if (in_comment >= 2 && in_comment < 6) in_comment++; break;

							default:
								{
									// reset comment state machine
									if (in_comment < 4) in_comment = 0;
									if (in_comment > 4) in_comment = 4;
									break;
								}
						}
					}

					if (in_brackets && start_index < line.Length) tag.Append(line, start_index, line.Length - start_index);
				}
			}
			catch (IOException)
			{
				return null;
			}

			return result;
		}
Пример #30
0
 public virtual Stream GetFileStream(string path, FileOpenMode mode, FileAccessMode access, FileShareMode share, FileOpenOptions fileOpenOptions)
 => new FileStream(path, GetFileMode(mode), GetFileAccess(access), GetFileShare(share), 4096, GetFileOptions(fileOpenOptions));
Пример #31
0
		public static PhpResource Open(string path, string mode, FileOpenOptions flags)
		{
			return Open(path, mode, flags, StreamContext.Default);
		}
Пример #32
0
		public static PhpResource Open(string path, string mode, FileOpenOptions flags, PhpResource context)
		{
			StreamContext sc = StreamContext.GetValid(context);
			if (sc == null) return null;

			if (String.IsNullOrEmpty(path))
			{
				PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:empty", "path"));
				return null;
			}

			if (String.IsNullOrEmpty(mode))
			{
				PhpException.Throw(PhpError.Warning, LibResources.GetString("arg:empty", "mode"));
				return null;
			}

			return PhpStream.Open(path, mode, ProcessOptions(flags), sc);
		}
Пример #33
0
		/// <summary>
		/// Prevents invalid options from the the options argument for StreamWrapper.Open().
		/// </summary>
		/// <param name="flags">Flags passed to stream opening functions.</param>
		/// <returns>The StreamOpenFlags combination for the given arguments.</returns>
		internal static StreamOpenOptions ProcessOptions(FileOpenOptions flags)
		{
			StreamOpenOptions options = 0;

			if ((flags & FileOpenOptions.UseIncludePath) > 0)
				options |= StreamOpenOptions.UseIncludePath;

			if (!ScriptContext.CurrentContext.ErrorReportingDisabled)
				options |= StreamOpenOptions.ReportErrors;

			return options;
		}
Пример #34
0
		public static int ReadFile(string path, FileOpenOptions flags, PhpResource context)
		{
            StreamContext sc = StreamContext.GetValid(context, true);
			if (sc == null) return -1;

			using (PhpStream res = PhpStream.Open(path, "rb", ProcessOptions(flags), sc))
			{
				if (res == null) return -1;

				// Note: binary file access is the most efficient (no superfluous filtering
				// and no conversions - PassThrough will write directly to the OutputStream).
				return PassThrough(res);
			}
		}
Пример #35
0
		public static int ReadFile(string path, FileOpenOptions flags)
		{
			return ReadFile(path, flags, StreamContext.Default);
		}
Пример #36
0
        private static String[] ShowDialogInner(IFileOpenDialog dialog, IntPtr parentWindowHandle, String title, String initialDirectory, String defaultFileName, IReadOnlyCollection <Filter> filters, Int32 selectedFilterZeroBasedIndex, FileOpenOptions flags)
        {
            flags = flags |
                    FileOpenOptions.NoTestFileCreate |
                    FileOpenOptions.PathMustExist |
                    FileOpenOptions.ForceFilesystem;

            dialog.SetOptions(flags);

            if (title != null)
            {
                dialog.SetTitle(title);
            }

            if (initialDirectory != null)
            {
                IShellItem2 initialDirectoryShellItem = Utility.ParseShellItem2Name(initialDirectory);
                if (initialDirectoryShellItem != null)
                {
                    dialog.SetFolder(initialDirectoryShellItem);
                }
            }

            if (defaultFileName != null)
            {
                dialog.SetFileName(defaultFileName);
            }

            Utility.SetFilters(dialog, filters, selectedFilterZeroBasedIndex);

            HResult result = dialog.Show(parentWindowHandle);

            if (result == HResult.Ok)
            {
                IShellItemArray resultsArray;
                dialog.GetResults(out resultsArray);

                String[] fileNames = Utility.GetFileNames(resultsArray);
                return(fileNames);
            }
            else if (result == HResult_Win32_Canceled)
            {
                // Cancelled by user.
                return(null);
            }
            else
            {
                UInt32 win32ErrorCode = Utility.Win32ErrorFromHResult((UInt32)result);
                throw new Win32Exception(error: (Int32)win32ErrorCode);
            }
        }
Пример #37
0
        public static object ReadContents(ScriptContext scriptcontext, System.Collections.Generic.Dictionary<string, object> definedVariables, string path, FileOpenOptions flags)
		{
            return ReadContents(scriptcontext, definedVariables, path, flags, StreamContext.Default, -1, -1);
		}
Пример #38
0
        private FileOptions GetFileOptions(FileOpenOptions mode)
        {
            var val = (int)mode;

            return((FileOptions)val);
        }
Пример #39
0
        public static object ReadContents(ScriptContext scriptcontext, System.Collections.Generic.Dictionary<string, object> definedVariables, string path, FileOpenOptions flags, PhpResource context,
		  int offset)
		{
            return ReadContents(scriptcontext, definedVariables, path, flags, context, offset, -1);
		}