mirror of
https://github.com/gerardog/gsudo.git
synced 2025-01-07 03:06:40 +08:00
Code style and build warning fixes
This commit is contained in:
parent
d198975bc5
commit
5be428734a
@ -8,3 +8,15 @@ dotnet_diagnostic.CA2000.severity = none
|
||||
|
||||
# CA1031: Do not catch general exception types
|
||||
dotnet_diagnostic.CA1031.severity = none
|
||||
|
||||
# IDE0008: Use explicit type
|
||||
csharp_style_var_for_built_in_types = false:silent
|
||||
|
||||
# IDE0008: Use explicit type
|
||||
csharp_style_var_elsewhere = false:silent
|
||||
|
||||
# IDE0008: Use explicit type
|
||||
csharp_style_var_when_type_is_apparent = false:silent
|
||||
|
||||
# CA1062: Validate arguments of public methods
|
||||
dotnet_diagnostic.CA1062.severity = none
|
||||
|
@ -84,6 +84,8 @@ $@"# ./gsudo 'echo 1 2 3'
|
||||
|
||||
string FixAppVeyor(string input)
|
||||
{
|
||||
// AppVeyor's powershell displays a warning message because it uses PSReadLine that does not support Process Rediretion.
|
||||
// Remove the message.
|
||||
var ret = Regex.Replace(input, "((\r\n|\r|\n)Oops.*?-{71}.*?-{71}(\r\n|\r|\n))", string.Empty, RegexOptions.Singleline);
|
||||
return ret;
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
using System.Threading.Tasks;
|
||||
using System.Threading;
|
||||
using static gsudo.Native.ConsoleApi;
|
||||
|
||||
namespace gsudo.Commands
|
||||
@ -8,11 +7,7 @@ namespace gsudo.Commands
|
||||
{
|
||||
public int pid { get; set; }
|
||||
|
||||
Timer ShutdownTimer;
|
||||
void EnableTimer() => ShutdownTimer.Change((int)GlobalSettings.CredentialsCacheDuration.Value.TotalMilliseconds, Timeout.Infinite);
|
||||
void DisableTimer() => ShutdownTimer.Change(Timeout.Infinite, Timeout.Infinite);
|
||||
|
||||
public async Task<int> Execute()
|
||||
public Task<int> Execute()
|
||||
{
|
||||
FreeConsole();
|
||||
|
||||
@ -23,10 +18,10 @@ namespace gsudo.Commands
|
||||
}
|
||||
else
|
||||
{
|
||||
return Constants.GSUDO_ERROR_EXITCODE;
|
||||
return Task.FromResult(Constants.GSUDO_ERROR_EXITCODE);
|
||||
}
|
||||
|
||||
return 0;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -146,11 +146,10 @@ namespace gsudo.Commands
|
||||
|
||||
await WriteElevationRequest(elevationRequest, connection).ConfigureAwait(false);
|
||||
|
||||
await connection.ControlStream.FlushAsync().ConfigureAwait(false);
|
||||
ConnectionKeepAliveThread.Start(connection);
|
||||
|
||||
var p = GetRenderer(connection, elevationRequest);
|
||||
var exitcode = await p.Start().ConfigureAwait(false);
|
||||
var renderer = GetRenderer(connection, elevationRequest);
|
||||
var exitcode = await renderer.Start().ConfigureAwait(false);
|
||||
return exitcode;
|
||||
}
|
||||
finally
|
||||
@ -185,6 +184,7 @@ namespace gsudo.Commands
|
||||
|
||||
await connection.ControlStream.WriteAsync(lengthArray, 0, sizeof(int)).ConfigureAwait(false);
|
||||
await connection.ControlStream.WriteAsync(ms.ToArray(), 0, (int)ms.Length).ConfigureAwait(false);
|
||||
await connection.ControlStream.FlushAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@ -205,17 +205,13 @@ namespace gsudo.Commands
|
||||
|
||||
return ElevationRequest.ConsoleMode.Attached;
|
||||
|
||||
if (TerminalHelper.TerminalHasBuiltInVTSupport())
|
||||
{
|
||||
// we where called from a ConEmu console which has a working
|
||||
// full VT terminal with no bugs.
|
||||
return ElevationRequest.ConsoleMode.VT;
|
||||
}
|
||||
|
||||
return ElevationRequest.ConsoleMode.Raw;
|
||||
// if (TerminalHelper.TerminalHasBuiltInVTSupport()) return ElevationRequest.ConsoleMode.VT;
|
||||
// else return ElevationRequest.ConsoleMode.Raw;
|
||||
}
|
||||
|
||||
#pragma warning disable IDE0060 // Remove unused parameter (reserved for future use)
|
||||
private IRpcClient GetClient(ElevationRequest elevationRequest)
|
||||
#pragma warning restore IDE0060 // Remove unused parameter
|
||||
{
|
||||
// future Tcp implementations should be plugged here.
|
||||
return new NamedPipeClient();
|
||||
|
@ -58,7 +58,7 @@ namespace gsudo.Commands
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Instance.Log(e.ToString(), LogLevel.Error);
|
||||
await connection.FlushAndCloseAll();
|
||||
await connection.FlushAndCloseAll().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -81,22 +81,23 @@ namespace gsudo.Commands
|
||||
return new NamedPipeServer(allowedPid);
|
||||
}
|
||||
|
||||
private static async Task<ElevationRequest> ReadElevationRequest(Stream dataPipe)
|
||||
private async Task<ElevationRequest> ReadElevationRequest(Stream dataPipe)
|
||||
{
|
||||
byte[] dataSize = new byte[sizeof(int)];
|
||||
dataPipe.Read(dataSize, 0, sizeof(int));
|
||||
await dataPipe.ReadAsync(dataSize, 0, sizeof(int)).ConfigureAwait(false);
|
||||
int dataSizeInt = BitConverter.ToInt32(dataSize, 0);
|
||||
byte[] inBuffer = new byte[dataSizeInt];
|
||||
|
||||
var bytesRemaining = dataSizeInt;
|
||||
while (bytesRemaining > 0 )
|
||||
bytesRemaining -= dataPipe.Read(inBuffer, 0, bytesRemaining);
|
||||
bytesRemaining -= await dataPipe.ReadAsync(inBuffer, 0, bytesRemaining).ConfigureAwait(false);
|
||||
|
||||
Logger.Instance.Log($"ElevationRequest length {dataSizeInt}", LogLevel.Debug);
|
||||
|
||||
return (ElevationRequest) new BinaryFormatter()
|
||||
// { TypeFormat = System.Runtime.Serialization.Formatters.FormatterTypeStyle.TypesAlways, Binder = new MySerializationBinder() }
|
||||
.Deserialize(new MemoryStream(inBuffer));
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,4 +1,5 @@
|
||||
using gsudo.Commands;
|
||||
using gsudo.Native;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@ -9,55 +10,30 @@ using System.Runtime.InteropServices;
|
||||
|
||||
namespace gsudo.Helpers
|
||||
{
|
||||
public class ArgumentsHelper
|
||||
public static class ArgumentsHelper
|
||||
{
|
||||
internal static string[] AugmentCommand(string[] args)
|
||||
{
|
||||
string currentShellExeName;
|
||||
Shell currentShell = ShellHelper.DetectInvokingShell(out currentShellExeName);
|
||||
|
||||
// Is our current shell Powershell ? (Powershell.exe -calls-> gsudo)
|
||||
var parentProcess = Process.GetCurrentProcess().ParentProcess();
|
||||
var parentExeName = Path.GetFileName(parentProcess.MainModule.FileName).ToUpperInvariant();
|
||||
if (parentExeName == "POWERSHELL.EXE")
|
||||
if (currentShell.In(Shell.PowerShell, Shell.PowerShellCore))
|
||||
{
|
||||
if (args.Length == 0)
|
||||
return new string[]
|
||||
{ parentProcess.MainModule.FileName };
|
||||
{ currentShellExeName };
|
||||
else
|
||||
return new string[] // Escape " => ""
|
||||
{ parentProcess.MainModule.FileName ,
|
||||
return new string[]
|
||||
{ currentShellExeName ,
|
||||
"-NoProfile",
|
||||
//$"\"{ String.Join(" ", args.Select(arg => arg.Replace("\"","\"\""))) }\""
|
||||
String.Join(" ", args)
|
||||
};
|
||||
}
|
||||
else
|
||||
{
|
||||
// Is our current shell Powershell Core? (Pwsh.exe -calls-> dotnet -calls-> gsudo)
|
||||
var grandParentProcess = parentProcess.ParentProcess();
|
||||
if (grandParentProcess != null)
|
||||
{
|
||||
var grandParentExeName = Path.GetFileName(grandParentProcess.MainModule.FileName).ToUpperInvariant();
|
||||
if (grandParentExeName == "PWSH.EXE")
|
||||
{
|
||||
if (args.Length == 0)
|
||||
return new string[]
|
||||
{ grandParentProcess.MainModule.FileName };
|
||||
else
|
||||
return new string[] // Escape " => `"
|
||||
{ grandParentProcess.MainModule.FileName ,
|
||||
"-NoProfile",
|
||||
//$"\"{ String.Join(" ", args.Select(arg => arg.Replace("\"","'\""))) }\""
|
||||
String.Join(" ", args)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Not Powershell, or Powershell Core, assume CMD.
|
||||
if (args.Length == 0)
|
||||
{
|
||||
// If zero args specified, elevate CMD.
|
||||
|
||||
// Default, our current shell is CMD.
|
||||
return new string[]
|
||||
{ Environment.GetEnvironmentVariable("COMSPEC"), "/k" };
|
||||
}
|
||||
@ -106,7 +82,6 @@ namespace gsudo.Helpers
|
||||
return results.ToArray();
|
||||
}
|
||||
|
||||
|
||||
internal static int? ParseCommonSettings(ref string[] args)
|
||||
{
|
||||
Stack<string> stack = new Stack<string>(args.Reverse());
|
||||
@ -216,7 +191,7 @@ namespace gsudo.Helpers
|
||||
|
||||
internal static string GetRealCommandLine()
|
||||
{
|
||||
System.IntPtr ptr = GetCommandLine();
|
||||
System.IntPtr ptr = ConsoleApi.GetCommandLine();
|
||||
string commandLine = Marshal.PtrToStringAuto(ptr);
|
||||
|
||||
if (commandLine[0] == '"')
|
||||
@ -237,11 +212,5 @@ namespace gsudo.Helpers
|
||||
else
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
|
||||
private static extern System.IntPtr GetCommandLine();
|
||||
|
||||
}
|
||||
}
|
||||
|
@ -1,12 +1,11 @@
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using static gsudo.Native.ProcessApi;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.ConstrainedExecution;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security;
|
||||
using System.Security.Permissions;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
|
||||
@ -22,7 +21,7 @@ namespace gsudo.Helpers
|
||||
// So the best we can do is create a new process that will attach and send Ctrl-C to the target process.
|
||||
|
||||
using (var p = ProcessFactory.StartDetached
|
||||
(Process.GetCurrentProcess().MainModule.FileName, $"gsudoctrlc {proc.Id.ToString()}", Environment.CurrentDirectory, true))
|
||||
(Process.GetCurrentProcess().MainModule.FileName, $"gsudoctrlc {proc.Id.ToString(CultureInfo.InvariantCulture)}", Environment.CurrentDirectory, true))
|
||||
{
|
||||
p.WaitForExit();
|
||||
}
|
||||
@ -114,66 +113,6 @@ namespace gsudo.Helpers
|
||||
}
|
||||
}
|
||||
|
||||
#region Win32 api
|
||||
|
||||
private const int ERROR_NO_MORE_FILES = 0x12;
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern SafeSnapshotHandle CreateToolhelp32Snapshot(SnapshotFlags flags, uint id);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool Process32First(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool Process32Next(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
|
||||
|
||||
[Flags]
|
||||
private enum SnapshotFlags : uint
|
||||
{
|
||||
HeapList = 0x00000001,
|
||||
Process = 0x00000002,
|
||||
Thread = 0x00000004,
|
||||
Module = 0x00000008,
|
||||
Module32 = 0x00000010,
|
||||
All = (HeapList | Process | Thread | Module),
|
||||
Inherit = 0x80000000,
|
||||
NoHeaps = 0x40000000
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct PROCESSENTRY32
|
||||
{
|
||||
public uint dwSize;
|
||||
public uint cntUsage;
|
||||
public uint th32ProcessID;
|
||||
public IntPtr th32DefaultHeapID;
|
||||
public uint th32ModuleID;
|
||||
public uint cntThreads;
|
||||
public uint th32ParentProcessID;
|
||||
public int pcPriClassBase;
|
||||
public uint dwFlags;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile;
|
||||
};
|
||||
[SuppressUnmanagedCodeSecurity, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
|
||||
internal sealed class SafeSnapshotHandle : SafeHandleMinusOneIsInvalid
|
||||
{
|
||||
internal SafeSnapshotHandle() : base(true)
|
||||
{
|
||||
}
|
||||
|
||||
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
|
||||
internal SafeSnapshotHandle(IntPtr handle) : base(true)
|
||||
{
|
||||
base.SetHandle(handle);
|
||||
}
|
||||
|
||||
protected override bool ReleaseHandle()
|
||||
{
|
||||
return CloseHandle(base.handle);
|
||||
}
|
||||
|
||||
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CloseHandle(IntPtr handle);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
public static void Terminate(this Process process)
|
||||
{
|
||||
if (process.HasExited) return;
|
||||
@ -188,16 +127,6 @@ namespace gsudo.Helpers
|
||||
if (!process.HasExited)
|
||||
{
|
||||
process.Kill();
|
||||
/*
|
||||
var p = Process.Start(new ProcessStartInfo()
|
||||
{
|
||||
FileName = "taskkill",
|
||||
Arguments = $"/PID {process.Id} /T",
|
||||
WindowStyle = ProcessWindowStyle.Hidden
|
||||
|
||||
});
|
||||
p.WaitForExit();
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using gsudo.Native;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
@ -85,15 +86,12 @@ namespace gsudo.Helpers
|
||||
|
||||
// set user the focus to the window, if there is one.
|
||||
if (process.MainWindowHandle != IntPtr.Zero)
|
||||
SetForegroundWindow(process.MainWindowHandle);
|
||||
WindowApi.SetForegroundWindow(process.MainWindowHandle);
|
||||
}
|
||||
|
||||
return process;
|
||||
}
|
||||
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")]
|
||||
public static extern int SetForegroundWindow(IntPtr hwnd);
|
||||
|
||||
public static bool IsWindowsApp(string exe)
|
||||
{
|
||||
var path = exe;
|
||||
|
49
src/gsudo/Helpers/ShellHelper.cs
Normal file
49
src/gsudo/Helpers/ShellHelper.cs
Normal file
@ -0,0 +1,49 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace gsudo.Helpers
|
||||
{
|
||||
public enum Shell
|
||||
{
|
||||
PowerShell,
|
||||
PowerShellCore,
|
||||
Cmd
|
||||
}
|
||||
|
||||
static class ShellHelper
|
||||
{
|
||||
public static Shell DetectInvokingShell(out string ShellExeName)
|
||||
{
|
||||
// Is our current shell Powershell ? (Powershell.exe -calls-> gsudo)
|
||||
var parentProcess = Process.GetCurrentProcess().ParentProcess();
|
||||
var parentExeName = Path.GetFileName(parentProcess.MainModule.FileName).ToUpperInvariant();
|
||||
if (parentExeName == "POWERSHELL.EXE")
|
||||
{
|
||||
ShellExeName = parentProcess.MainModule.FileName;
|
||||
return Shell.PowerShell;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Is our current shell Powershell Core? (Pwsh.exe -calls-> dotnet -calls-> gsudo)
|
||||
var grandParentProcess = parentProcess.ParentProcess();
|
||||
if (grandParentProcess != null)
|
||||
{
|
||||
var grandParentExeName = Path.GetFileName(grandParentProcess.MainModule.FileName).ToUpperInvariant();
|
||||
if (grandParentExeName == "PWSH.EXE")
|
||||
{
|
||||
ShellExeName = grandParentProcess.MainModule.FileName; ;
|
||||
return Shell.PowerShellCore;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ShellExeName = Environment.GetEnvironmentVariable("COMSPEC");
|
||||
return Shell.Cmd;
|
||||
}
|
||||
}
|
||||
}
|
@ -7,6 +7,7 @@ namespace gsudo.Native
|
||||
/// <summary>
|
||||
/// PInvoke signatures for win32 console api
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1060:Move pinvokes to native methods class", Justification = "Done")]
|
||||
static class ConsoleApi
|
||||
{
|
||||
internal const int STD_OUTPUT_HANDLE = -11;
|
||||
@ -58,5 +59,7 @@ namespace gsudo.Native
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
|
||||
public static extern System.IntPtr GetCommandLine();
|
||||
}
|
||||
}
|
||||
|
@ -5,6 +5,7 @@ using System.Text;
|
||||
|
||||
namespace gsudo.Native
|
||||
{
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1060:Move pinvokes to native methods class", Justification = "Done")]
|
||||
static class FileApi
|
||||
{
|
||||
internal static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1);
|
||||
@ -12,8 +13,8 @@ namespace gsudo.Native
|
||||
internal const uint FILE_READ_EA = 0x0008;
|
||||
internal const uint FILE_FLAG_BACKUP_SEMANTICS = 0x2000000;
|
||||
|
||||
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
|
||||
internal static extern uint GetFinalPathNameByHandle(IntPtr hFile, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpszFilePath, uint cchFilePath, uint dwFlags);
|
||||
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
||||
internal static extern uint GetFinalPathNameByHandle(IntPtr hFile, StringBuilder lpszFilePath, uint cchFilePath, uint dwFlags);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
@ -21,7 +22,7 @@ namespace gsudo.Native
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
internal static extern IntPtr CreateFile(
|
||||
[MarshalAs(UnmanagedType.LPTStr)] string filename,
|
||||
[MarshalAs(UnmanagedType.LPWStr)] string filename,
|
||||
[MarshalAs(UnmanagedType.U4)] uint access,
|
||||
[MarshalAs(UnmanagedType.U4)] FileShare share,
|
||||
IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
|
||||
@ -30,7 +31,7 @@ namespace gsudo.Native
|
||||
IntPtr templateFile);
|
||||
|
||||
#region IsWindowsApp Win32 Api
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode)]
|
||||
internal static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbFileInfo, uint uFlags);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
|
||||
|
@ -1,11 +1,17 @@
|
||||
using System;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
using System;
|
||||
using System.Runtime.ConstrainedExecution;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security;
|
||||
using System.Security.Permissions;
|
||||
using static gsudo.Helpers.ProcessExtensions;
|
||||
|
||||
namespace gsudo.Native
|
||||
{
|
||||
/// <summary>
|
||||
/// PInvoke signatures for win32 process api
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1060:Move pinvokes to native methods class", Justification = "Done")]
|
||||
static class ProcessApi
|
||||
{
|
||||
internal const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
|
||||
@ -68,7 +74,7 @@ namespace gsudo.Native
|
||||
IntPtr lpAttributeList, uint dwFlags, IntPtr attribute, IntPtr lpValue,
|
||||
IntPtr cbSize, IntPtr lpPreviousValue, IntPtr lpReturnSize);
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
internal static extern bool CreateProcess(
|
||||
string lpApplicationName, string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
|
||||
@ -91,5 +97,63 @@ namespace gsudo.Native
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
public static extern bool GetNamedPipeClientProcessId(IntPtr Pipe, out uint ClientProcessId);
|
||||
|
||||
#region PID traversing
|
||||
internal const int ERROR_NO_MORE_FILES = 0x12;
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
internal static extern SafeSnapshotHandle CreateToolhelp32Snapshot(SnapshotFlags flags, uint id);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
internal static extern bool Process32First(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
internal static extern bool Process32Next(SafeSnapshotHandle hSnapshot, ref PROCESSENTRY32 lppe);
|
||||
|
||||
[Flags]
|
||||
internal enum SnapshotFlags : uint
|
||||
{
|
||||
HeapList = 0x00000001,
|
||||
Process = 0x00000002,
|
||||
Thread = 0x00000004,
|
||||
Module = 0x00000008,
|
||||
Module32 = 0x00000010,
|
||||
All = (HeapList | Process | Thread | Module),
|
||||
Inherit = 0x80000000,
|
||||
NoHeaps = 0x40000000
|
||||
}
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
internal struct PROCESSENTRY32
|
||||
{
|
||||
public uint dwSize;
|
||||
public uint cntUsage;
|
||||
public uint th32ProcessID;
|
||||
public IntPtr th32DefaultHeapID;
|
||||
public uint th32ModuleID;
|
||||
public uint cntThreads;
|
||||
public uint th32ParentProcessID;
|
||||
public int pcPriClassBase;
|
||||
public uint dwFlags;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile;
|
||||
};
|
||||
|
||||
[SuppressUnmanagedCodeSecurity, HostProtection(SecurityAction.LinkDemand, MayLeakOnAbort = true)]
|
||||
internal sealed class SafeSnapshotHandle : SafeHandleMinusOneIsInvalid
|
||||
{
|
||||
internal SafeSnapshotHandle() : base(true)
|
||||
{
|
||||
}
|
||||
|
||||
[SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)]
|
||||
internal SafeSnapshotHandle(IntPtr handle) : base(true)
|
||||
{
|
||||
base.SetHandle(handle);
|
||||
}
|
||||
|
||||
protected override bool ReleaseHandle()
|
||||
{
|
||||
return CloseHandle(base.handle);
|
||||
}
|
||||
|
||||
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success), DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool CloseHandle(IntPtr handle);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
|
@ -7,6 +7,7 @@ namespace gsudo.Native
|
||||
/// <summary>
|
||||
/// PInvoke signatures for win32 pseudo console api
|
||||
/// </summary>
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1060:Move pinvokes to native methods class", Justification = "Done")]
|
||||
static class PseudoConsoleApi
|
||||
{
|
||||
internal const uint PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE = 0x00020016;
|
||||
|
12
src/gsudo/Native/WindowApi.cs
Normal file
12
src/gsudo/Native/WindowApi.cs
Normal file
@ -0,0 +1,12 @@
|
||||
using System;
|
||||
|
||||
namespace gsudo.Native
|
||||
{
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1060:Move pinvokes to native methods class", Justification = "<Pending>")]
|
||||
static class WindowApi
|
||||
{
|
||||
[System.Runtime.InteropServices.DllImport("user32.dll")]
|
||||
public static extern int SetForegroundWindow(IntPtr hwnd);
|
||||
|
||||
}
|
||||
}
|
@ -14,11 +14,9 @@ namespace gsudo.ProcessHosts
|
||||
var exitCode = 0;
|
||||
try
|
||||
{
|
||||
|
||||
Native.ConsoleApi.FreeConsole();
|
||||
uint pid = (uint)elevationRequest.ConsoleProcessId;
|
||||
const uint ATTACH_PARENT_PROCESS = 0x0ffffffff; // default value if not specifing a process ID
|
||||
|
||||
|
||||
if (Native.ConsoleApi.AttachConsole(pid))
|
||||
{
|
||||
Native.ConsoleApi.SetConsoleCtrlHandler(HandleConsoleCancelKeyPress, true);
|
||||
@ -36,7 +34,7 @@ namespace gsudo.ProcessHosts
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await connection.ControlStream.WriteAsync($"{Constants.TOKEN_ERROR}Server Error:{ex.ToString()}\r\n{Constants.TOKEN_ERROR}");
|
||||
await connection.ControlStream.WriteAsync($"{Constants.TOKEN_ERROR}Server Error:{ex.ToString()}\r\n{Constants.TOKEN_ERROR}").ConfigureAwait(false);
|
||||
exitCode = Constants.GSUDO_ERROR_EXITCODE;
|
||||
}
|
||||
}
|
||||
@ -56,7 +54,7 @@ namespace gsudo.ProcessHosts
|
||||
{
|
||||
Native.ConsoleApi.SetConsoleCtrlHandler(HandleConsoleCancelKeyPress, false);
|
||||
Native.ConsoleApi.FreeConsole();
|
||||
await connection.FlushAndCloseAll();
|
||||
await connection.FlushAndCloseAll().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -31,8 +31,6 @@ namespace gsudo.ProcessHosts
|
||||
var t3 = new StreamReader(connection.DataStream, GlobalSettings.Encoding).ConsumeOutput((s) => WriteToProcessStdIn(s, process));
|
||||
var t4 = new StreamReader(connection.ControlStream, GlobalSettings.Encoding).ConsumeOutput((s) => HandleControl(s, process));
|
||||
|
||||
int i = 0;
|
||||
|
||||
WaitHandle.WaitAny(new WaitHandle[] { process.GetWaitHandle(), connection.DisconnectedWaitHandle });
|
||||
|
||||
if (process.HasExited && connection.IsAlive)
|
||||
|
@ -90,7 +90,7 @@ namespace gsudo.ProcessRenderers
|
||||
if (CurrentMode == Mode.Focus)
|
||||
{
|
||||
var hwnd = (IntPtr)int.Parse(token, CultureInfo.InvariantCulture);
|
||||
Logger.Instance.Log($"SetForegroundWindow({hwnd}) returned {ProcessFactory.SetForegroundWindow(hwnd)}", LogLevel.Debug);
|
||||
Logger.Instance.Log($"SetForegroundWindow({hwnd}) returned {Native.WindowApi.SetForegroundWindow(hwnd)}", LogLevel.Debug);
|
||||
continue;
|
||||
}
|
||||
if (CurrentMode == Mode.Error)
|
||||
|
@ -40,7 +40,6 @@ namespace gsudo.ProcessRenderers
|
||||
var t3 = new StreamReader(_connection.ControlStream, GlobalSettings.Encoding)
|
||||
.ConsumeOutput((s) => HandleControlData(s));
|
||||
|
||||
int i = 0;
|
||||
while (_connection.IsAlive)
|
||||
{
|
||||
await Task.Delay(10).ConfigureAwait(false);
|
||||
@ -91,11 +90,11 @@ namespace gsudo.ProcessRenderers
|
||||
if (++consecutiveCancelKeys > 2)
|
||||
{
|
||||
Logger.Instance.Log("Press CTRL-C again to stop gsudo", LogLevel.Warning);
|
||||
_connection.ControlStream.WriteAsync(Constants.TOKEN_KEY_CTRLBREAK); // .GetAwaiter().GetResult();
|
||||
_ = _connection.ControlStream.WriteAsync(Constants.TOKEN_KEY_CTRLBREAK); // .GetAwaiter().GetResult();
|
||||
}
|
||||
else
|
||||
{
|
||||
_connection.ControlStream.WriteAsync(Constants.TOKEN_KEY_CTRLC); //.GetAwaiter().GetResult();
|
||||
_ = _connection.ControlStream.WriteAsync(Constants.TOKEN_KEY_CTRLC); //.GetAwaiter().GetResult();
|
||||
}
|
||||
}
|
||||
|
||||
@ -158,7 +157,7 @@ namespace gsudo.ProcessRenderers
|
||||
if (CurrentMode == Mode.Focus)
|
||||
{
|
||||
var hwnd = (IntPtr)int.Parse(token, CultureInfo.InvariantCulture);
|
||||
Logger.Instance.Log($"SetForegroundWindow({hwnd}) returned {ProcessFactory.SetForegroundWindow(hwnd)}", LogLevel.Debug);
|
||||
Logger.Instance.Log($"SetForegroundWindow({hwnd}) returned {Native.WindowApi.SetForegroundWindow(hwnd)}", LogLevel.Debug);
|
||||
continue;
|
||||
}
|
||||
if (CurrentMode == Mode.Error)
|
||||
|
@ -39,7 +39,6 @@ namespace gsudo.ProcessRenderers
|
||||
var t2 = new StreamReader(_connection.ControlStream, GlobalSettings.Encoding)
|
||||
.ConsumeOutput((s) => HandleControlData(s));
|
||||
|
||||
int i = 0;
|
||||
while (_connection.IsAlive)
|
||||
{
|
||||
try
|
||||
@ -49,7 +48,7 @@ namespace gsudo.ProcessRenderers
|
||||
consecutiveCancelKeys = 0;
|
||||
// send input character-by-character to the pipe
|
||||
var key = Console.ReadKey(intercept: true);
|
||||
byte[] sequence = TerminalHelper.GetSequenceFromConsoleKey(key, GlobalSettings.Debug && _elevationRequest.FileName.EndsWith("KeyPressTester.exe"));
|
||||
byte[] sequence = TerminalHelper.GetSequenceFromConsoleKey(key, GlobalSettings.Debug && _elevationRequest.FileName.EndsWith("KeyPressTester.exe", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
_connection.DataStream.Write(sequence, 0, sequence.Length);
|
||||
}
|
||||
@ -147,7 +146,7 @@ namespace gsudo.ProcessRenderers
|
||||
enum Mode { Normal, Focus, Error, ExitCode };
|
||||
Mode CurrentMode = Mode.Normal;
|
||||
|
||||
private async Task HandleControlData(string s)
|
||||
private Task HandleControlData(string s)
|
||||
{
|
||||
Action<Mode> Toggle = (m) => CurrentMode = CurrentMode == Mode.Normal ? m : Mode.Normal;
|
||||
|
||||
@ -182,7 +181,7 @@ namespace gsudo.ProcessRenderers
|
||||
Console.Write(token);
|
||||
}
|
||||
|
||||
return;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private async Task IncomingKey(string s, NamedPipeClientStream pipe)
|
||||
|
@ -45,7 +45,7 @@ namespace gsudo.PseudoConsole
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
ClosePseudoConsole(Handle);
|
||||
_ = ClosePseudoConsole(Handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user