This repository was archived by the owner on Jun 21, 2023. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathCredentialSet.cs
More file actions
96 lines (82 loc) · 2.78 KB
/
Copy pathCredentialSet.cs
File metadata and controls
96 lines (82 loc) · 2.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using GitHub.Extensions;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
namespace GitHub.Authentication.CredentialManagement
{
public class CredentialSet : List<Credential>, IDisposable
{
public CredentialSet()
{
}
public CredentialSet(string target)
: this()
{
Guard.ArgumentNotEmptyString(target, nameof(target));
Target = target;
}
public string Target { get; set; }
bool disposed;
private void Dispose(bool disposing)
{
if (disposing)
{
if (disposed) return;
if (Count > 0)
{
ForEach(cred => cred.Dispose());
}
disposed = true;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public CredentialSet Load()
{
LoadInternal();
return this;
}
private void LoadInternal()
{
uint count;
IntPtr pCredentials;
bool result = NativeMethods.CredEnumerateW(Target, 0, out count, out pCredentials);
if (!result)
{
var lastError = Marshal.GetLastWin32Error();
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Win32Exception: {0}", new Win32Exception(lastError)));
return;
}
// Read in all of the pointers first
var ptrCredList = new IntPtr[count];
for (int i = 0; i < count; i++)
{
ptrCredList[i] = Marshal.ReadIntPtr(pCredentials, IntPtr.Size * i);
}
// Now let's go through all of the pointers in the list
// and create our Credential object(s)
var credentialHandles =
ptrCredList.Select(ptrCred => new NativeMethods.CriticalCredentialHandle(ptrCred)).ToList();
var existingCredentials = credentialHandles
.Select(handle => handle.GetCredential())
.Select(nativeCredential =>
{
Credential credential = new Credential();
credential.LoadInternal(nativeCredential);
return credential;
});
AddRange(existingCredentials);
// The individual credentials should not be free'd
credentialHandles.ForEach(handle => handle.SetHandleAsInvalid());
// Clean up memory to the Enumeration pointer
NativeMethods.CredFree(pCredentials);
}
}
}