Skip to content

Commit

Permalink
Merge branch 'master' into Feature.MSIUpdateInUse
Browse files Browse the repository at this point in the history
  • Loading branch information
gerardog authored Nov 22, 2022
2 parents bce6013 + 7d67117 commit 392f2af
Show file tree
Hide file tree
Showing 5 changed files with 60 additions and 52 deletions.
2 changes: 1 addition & 1 deletion docs/docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ const config = {
showReadingTime: true,
// Please change this to your repo.
editUrl:
'https://github.com/gerardog/gsudo/tree/docs/docs/blog/',
'https://github.com/gerardog/gsudo/tree/master/docs/blog/',
},
theme: {
customCss: require.resolve('./src/css/custom.css'),
Expand Down
26 changes: 15 additions & 11 deletions src/gsudo.Wrappers/Invoke-gsudo.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ if ($Debug) {
Write-Debug "Full Script to run on the isolated instance: { $remoteCmd }"
}

$pwsh = ("""$([System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName)""") # Get same running powershell EXE.
$pwsh = ("$([System.Diagnostics.Process]::GetCurrentProcess().MainModule.FileName)") # Get same running powershell EXE.

if ($host.Name -notmatch 'consolehost') { # Workaround for PowerShell ISE, or PS hosted inside other process
if ($PSVersionTable.PSVersion.Major -le 5)
Expand All @@ -150,18 +150,12 @@ if ($host.Name -notmatch 'consolehost') { # Workaround for PowerShell ISE, or PS
}

$windowTitle = $host.ui.RawUI.WindowTitle;

$dbg = if ($debug) {"--debug "} else {" "}

if ($LoadProfile -and (-not $NoProfile -or (gsudo.exe --loglevel None config PowerShellLoadProfile).Split(" = ")[1] -like "*true*")) {
$sNoProfile = ""
} else {
$sNoProfile = "-NoProfile "
}
$arguments = "-d", "--LogLevel", "Error"

if ($credential) {
$currentSid = ([System.Security.Principal.WindowsIdentity]::GetCurrent()).User.Value;
$user = "-u $($credential.UserName) "
$arguments += "-u", $credential.UserName

# At the time of writing this, there is no way (considered secure) to send the password to gsudo. So instead of sending the password, lets start a credentials cache instance.
Start-Process "gsudo.exe" -Args "$dbg -u $($credential.UserName) gsudoservice $PID $CurrentSid All 00:05:00" -credential $Credential -LoadUserProfile -WorkingDirectory "$env:windir" *> $null
Expand All @@ -173,10 +167,20 @@ if ($credential) {
$user = "";
}

$arguments = "-d --LogLevel Error $user$dbg$pwsh $sNoProfile -nologo -NonInteractive -OutputFormat Xml -InputFormat Text -encodedCommand IAAoACQAaQBuAHAAdQB0ACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAKQAgAHwAIABpAGUAeAAgAA==".Split(" ")
if ($debug) { $arguments += "--debug"}

$arguments += $pwsh

if ($LoadProfile -and (-not $NoProfile -or (gsudo.exe --loglevel None config PowerShellLoadProfile).Split(" = ")[1] -like "*true*")) {
} else {
$arguments += "-NoProfile"
}

$arguments += "-NoLogo", "-NonInteractive", "-OutputFormat", "Xml", "-InputFormat", "Text", "-encodedCommand", "IAAoACQAaQBuAHAAdQB0ACAAfAAgAE8AdQB0AC0AUwB0AHIAaQBuAGcAKQAgAHwAIABpAGUAeAAgAA=="

# Must Read: https://stackoverflow.com/questions/68136128/how-do-i-call-the-powershell-cli-robustly-with-respect-to-character-encoding-i?noredirect=1&lq=1

$result = $remoteCmd | & gsudo.exe $arguments *>&1
$result = $remoteCmd | & gsudo.exe @arguments *>&1

$host.ui.RawUI.WindowTitle = $windowTitle;

Expand Down
9 changes: 6 additions & 3 deletions src/gsudo/Helpers/CommandToRunAdapter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,9 +163,12 @@ Running ./gsudo {command} should elevate the powershell command.
}
// ----

string pscommand = string.Join(" ", args)
.ReplaceOrdinal("\"", "\\\"")
.Quote();
string pscommand = string.Join(" ", args);

if (ShellHelper.GetInvokingShellVersion() < new Version(7, 3, 0))
pscommand = pscommand.ReplaceOrdinal("\"", "\\\"");

pscommand = pscommand.Quote();

newArgs.Add(pscommand);
}
Expand Down
69 changes: 35 additions & 34 deletions src/gsudo/Helpers/ShellHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,7 @@ public static string InvokingShellFullPath
{
get
{
if (!IsIntialized)
{
_invokingShell = Initialize(out _invokingShellFullPath);
IsIntialized = true;
}

if (!IsIntialized) Initialize();
return _invokingShellFullPath;
}
}
Expand All @@ -42,19 +37,20 @@ public static Shell InvokingShell
{
get
{
if (!IsIntialized)
{
_invokingShell = Initialize(out _invokingShellFullPath);
IsIntialized = true;
}

if (!IsIntialized) Initialize();
return _invokingShell.Value;
}
}

private static bool IsIntialized { get; set; }

private static Shell Initialize(out string invokingShellFullPath)
private static void Initialize()
{
_invokingShell = InitializeInternal(out _invokingShellFullPath);
IsIntialized = true;
}

private static Shell InitializeInternal(out string invokingShellFullPath)
{
var parentProcess = Process.GetCurrentProcess().GetParentProcessExcludingShim();

Expand All @@ -63,37 +59,34 @@ private static Shell Initialize(out string invokingShellFullPath)
invokingShellFullPath = parentProcess.GetExeName();

var shell = DetectShellByFileName(invokingShellFullPath);

if (shell.HasValue)
return shell.Value;
else
// Depending on how pwsh was installed, Pwsh.exe -calls-> dotnet -calls-> gsudo.
var grandParentProcess = parentProcess.GetParentProcessExcludingShim();
if (grandParentProcess != null)
{
// Depending on how pwsh was installed, Pwsh.exe -calls-> dotnet -calls-> gsudo.
var grandParentProcess = parentProcess.GetParentProcessExcludingShim();
if (grandParentProcess != null)
var grandParentExeName = Path.GetFileName(grandParentProcess.GetExeName()).ToUpperInvariant();
if (grandParentExeName == "PWSH.EXE" || grandParentExeName == "PWSH")
{
var grandParentExeName = Path.GetFileName(grandParentProcess.GetExeName()).ToUpperInvariant();
if (grandParentExeName == "PWSH.EXE" || grandParentExeName == "PWSH")
{
invokingShellFullPath = grandParentProcess.GetExeName();
invokingShellFullPath = grandParentProcess.GetExeName();

FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(invokingShellFullPath);
Version fileVersion = GetInvokingShellVersion();

if (Version.Parse(versionInfo.FileVersion) <= Version.Parse("6.2.3.0") && invokingShellFullPath.EndsWith(".dotnet\\tools\\pwsh.exe", StringComparison.OrdinalIgnoreCase))
{
return Helpers.Shell.PowerShellCore623BuggedGlobalInstall;
}

return Helpers.Shell.PowerShellCore;
if (fileVersion <= new Version(6, 2, 3) && invokingShellFullPath.EndsWith(".dotnet\\tools\\pwsh.exe", StringComparison.OrdinalIgnoreCase))
{
return Helpers.Shell.PowerShellCore623BuggedGlobalInstall;
}
}

if (ProcessFactory.IsWindowsApp(invokingShellFullPath))
{
invokingShellFullPath = Environment.GetEnvironmentVariable("COMSPEC");
return Helpers.Shell.WindowsApp; // Called from explorer.exe, task mgr, etc.
return Helpers.Shell.PowerShellCore;
}
}

if (ProcessFactory.IsWindowsApp(invokingShellFullPath))
{
invokingShellFullPath = Environment.GetEnvironmentVariable("COMSPEC");
return Helpers.Shell.WindowsApp; // Called from explorer.exe, task mgr, etc.
}
}

// Unknown Shell.
Expand All @@ -102,6 +95,14 @@ private static Shell Initialize(out string invokingShellFullPath)
invokingShellFullPath = Environment.GetEnvironmentVariable("COMSPEC");
return Helpers.Shell.Cmd;
}


public static Version GetInvokingShellVersion()
{
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(_invokingShellFullPath);
var fileVersion = new Version(versionInfo.FileMajorPart, versionInfo.FileMinorPart, versionInfo.FileBuildPart);
return fileVersion;
}

public static Shell? DetectShellByFileName(string filename)
{
Expand Down
6 changes: 3 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -4835,9 +4835,9 @@ loader-runner@^4.2.0:
integrity sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==

loader-utils@^2.0.0:
version "2.0.3"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.3.tgz#d4b15b8504c63d1fc3f2ade52d41bc8459d6ede1"
integrity sha512-THWqIsn8QRnvLl0shHYVBN9syumU8pYWEHPTmkiVGd+7K5eFNVSY6AJhRvgGF70gg1Dz+l/k8WicvFCxdEs60A==
version "2.0.4"
resolved "https://registry.yarnpkg.com/loader-utils/-/loader-utils-2.0.4.tgz#8b5cb38b5c34a9a018ee1fc0e6a066d1dfcc528c"
integrity sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==
dependencies:
big.js "^5.2.2"
emojis-list "^3.0.0"
Expand Down

0 comments on commit 392f2af

Please sign in to comment.