aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/HttpServer/HttpListenerHost.cs
blob: 27369960b0799a2bb28b5e2600cd11156f00c4ad (plain)
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
310
311
312
313
314
315
#pragma warning disable CS1591

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Threading.Tasks;
using Jellyfin.Data.Events;
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Net;
using MediaBrowser.Model.Globalization;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;

namespace Emby.Server.Implementations.HttpServer
{
    public class HttpListenerHost : IHttpServer
    {
        /// <summary>
        /// The key for a setting that specifies the default redirect path
        /// to use for requests where the URL base prefix is invalid or missing.
        /// </summary>
        public const string DefaultRedirectKey = "HttpListenerHost:DefaultRedirectPath";

        private readonly ILogger<HttpListenerHost> _logger;
        private readonly ILoggerFactory _loggerFactory;
        private readonly IServerConfigurationManager _config;
        private readonly INetworkManager _networkManager;
        private readonly string _defaultRedirectPath;
        private readonly string _baseUrlPrefix;

        private IWebSocketListener[] _webSocketListeners = Array.Empty<IWebSocketListener>();
        private bool _disposed = false;

        public HttpListenerHost(
            ILogger<HttpListenerHost> logger,
            IServerConfigurationManager config,
            IConfiguration configuration,
            INetworkManager networkManager,
            ILocalizationManager localizationManager,
            ILoggerFactory loggerFactory)
        {
            _logger = logger;
            _config = config;
            _defaultRedirectPath = configuration[DefaultRedirectKey];
            _baseUrlPrefix = _config.Configuration.BaseUrl;
            _networkManager = networkManager;
            _loggerFactory = loggerFactory;

            Instance = this;
            GlobalResponse = localizationManager.GetLocalizedString("StartupEmbyServerIsLoading");
        }

        public event EventHandler<GenericEventArgs<IWebSocketConnection>> WebSocketConnected;

        public static HttpListenerHost Instance { get; protected set; }

        public string[] UrlPrefixes { get; private set; }

        public string GlobalResponse { get; set; }

        private static string NormalizeConfiguredLocalAddress(string address)
        {
            var add = address.AsSpan().Trim('/');
            int index = add.IndexOf('/');
            if (index != -1)
            {
                add = add.Slice(index + 1);
            }

            return add.TrimStart('/').ToString();
        }

        private bool ValidateHost(string host)
        {
            var hosts = _config
                .Configuration
                .LocalNetworkAddresses
                .Select(NormalizeConfiguredLocalAddress)
                .ToList();

            if (hosts.Count == 0)
            {
                return true;
            }

            host ??= string.Empty;

            if (_networkManager.IsInPrivateAddressSpace(host))
            {
                hosts.Add("localhost");
                hosts.Add("127.0.0.1");

                return hosts.Any(i => host.IndexOf(i, StringComparison.OrdinalIgnoreCase) != -1);
            }

            return true;
        }

        private bool ValidateRequest(string remoteIp, bool isLocal)
        {
            if (isLocal)
            {
                return true;
            }

            if (_config.Configuration.EnableRemoteAccess)
            {
                var addressFilter = _config.Configuration.RemoteIPFilter.Where(i => !string.IsNullOrWhiteSpace(i)).ToArray();

                if (addressFilter.Length > 0 && !_networkManager.IsInLocalNetwork(remoteIp))
                {
                    if (_config.Configuration.IsRemoteIPFilterBlacklist)
                    {
                        return !_networkManager.IsAddressInSubnets(remoteIp, addressFilter);
                    }
                    else
                    {
                        return _networkManager.IsAddressInSubnets(remoteIp, addressFilter);
                    }
                }
            }
            else
            {
                if (!_networkManager.IsInLocalNetwork(remoteIp))
                {
                    return false;
                }
            }

            return true;
        }

        /// <inheritdoc />
        public Task RequestHandler(HttpContext context, Func<Task> next)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                return WebSocketRequestHandler(context);
            }

            return HttpRequestHandler(context, next);
        }

        /// <summary>
        /// Overridable method that can be used to implement a custom handler.
        /// </summary>
        private async Task HttpRequestHandler(HttpContext httpContext, Func<Task> next)
        {
            var cancellationToken = httpContext.RequestAborted;
            var httpRes = httpContext.Response;
            var host = httpContext.Request.Host.ToString();
            var localPath = httpContext.Request.Path.ToString();
            string remoteIp = httpContext.Request.RemoteIp();

            if (_disposed)
            {
                httpRes.StatusCode = 503;
                httpRes.ContentType = "text/plain";
                await httpRes.WriteAsync("Server shutting down", cancellationToken).ConfigureAwait(false);
                return;
            }

            if (!ValidateHost(host))
            {
                httpRes.StatusCode = 400;
                httpRes.ContentType = "text/plain";
                await httpRes.WriteAsync("Invalid host", cancellationToken).ConfigureAwait(false);
                return;
            }

            if (!ValidateRequest(remoteIp, httpContext.Request.IsLocal()))
            {
                httpRes.StatusCode = 403;
                httpRes.ContentType = "text/plain";
                await httpRes.WriteAsync("Forbidden", cancellationToken).ConfigureAwait(false);
                return;
            }

            if (string.Equals(httpContext.Request.Method, "OPTIONS", StringComparison.OrdinalIgnoreCase))
            {
                httpRes.StatusCode = 200;
                foreach (var (key, value) in GetDefaultCorsHeaders(httpContext))
                {
                    httpRes.Headers.Add(key, value);
                }

                httpRes.ContentType = "text/plain";
                await httpRes.WriteAsync(string.Empty, cancellationToken).ConfigureAwait(false);
                return;
            }

            if (string.Equals(localPath, _baseUrlPrefix + "/", StringComparison.OrdinalIgnoreCase)
                || string.Equals(localPath, _baseUrlPrefix, StringComparison.OrdinalIgnoreCase)
                || string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)
                || string.IsNullOrEmpty(localPath)
                || !localPath.StartsWith(_baseUrlPrefix, StringComparison.OrdinalIgnoreCase))
            {
                // Always redirect back to the default path if the base prefix is invalid or missing
                _logger.LogDebug("Normalizing a URL at {0}", localPath);
                httpRes.Redirect(_baseUrlPrefix + "/" + _defaultRedirectPath);
                return;
            }

            if (!string.IsNullOrEmpty(GlobalResponse))
            {
                // We don't want the address pings in ApplicationHost to fail
                if (localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1)
                {
                    httpRes.StatusCode = 503;
                    httpRes.ContentType = "text/html";
                    await httpRes.WriteAsync(GlobalResponse, cancellationToken).ConfigureAwait(false);
                    return;
                }
            }

            await next().ConfigureAwait(false);
        }

        private async Task WebSocketRequestHandler(HttpContext context)
        {
            if (_disposed)
            {
                return;
            }

            try
            {
                _logger.LogInformation("WS {IP} request", context.Connection.RemoteIpAddress);

                WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);

                using var connection = new WebSocketConnection(
                    _loggerFactory.CreateLogger<WebSocketConnection>(),
                    webSocket,
                    context.Connection.RemoteIpAddress,
                    context.Request.Query)
                {
                    OnReceive = ProcessWebSocketMessageReceived
                };

                WebSocketConnected?.Invoke(this, new GenericEventArgs<IWebSocketConnection>(connection));

                await connection.ProcessAsync().ConfigureAwait(false);
                _logger.LogInformation("WS {IP} closed", context.Connection.RemoteIpAddress);
            }
            catch (Exception ex) // Otherwise ASP.Net will ignore the exception
            {
                _logger.LogError(ex, "WS {IP} WebSocketRequestHandler error", context.Connection.RemoteIpAddress);
                if (!context.Response.HasStarted)
                {
                    context.Response.StatusCode = 500;
                }
            }
        }

        /// <inheritdoc />
        public IDictionary<string, string> GetDefaultCorsHeaders(HttpContext httpContext)
        {
            var origin = httpContext.Request.Headers["Origin"];
            if (origin == StringValues.Empty)
            {
                origin = httpContext.Request.Headers["Host"];
                if (origin == StringValues.Empty)
                {
                    origin = "*";
                }
            }

            var headers = new Dictionary<string, string>();
            headers.Add("Access-Control-Allow-Origin", origin);
            headers.Add("Access-Control-Allow-Credentials", "true");
            headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS");
            headers.Add("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization, Cookie");
            return headers;
        }

        /// <summary>
        /// Adds the rest handlers.
        /// </summary>
        /// <param name="listeners">The web socket listeners.</param>
        /// <param name="urlPrefixes">The URL prefixes. See <see cref="UrlPrefixes"/>.</param>
        public void Init(IEnumerable<IWebSocketListener> listeners, IEnumerable<string> urlPrefixes)
        {
            _webSocketListeners = listeners.ToArray();
            UrlPrefixes = urlPrefixes.ToArray();
        }

        /// <summary>
        /// Processes the web socket message received.
        /// </summary>
        /// <param name="result">The result.</param>
        private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
        {
            if (_disposed)
            {
                return Task.CompletedTask;
            }

            IEnumerable<Task> GetTasks()
            {
                foreach (var x in _webSocketListeners)
                {
                    yield return x.ProcessMessageAsync(result);
                }
            }

            return Task.WhenAll(GetTasks());
        }
    }
}