This repository was archived by the owner on Dec 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 514
Expand file tree
/
Copy pathAddressBinder.cs
More file actions
309 lines (264 loc) · 11.6 KB
/
Copy pathAddressBinder.cs
File metadata and controls
309 lines (264 loc) · 11.6 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
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
using Microsoft.AspNetCore.Server.Kestrel.Transport.Abstractions.Internal;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal
{
internal class AddressBinder
{
public static async Task BindAsync(IServerAddressesFeature addresses,
List<ListenOptions> listenOptions,
ILogger logger,
Func<ListenOptions, Task> createBinding)
{
var strategy = CreateStrategy(
listenOptions.ToArray(),
addresses.Addresses.ToArray(),
addresses.PreferHostingUrls);
var context = new AddressBindContext
{
Addresses = addresses.Addresses,
ListenOptions = listenOptions,
Logger = logger,
CreateBinding = createBinding
};
// reset options. The actual used options and addresses will be populated
// by the address binding feature
listenOptions.Clear();
addresses.Addresses.Clear();
await strategy.BindAsync(context).ConfigureAwait(false);
}
private class AddressBindContext
{
public ICollection<string> Addresses { get; set; }
public List<ListenOptions> ListenOptions { get; set; }
public ILogger Logger { get; set; }
public Func<ListenOptions, Task> CreateBinding { get; set; }
}
private static IStrategy CreateStrategy(ListenOptions[] listenOptions, string[] addresses, bool preferAddresses)
{
var hasListenOptions = listenOptions.Length > 0;
var hasAddresses = addresses.Length > 0;
if (preferAddresses && hasAddresses)
{
if (hasListenOptions)
{
return new OverrideWithAddressesStrategy(addresses);
}
return new AddressesStrategy(addresses);
}
else if (hasListenOptions)
{
if (hasAddresses)
{
return new OverrideWithEndpointsStrategy(listenOptions, addresses);
}
return new EndpointsStrategy(listenOptions);
}
else if (hasAddresses)
{
// If no endpoints are configured directly using KestrelServerOptions, use those configured via the IServerAddressesFeature.
return new AddressesStrategy(addresses);
}
else
{
// "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
return new DefaultAddressStrategy();
}
}
/// <summary>
/// Returns an <see cref="IPEndPoint"/> for the given host an port.
/// If the host parameter isn't "localhost" or an IP address, use IPAddress.Any.
/// </summary>
protected internal static bool TryCreateIPEndPoint(ServerAddress address, out IPEndPoint endpoint)
{
if (!IPAddress.TryParse(address.Host, out var ip))
{
endpoint = null;
return false;
}
endpoint = new IPEndPoint(ip, address.Port);
return true;
}
private static Task BindEndpointAsync(IPEndPoint endpoint, AddressBindContext context)
=> BindEndpointAsync(new ListenOptions(endpoint), context);
private static async Task BindEndpointAsync(ListenOptions endpoint, AddressBindContext context)
{
try
{
await context.CreateBinding(endpoint).ConfigureAwait(false);
}
catch (AddressInUseException ex)
{
throw new IOException(CoreStrings.FormatEndpointAlreadyInUse(endpoint), ex);
}
context.ListenOptions.Add(endpoint);
}
private static async Task BindLocalhostAsync(ServerAddress address, AddressBindContext context)
{
if (address.Port == 0)
{
throw new InvalidOperationException(CoreStrings.DynamicPortOnLocalhostNotSupported);
}
var exceptions = new List<Exception>();
try
{
await BindEndpointAsync(new IPEndPoint(IPAddress.Loopback, address.Port), context).ConfigureAwait(false);
}
catch (Exception ex) when (!(ex is IOException))
{
context.Logger.LogWarning(0, CoreStrings.NetworkInterfaceBindingFailed, address, "IPv4 loopback", ex.Message);
exceptions.Add(ex);
}
try
{
await BindEndpointAsync(new IPEndPoint(IPAddress.IPv6Loopback, address.Port), context).ConfigureAwait(false);
}
catch (Exception ex) when (!(ex is IOException))
{
context.Logger.LogWarning(0, CoreStrings.NetworkInterfaceBindingFailed, address, "IPv6 loopback", ex.Message);
exceptions.Add(ex);
}
if (exceptions.Count == 2)
{
throw new IOException(CoreStrings.FormatAddressBindingFailed(address), new AggregateException(exceptions));
}
// If StartLocalhost doesn't throw, there is at least one listener.
// The port cannot change for "localhost".
context.Addresses.Add(address.ToString());
}
private static async Task BindAddressAsync(string address, AddressBindContext context)
{
var parsedAddress = ServerAddress.FromUrl(address);
if (parsedAddress.Scheme.Equals("https", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(CoreStrings.FormatConfigureHttpsFromMethodCall($"{nameof(KestrelServerOptions)}.{nameof(KestrelServerOptions.Listen)}()"));
}
else if (!parsedAddress.Scheme.Equals("http", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(CoreStrings.FormatUnsupportedAddressScheme(address));
}
if (!string.IsNullOrEmpty(parsedAddress.PathBase))
{
throw new InvalidOperationException(CoreStrings.FormatConfigurePathBaseFromMethodCall($"{nameof(IApplicationBuilder)}.UsePathBase()"));
}
if (parsedAddress.IsUnixPipe)
{
var endPoint = new ListenOptions(parsedAddress.UnixPipePath);
await BindEndpointAsync(endPoint, context).ConfigureAwait(false);
context.Addresses.Add(endPoint.GetDisplayName());
}
else if (string.Equals(parsedAddress.Host, "localhost", StringComparison.OrdinalIgnoreCase))
{
// "localhost" for both IPv4 and IPv6 can't be represented as an IPEndPoint.
await BindLocalhostAsync(parsedAddress, context).ConfigureAwait(false);
}
else
{
ListenOptions options;
if (TryCreateIPEndPoint(parsedAddress, out var endpoint))
{
options = new ListenOptions(endpoint);
await BindEndpointAsync(options, context).ConfigureAwait(false);
}
else
{
// when address is 'http://hostname:port', 'http://*:port', or 'http://+:port'
try
{
options = new ListenOptions(new IPEndPoint(IPAddress.IPv6Any, parsedAddress.Port));
await BindEndpointAsync(options, context).ConfigureAwait(false);
}
catch (Exception ex) when (!(ex is IOException))
{
context.Logger.LogDebug(CoreStrings.FormatFallbackToIPv4Any(parsedAddress.Port));
// for machines that do not support IPv6
options = new ListenOptions(new IPEndPoint(IPAddress.Any, parsedAddress.Port));
await BindEndpointAsync(options, context).ConfigureAwait(false);
}
}
context.Addresses.Add(options.GetDisplayName());
}
}
private interface IStrategy
{
Task BindAsync(AddressBindContext context);
}
private class DefaultAddressStrategy : IStrategy
{
public async Task BindAsync(AddressBindContext context)
{
context.Logger.LogDebug(CoreStrings.BindingToDefaultAddress, Constants.DefaultServerAddress);
await BindLocalhostAsync(ServerAddress.FromUrl(Constants.DefaultServerAddress), context).ConfigureAwait(false);
}
}
private class OverrideWithAddressesStrategy : AddressesStrategy
{
public OverrideWithAddressesStrategy(IReadOnlyCollection<string> addresses)
: base(addresses)
{
}
public override Task BindAsync(AddressBindContext context)
{
var joined = string.Join(", ", _addresses);
context.Logger.LogInformation(CoreStrings.OverridingWithPreferHostingUrls, nameof(IServerAddressesFeature.PreferHostingUrls), joined);
return base.BindAsync(context);
}
}
private class OverrideWithEndpointsStrategy : EndpointsStrategy
{
private readonly string[] _originalAddresses;
public OverrideWithEndpointsStrategy(IReadOnlyCollection<ListenOptions> endpoints, string[] originalAddresses)
: base(endpoints)
{
_originalAddresses = originalAddresses;
}
public override Task BindAsync(AddressBindContext context)
{
var joined = string.Join(", ", _originalAddresses);
context.Logger.LogWarning(CoreStrings.OverridingWithKestrelOptions, joined, "UseKestrel()");
return base.BindAsync(context);
}
}
private class EndpointsStrategy : IStrategy
{
private readonly IReadOnlyCollection<ListenOptions> _endpoints;
public EndpointsStrategy(IReadOnlyCollection<ListenOptions> endpoints)
{
_endpoints = endpoints;
}
public virtual async Task BindAsync(AddressBindContext context)
{
foreach (var endpoint in _endpoints)
{
await BindEndpointAsync(endpoint, context).ConfigureAwait(false);
context.Addresses.Add(endpoint.GetDisplayName());
}
}
}
private class AddressesStrategy : IStrategy
{
protected readonly IReadOnlyCollection<string> _addresses;
public AddressesStrategy(IReadOnlyCollection<string> addresses)
{
_addresses = addresses;
}
public virtual async Task BindAsync(AddressBindContext context)
{
foreach (var address in _addresses)
{
await BindAddressAsync(address, context).ConfigureAwait(false);
}
}
}
}
}