-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathProgram.cs
220 lines (210 loc) · 8.45 KB
/
Program.cs
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
using System;
using System.CommandLine;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Nodes;
using WSLAttachSwitch.ComputeService;
namespace WSLAttachSwitch
{
class Program
{
static ComputeNetwork FindNetworkByName(string name)
{
var networks = ComputeNetwork.Enumerate();
foreach (var id in networks)
{
var network = ComputeNetwork.Open(id);
if (name.Equals(network.QueryProperites().GetProperty("Name").GetString(), StringComparison.OrdinalIgnoreCase))
{
return network;
}
network.Close();
}
throw Marshal.GetExceptionForHR(unchecked((int)0x80070037));
}
static Guid XorGuid(in Guid input, ReadOnlySpan<byte> xorWith)
{
var guidbytes = input.ToByteArray();
var minlen = Math.Min(xorWith.Length, guidbytes.Length);
for (int i = 0; i < minlen; i++)
{
guidbytes[i] ^= xorWith[i];
}
return new Guid(guidbytes);
}
static bool Attach(string networkName, string macAddress = null, int? vlanIsolationId = null)
{
try
{
var systems = ComputeSystem.Enumerate(new JsonObject { ["Owners"] = new JsonArray("WSL") });
if (systems.Length != 1)
{
Console.Error.WriteLine("Can't find unique WSL VM. Is WSL2 running?");
return false;
}
var systemid = systems[0].GetProperty("Id").GetString();
using var system = ComputeSystem.Open(systemid);
var props = system.QueryProperites();
ComputeNetwork network;
if (Guid.TryParse(networkName, out var netid))
{
network = ComputeNetwork.Open(netid);
}
else
{
network = FindNetworkByName(networkName);
var netprops = network.QueryProperites();
netid = new Guid(netprops.GetProperty("ID").GetString());
}
var epid = XorGuid(netid, "WSL2BrdgEp"u8);
var eps = ComputeNetworkEndpoint.Enumerate();
if (Array.Exists(eps, x => x == epid))
{
using var oldendpoint = ComputeNetworkEndpoint.Open(epid);
var epprops = oldendpoint.QueryProperites();
if (!epprops.TryGetProperty("VirtualMachine", out JsonElement vmJsonElement) || vmJsonElement.GetString() != systemid)
{
// endpoint not attached to current WSL2 VM, recreate it
ComputeNetworkEndpoint.Delete(epid);
}
else
{
Console.WriteLine("Endpoint already attached to current WSL2 VM.");
return true;
}
}
JsonNode policies = null;
if (vlanIsolationId != null)
{
policies = new JsonArray(
new JsonObject
{
["Type"] = "VLAN",
["Settings"] = new JsonObject { ["IsolationId"] = (int)vlanIsolationId },
}
);
}
using var endpoint = ComputeNetworkEndpoint.Create(network, epid, new JsonObject
{
["VirtualNetwork"] = netid.ToString(),
["MacAddress"] = macAddress,
["Policies"] = policies
});
system.Modify(
"VirtualMachine/Devices/NetworkAdapters/bridge_" + netid.ToString("N"),
ModifyRequestType.Add,
new JsonObject { ["EndpointId"] = epid.ToString(), ["MacAddress"] = macAddress },
null
);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
return false;
}
return true;
}
static string ParseMacAddress(string input)
{
if (input.Length == 17)
{
// XX-XX-XX-XX-XX-XX
var sep = input[2];
if (sep != ':' && sep != '-' && sep != '.') return null;
for (int i = 0; i < 17; i += 1)
{
if (i == 2 || i == 5 || i == 8 || i == 11 || i == 14)
{
if (input[i] != sep) return null;
}
else if (!Uri.IsHexDigit(input[i]))
{
return null;
}
}
return input.Replace(sep, '-').ToUpperInvariant();
}
else if (input.Length == 14)
{
// XXXX-XXXX-XXXX
var sep = input[4];
if (sep != ':' && sep != '-' && sep != '.') return null;
for (int i = 0; i < 14; i += 1)
{
if (i == 4 || i == 9)
{
if (input[i] != sep) return null;
}
else if (!Uri.IsHexDigit(input[i]))
{
return null;
}
}
return string.Format("{0}-{1}-{2}-{3}-{4}-{5}",
input.Substring(0, 2),
input.Substring(2, 2),
input.Substring(5, 2),
input.Substring(7, 2),
input.Substring(10, 2),
input.Substring(12, 2)
).ToUpperInvariant();
}
else if (input.Length == 12)
{
// XXXXXXXXXXXX
for (int i = 0; i < 12; i += 1)
{
if (!Uri.IsHexDigit(input[i]))
{
return null;
}
}
return string.Format("{0}-{1}-{2}-{3}-{4}-{5}",
input.Substring(0, 2),
input.Substring(2, 2),
input.Substring(4, 2),
input.Substring(6, 2),
input.Substring(8, 2),
input.Substring(10, 2)
).ToUpperInvariant();
}
return null;
}
static int Main(string[] args)
{
var command = new RootCommand("Attach a Hyper-V virtual switch to the WSL2 virtual machine");
var macAddressOption = new Option<string>(
name: "--mac",
description: "If specified, use this physical address for the virtual interface instead of random one.",
parseArgument: static result =>
{
if (result.Tokens.Count == 0) return null;
var raw = result.Tokens.Single().Value;
var mac = Program.ParseMacAddress(raw);
if (mac == null) result.ErrorMessage = "Invalid MAC address";
return mac;
});
var vlanIdOption = new Option<int?>("--vlan", "If specified, enable VLAN filtering with this VLAN ID for the virtual interface.");
vlanIdOption.AddValidator(static result =>
{
var vlanid = result.GetValueOrDefault<int?>();
if (vlanid != null && (vlanid < 0 || vlanid > 4095))
{
result.ErrorMessage = "VLAN ID must be between 0 and 4095";
}
});
var networkArg = new Argument<string>("network name or GUID", "Name or GUID of the virtual switch to attach to the WSL2 virtual machine. Check availiable networks with `hnsdiag list networks`");
command.AddOption(macAddressOption);
command.AddOption(vlanIdOption);
command.AddArgument(networkArg);
var status = 0;
command.SetHandler((network, macAddress, vlanId) =>
{
status = Attach(network, macAddress, vlanId) ? 0 : 1;
}, networkArg, macAddressOption, vlanIdOption);
command.Invoke(args);
return status;
}
}
}