aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/SocketSharp/WebSocketSharpRequest.cs
blob: 38d0332308b06c1e13c96261693c7d8f41c6c408 (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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using Emby.Server.Implementations.HttpServer;
using MediaBrowser.Model.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using SocketHttpListener.Net;
using IHttpFile = MediaBrowser.Model.Services.IHttpFile;
using IHttpRequest = MediaBrowser.Model.Services.IHttpRequest;
using IHttpResponse = MediaBrowser.Model.Services.IHttpResponse;
using IResponse = MediaBrowser.Model.Services.IResponse;

namespace Emby.Server.Implementations.SocketSharp
{
    public partial class WebSocketSharpRequest : IHttpRequest
    {
        private readonly HttpRequest request;
        private readonly IHttpResponse response;

        public WebSocketSharpRequest(HttpRequest httpContext, HttpResponse response, string operationName, ILogger logger)
        {
            this.OperationName = operationName;
            this.request = httpContext;
            this.response = new WebSocketSharpResponse(logger, response, this);

            // HandlerFactoryPath = GetHandlerPathIfAny(UrlPrefixes[0]);
        }

        public HttpRequest HttpRequest => request;

        public object OriginalRequest => request;

        public IResponse Response => response;

        public IHttpResponse HttpResponse => response;

        public string OperationName { get; set; }

        public object Dto { get; set; }

        public string RawUrl => request.GetEncodedPathAndQuery();

        public string AbsoluteUri => request.GetDisplayUrl().TrimEnd('/');

        public string UserHostAddress => request.HttpContext.Connection.RemoteIpAddress.ToString();

        public string XForwardedFor
            => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-For"]) ? null : request.Headers["X-Forwarded-For"].ToString();

        public int? XForwardedPort
            => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Port"]) ? (int?)null : int.Parse(request.Headers["X-Forwarded-Port"], CultureInfo.InvariantCulture);

        public string XForwardedProtocol => StringValues.IsNullOrEmpty(request.Headers["X-Forwarded-Proto"]) ? null : request.Headers["X-Forwarded-Proto"].ToString();

        public string XRealIp => StringValues.IsNullOrEmpty(request.Headers["X-Real-IP"]) ? null : request.Headers["X-Real-IP"].ToString();

        private string remoteIp;

        public string RemoteIp =>
            remoteIp ??
            (remoteIp = CheckBadChars(XForwardedFor) ??
                        NormalizeIp(CheckBadChars(XRealIp) ??
                                    (string.IsNullOrEmpty(request.HttpContext.Connection.RemoteIpAddress.ToString()) ? null : NormalizeIp(request.HttpContext.Connection.RemoteIpAddress.ToString()))));

        private static readonly char[] HttpTrimCharacters = new char[] { (char)0x09, (char)0xA, (char)0xB, (char)0xC, (char)0xD, (char)0x20 };

        // CheckBadChars - throws on invalid chars to be not found in header name/value
        internal static string CheckBadChars(string name)
        {
            if (name == null || name.Length == 0)
            {
                return name;
            }

            // VALUE check
            // Trim spaces from both ends
            name = name.Trim(HttpTrimCharacters);

            // First, check for correctly formed multi-line value
            // Second, check for absence of CTL characters
            int crlf = 0;
            for (int i = 0; i < name.Length; ++i)
            {
                char c = (char)(0x000000ff & (uint)name[i]);
                switch (crlf)
                {
                    case 0:
                    {
                        if (c == '\r')
                        {
                            crlf = 1;
                        }
                        else if (c == '\n')
                        {
                            // Technically this is bad HTTP.  But it would be a breaking change to throw here.
                            // Is there an exploit?
                            crlf = 2;
                        }
                        else if (c == 127 || (c < ' ' && c != '\t'))
                        {
                            throw new ArgumentException("net_WebHeaderInvalidControlChars");
                        }

                        break;
                    }

                    case 1:
                    {
                        if (c == '\n')
                        {
                            crlf = 2;
                            break;
                        }

                        throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
                    }

                    case 2:
                    {
                        if (c == ' ' || c == '\t')
                        {
                            crlf = 0;
                            break;
                        }

                        throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
                    }
                }
            }

            if (crlf != 0)
            {
                throw new ArgumentException("net_WebHeaderInvalidCRLFChars");
            }

            return name;
        }

        internal static bool ContainsNonAsciiChars(string token)
        {
            for (int i = 0; i < token.Length; ++i)
            {
                if ((token[i] < 0x20) || (token[i] > 0x7e))
                {
                    return true;
                }
            }

            return false;
        }

        private string NormalizeIp(string ip)
        {
            if (!string.IsNullOrWhiteSpace(ip))
            {
                // Handle ipv4 mapped to ipv6
                const string srch = "::ffff:";
                var index = ip.IndexOf(srch, StringComparison.OrdinalIgnoreCase);
                if (index == 0)
                {
                    ip = ip.Substring(srch.Length);
                }
            }

            return ip;
        }

        public bool IsSecureConnection => request.IsHttps || XForwardedProtocol == "https";

        public string[] AcceptTypes => request.Headers.GetCommaSeparatedValues(HeaderNames.Accept);

        private Dictionary<string, object> items;
        public Dictionary<string, object> Items => items ?? (items = new Dictionary<string, object>());

        private string responseContentType;
        public string ResponseContentType
        {
            get =>
                responseContentType
                ?? (responseContentType = GetResponseContentType(HttpRequest));
            set => this.responseContentType = value;
        }

        public const string FormUrlEncoded = "application/x-www-form-urlencoded";
        public const string MultiPartFormData = "multipart/form-data";
        public static string GetResponseContentType(HttpRequest httpReq)
        {
            var specifiedContentType = GetQueryStringContentType(httpReq);
            if (!string.IsNullOrEmpty(specifiedContentType))
            {
                return specifiedContentType;
            }

            const string serverDefaultContentType = "application/json";

            var acceptContentTypes = httpReq.Headers.GetCommaSeparatedValues(HeaderNames.Accept);
            string defaultContentType = null;
            if (HasAnyOfContentTypes(httpReq, FormUrlEncoded, MultiPartFormData))
            {
                defaultContentType = serverDefaultContentType;
            }

            var acceptsAnything = false;
            var hasDefaultContentType = defaultContentType != null;
            if (acceptContentTypes != null)
            {
                foreach (var acceptsType in acceptContentTypes)
                {
                    // TODO: @bond move to Span when Span.Split lands
                    // https://github.com/dotnet/corefx/issues/26528
                    var contentType = acceptsType?.Split(';')[0].Trim();
                    acceptsAnything = contentType.Equals("*/*", StringComparison.OrdinalIgnoreCase);

                    if (acceptsAnything)
                    {
                        break;
                    }
                }

                if (acceptsAnything)
                {
                    if (hasDefaultContentType)
                    {
                        return defaultContentType;
                    }
                    else
                    {
                        return serverDefaultContentType;
                    }
                }
            }

            if (acceptContentTypes == null && httpReq.ContentType == Soap11)
            {
                return Soap11;
            }

            // We could also send a '406 Not Acceptable', but this is allowed also
            return serverDefaultContentType;
        }

        public const string Soap11 = "text/xml; charset=utf-8";

        public static bool HasAnyOfContentTypes(HttpRequest request, params string[] contentTypes)
        {
            if (contentTypes == null || request.ContentType == null)
            {
                return false;
            }

            foreach (var contentType in contentTypes)
            {
                if (IsContentType(request, contentType))
                {
                    return true;
                }
            }

            return false;
        }

        public static bool IsContentType(HttpRequest request, string contentType)
        {
            return request.ContentType.StartsWith(contentType, StringComparison.OrdinalIgnoreCase);
        }

        private static string GetQueryStringContentType(HttpRequest httpReq)
        {
            ReadOnlySpan<char> format = httpReq.Query["format"].ToString().AsSpan();
            if (format == null)
            {
                const int formatMaxLength = 4;
                ReadOnlySpan<char> pi = httpReq.Path.ToString().AsSpan();
                if (pi == null || pi.Length <= formatMaxLength)
                {
                    return null;
                }

                if (pi[0] == '/')
                {
                    pi = pi.Slice(1);
                }

                format = LeftPart(pi, '/');
                if (format.Length > formatMaxLength)
                {
                    return null;
                }
            }

            format = LeftPart(format, '.');
            if (format.Contains("json".AsSpan(), StringComparison.OrdinalIgnoreCase))
            {
                return "application/json";
            }
            else if (format.Contains("xml".AsSpan(), StringComparison.OrdinalIgnoreCase))
            {
                return "application/xml";
            }

            return null;
        }

        public static ReadOnlySpan<char> LeftPart(ReadOnlySpan<char> strVal, char needle)
        {
            if (strVal == null)
            {
                return null;
            }

            var pos = strVal.IndexOf(needle);
            return pos == -1 ? strVal : strVal.Slice(0, pos);
        }

        public static string HandlerFactoryPath;

        private string pathInfo;
        public string PathInfo
        {
            get
            {
                if (this.pathInfo == null)
                {
                    var mode = HandlerFactoryPath;

                    var pos = RawUrl.IndexOf("?", StringComparison.Ordinal);
                    if (pos != -1)
                    {
                        var path = RawUrl.Substring(0, pos);
                        this.pathInfo = GetPathInfo(
                            path,
                            mode,
                            mode ?? string.Empty);
                    }
                    else
                    {
                        this.pathInfo = RawUrl;
                    }

                    this.pathInfo = WebUtility.UrlDecode(pathInfo);
                    this.pathInfo = NormalizePathInfo(pathInfo, mode);
                }

                return this.pathInfo;
            }
        }

        private static string GetPathInfo(string fullPath, string mode, string appPath)
        {
            var pathInfo = ResolvePathInfoFromMappedPath(fullPath, mode);
            if (!string.IsNullOrEmpty(pathInfo))
            {
                return pathInfo;
            }

            // Wildcard mode relies on this to work out the handlerPath
            pathInfo = ResolvePathInfoFromMappedPath(fullPath, appPath);
            if (!string.IsNullOrEmpty(pathInfo))
            {
                return pathInfo;
            }

            return fullPath;
        }

        private static string ResolvePathInfoFromMappedPath(string fullPath, string mappedPathRoot)
        {
            if (mappedPathRoot == null)
            {
                return null;
            }

            var sbPathInfo = new StringBuilder();
            var fullPathParts = fullPath.Split('/');
            var mappedPathRootParts = mappedPathRoot.Split('/');
            var fullPathIndexOffset = mappedPathRootParts.Length - 1;
            var pathRootFound = false;

            for (var fullPathIndex = 0; fullPathIndex < fullPathParts.Length; fullPathIndex++)
            {
                if (pathRootFound)
                {
                    sbPathInfo.Append("/" + fullPathParts[fullPathIndex]);
                }
                else if (fullPathIndex - fullPathIndexOffset >= 0)
                {
                    pathRootFound = true;
                    for (var mappedPathRootIndex = 0; mappedPathRootIndex < mappedPathRootParts.Length; mappedPathRootIndex++)
                    {
                        if (!string.Equals(fullPathParts[fullPathIndex - fullPathIndexOffset + mappedPathRootIndex], mappedPathRootParts[mappedPathRootIndex], StringComparison.OrdinalIgnoreCase))
                        {
                            pathRootFound = false;
                            break;
                        }
                    }
                }
            }

            if (!pathRootFound)
            {
                return null;
            }

            var path = sbPathInfo.ToString();
            return path.Length > 1 ? path.TrimEnd('/') : "/";
        }

        public string UserAgent => request.Headers[HeaderNames.UserAgent];

        public QueryParamCollection Headers => new QueryParamCollection(request.Headers);

        private QueryParamCollection queryString;
        public QueryParamCollection QueryString => queryString ?? (queryString = new QueryParamCollection(request.Query));

        public bool IsLocal => string.Equals(request.HttpContext.Connection.LocalIpAddress.ToString(), request.HttpContext.Connection.RemoteIpAddress.ToString());

        private string httpMethod;
        public string HttpMethod =>
            httpMethod
            ?? (httpMethod = request.Method);

        public string Verb => HttpMethod;

        public string ContentType => request.ContentType;

        private Encoding contentEncoding;
        public Encoding ContentEncoding
        {
            get => contentEncoding ?? Encoding.GetEncoding(request.Headers[HeaderNames.ContentEncoding].ToString());
            set => contentEncoding = value;
        }

        public Uri UrlReferrer => request.GetTypedHeaders().Referer;

        public static Encoding GetEncoding(string contentTypeHeader)
        {
            var param = GetParameter(contentTypeHeader, "charset=");
            if (param == null)
            {
                return null;
            }

            try
            {
                return Encoding.GetEncoding(param);
            }
            catch (ArgumentException)
            {
                return null;
            }
        }

        public Stream InputStream => request.Body;

        public long ContentLength => request.ContentLength ?? 0;

        private IHttpFile[] httpFiles;
        public IHttpFile[] Files
        {
            get
            {
                if (httpFiles == null)
                {
                    if (files == null)
                    {
                        return httpFiles = Array.Empty<IHttpFile>();
                    }

                    httpFiles = new IHttpFile[files.Count];
                    var i = 0;
                    foreach (var pair in files)
                    {
                        var reqFile = pair.Value;
                        httpFiles[i] = new HttpFile
                        {
                            ContentType = reqFile.ContentType,
                            ContentLength = reqFile.ContentLength,
                            FileName = reqFile.FileName,
                            InputStream = reqFile.InputStream,
                        };
                        i++;
                    }
                }

                return httpFiles;
            }
        }

        public static string NormalizePathInfo(string pathInfo, string handlerPath)
        {
            if (handlerPath != null)
            {
                var trimmed = pathInfo.TrimStart('/');
                if (trimmed.StartsWith(handlerPath, StringComparison.OrdinalIgnoreCase))
                {
                    return trimmed.Substring(handlerPath.Length);
                }
            }

            return pathInfo;
        }
    }
}