Skip to content

Commit

Permalink
One more thing...
Browse files Browse the repository at this point in the history
  • Loading branch information
Steve Pfister committed Jul 13, 2020
1 parent 952997c commit c7343fa
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 36 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -74,5 +74,41 @@ public static unsafe string UserName

}
}

private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string? username)
{
// Call getpwuid_r to get the passwd struct
Interop.Sys.Passwd passwd;
int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen);

// If the call succeeds, give back the user name retrieved
if (error == 0)
{
Debug.Assert(passwd.Name != null);
username = Marshal.PtrToStringAnsi((IntPtr)passwd.Name);
return true;
}

// If the current user's entry could not be found, give back null,
// but still return true (false indicates the buffer was too small).
if (error == -1)
{
username = null;
return true;
}

var errorInfo = new Interop.ErrorInfo(error);

// If the call failed because the buffer was too small, return false to
// indicate the caller should try again with a larger buffer.
if (errorInfo.Error == Interop.Error.ERANGE)
{
username = null;
return false;
}

// Otherwise, fail.
throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -56,42 +56,6 @@ private static string ExpandEnvironmentVariablesCore(string name)

public static int SystemPageSize => CheckedSysConf(Interop.Sys.SysConfName._SC_PAGESIZE);

private static unsafe bool TryGetUserNameFromPasswd(byte* buf, int bufLen, out string? username)
{
// Call getpwuid_r to get the passwd struct
Interop.Sys.Passwd passwd;
int error = Interop.Sys.GetPwUidR(Interop.Sys.GetEUid(), out passwd, buf, bufLen);

// If the call succeeds, give back the user name retrieved
if (error == 0)
{
Debug.Assert(passwd.Name != null);
username = Marshal.PtrToStringAnsi((IntPtr)passwd.Name);
return true;
}

// If the current user's entry could not be found, give back null,
// but still return true (false indicates the buffer was too small).
if (error == -1)
{
username = null;
return true;
}

var errorInfo = new Interop.ErrorInfo(error);

// If the call failed because the buffer was too small, return false to
// indicate the caller should try again with a larger buffer.
if (errorInfo.Error == Interop.Error.ERANGE)
{
username = null;
return false;
}

// Otherwise, fail.
throw new IOException(errorInfo.GetErrorMessage(), errorInfo.RawErrno);
}

public static string UserDomainName => MachineName;

/// <summary>Invoke <see cref="Interop.Sys.SysConf"/>, throwing if it fails.</summary>
Expand Down

0 comments on commit c7343fa

Please sign in to comment.