-
Notifications
You must be signed in to change notification settings - Fork 9.8k
/
WebSocketMiddleware.cs
231 lines (205 loc) · 9.49 KB
/
WebSocketMiddleware.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
221
222
223
224
225
226
227
228
229
230
231
// 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.WebSockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.WebSockets
{
/// <summary>
/// Enables accepting WebSocket requests by adding a <see cref="IHttpWebSocketFeature"/>
/// to the <see cref="HttpContext"/> if the request is a valid WebSocket request.
/// </summary>
public class WebSocketMiddleware
{
private readonly RequestDelegate _next;
private readonly WebSocketOptions _options;
private readonly ILogger _logger;
private readonly bool _anyOriginAllowed;
private readonly List<string> _allowedOrigins;
/// <summary>
/// Creates a new instance of the <see cref="WebSocketMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="options">The configuration options.</param>
/// <param name="loggerFactory">An <see cref="ILoggerFactory"/> instance used to create loggers.</param>
public WebSocketMiddleware(RequestDelegate next, IOptions<WebSocketOptions> options, ILoggerFactory loggerFactory)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
_next = next;
_options = options.Value;
_allowedOrigins = _options.AllowedOrigins.Select(o => o.ToLowerInvariant()).ToList();
_anyOriginAllowed = _options.AllowedOrigins.Count == 0 || _options.AllowedOrigins.Contains("*", StringComparer.Ordinal);
_logger = loggerFactory.CreateLogger<WebSocketMiddleware>();
// TODO: validate options.
}
/// <summary>
/// Processes a request to determine if it is a WebSocket request, and if so,
/// sets the <see cref="IHttpWebSocketFeature"/> on the <see cref="HttpContext.Features"/>.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/> representing the request.</param>
/// <returns>The <see cref="Task"/> that represents the completion of the middleware pipeline.</returns>
public Task Invoke(HttpContext context)
{
// Detect if an opaque upgrade is available. If so, add a websocket upgrade.
var upgradeFeature = context.Features.Get<IHttpUpgradeFeature>();
if (upgradeFeature != null && context.Features.Get<IHttpWebSocketFeature>() == null)
{
var webSocketFeature = new UpgradeHandshake(context, upgradeFeature, _options);
context.Features.Set<IHttpWebSocketFeature>(webSocketFeature);
if (!_anyOriginAllowed)
{
// Check for Origin header
var originHeader = context.Request.Headers.Origin;
if (!StringValues.IsNullOrEmpty(originHeader) && webSocketFeature.IsWebSocketRequest)
{
// Check allowed origins to see if request is allowed
if (!_allowedOrigins.Contains(originHeader.ToString(), StringComparer.Ordinal))
{
_logger.LogDebug("Request origin {Origin} is not in the list of allowed origins.", originHeader);
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
}
}
}
}
return _next(context);
}
private class UpgradeHandshake : IHttpWebSocketFeature
{
private readonly HttpContext _context;
private readonly IHttpUpgradeFeature _upgradeFeature;
private readonly WebSocketOptions _options;
private bool? _isWebSocketRequest;
public UpgradeHandshake(HttpContext context, IHttpUpgradeFeature upgradeFeature, WebSocketOptions options)
{
_context = context;
_upgradeFeature = upgradeFeature;
_options = options;
}
public bool IsWebSocketRequest
{
get
{
if (_isWebSocketRequest == null)
{
if (!_upgradeFeature.IsUpgradableRequest)
{
_isWebSocketRequest = false;
}
else
{
_isWebSocketRequest = CheckSupportedWebSocketRequest(_context.Request.Method, _context.Request.Headers);
}
}
return _isWebSocketRequest.Value;
}
}
public async Task<WebSocket> AcceptAsync(WebSocketAcceptContext acceptContext)
{
if (!IsWebSocketRequest)
{
throw new InvalidOperationException("Not a WebSocket request."); // TODO: LOC
}
string? subProtocol = null;
if (acceptContext != null)
{
subProtocol = acceptContext.SubProtocol;
}
TimeSpan keepAliveInterval = _options.KeepAliveInterval;
if (acceptContext is ExtendedWebSocketAcceptContext advancedAcceptContext)
{
if (advancedAcceptContext.KeepAliveInterval.HasValue)
{
keepAliveInterval = advancedAcceptContext.KeepAliveInterval.Value;
}
}
string key = _context.Request.Headers.SecWebSocketKey;
HandshakeHelpers.GenerateResponseHeaders(key, subProtocol, _context.Response.Headers);
Stream opaqueTransport = await _upgradeFeature.UpgradeAsync(); // Sets status code to 101
return WebSocket.CreateFromStream(opaqueTransport, isServer: true, subProtocol: subProtocol, keepAliveInterval: keepAliveInterval);
}
public static bool CheckSupportedWebSocketRequest(string method, IHeaderDictionary requestHeaders)
{
if (!HttpMethods.IsGet(method))
{
return false;
}
var foundHeader = false;
var values = requestHeaders.GetCommaSeparatedValues(HeaderNames.SecWebSocketVersion);
foreach (var value in values)
{
if (string.Equals(value, Constants.Headers.SupportedVersion, StringComparison.OrdinalIgnoreCase))
{
// WebSockets are long lived; so if the header values are valid we switch them out for the interned versions.
if (values.Length == 1)
{
requestHeaders.SecWebSocketVersion = Constants.Headers.SupportedVersion;
}
foundHeader = true;
break;
}
}
if (!foundHeader)
{
return false;
}
foundHeader = false;
values = requestHeaders.GetCommaSeparatedValues(HeaderNames.Connection);
foreach (var value in values)
{
if (string.Equals(value, HeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
{
// WebSockets are long lived; so if the header values are valid we switch them out for the interned versions.
if (values.Length == 1)
{
requestHeaders.Connection = HeaderNames.Upgrade;
}
foundHeader = true;
break;
}
}
if (!foundHeader)
{
return false;
}
foundHeader = false;
values = requestHeaders.GetCommaSeparatedValues(HeaderNames.Upgrade);
foreach (var value in values)
{
if (string.Equals(value, Constants.Headers.UpgradeWebSocket, StringComparison.OrdinalIgnoreCase))
{
// WebSockets are long lived; so if the header values are valid we switch them out for the interned versions.
if (values.Length == 1)
{
requestHeaders.Upgrade = Constants.Headers.UpgradeWebSocket;
}
foundHeader = true;
break;
}
}
if (!foundHeader)
{
return false;
}
return HandshakeHelpers.IsRequestKeyValid(requestHeaders.SecWebSocketKey.ToString());
}
}
}
}