aboutsummaryrefslogtreecommitdiff
path: root/Jellyfin.Server/SocketSharp/RequestMono.cs
blob: 8396ad600dad2372418e1e500b0a683d4bd7deeb (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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using MediaBrowser.Model.Services;

namespace Jellyfin.Server.SocketSharp
{
    public partial class WebSocketSharpRequest : IHttpRequest
    {
        internal static string GetParameter(ReadOnlySpan<char> header, string attr)
        {
            int ap = header.IndexOf(attr, StringComparison.Ordinal);
            if (ap == -1)
            {
                return null;
            }

            ap += attr.Length;
            if (ap >= header.Length)
            {
                return null;
            }

            char ending = header[ap];
            if (ending != '"')
            {
                ending = ' ';
            }

            var slice = header.Slice(ap + 1);
            int end = slice.IndexOf(ending);
            if (end == -1)
            {
                return ending == '"' ? null : header.Slice(ap).ToString();
            }

            return slice.Slice(0, end - ap - 1).ToString();
        }

        private async Task LoadMultiPart(WebROCollection form)
        {
            string boundary = GetParameter(ContentType, "; boundary=");
            if (boundary == null)
            {
                return;
            }

            using (var requestStream = InputStream)
            {
                // DB: 30/01/11 - Hack to get around non-seekable stream and received HTTP request
                // Not ending with \r\n?
                var ms = new MemoryStream(32 * 1024);
                await requestStream.CopyToAsync(ms).ConfigureAwait(false);

                var input = ms;
                ms.WriteByte((byte)'\r');
                ms.WriteByte((byte)'\n');

                input.Position = 0;

                // Uncomment to debug
                // var content = new StreamReader(ms).ReadToEnd();
                // Console.WriteLine(boundary + "::" + content);
                // input.Position = 0;

                var multi_part = new HttpMultipart(input, boundary, ContentEncoding);

                HttpMultipart.Element e;
                while ((e = multi_part.ReadNextElement()) != null)
                {
                    if (e.Filename == null)
                    {
                        byte[] copy = new byte[e.Length];

                        input.Position = e.Start;
                        input.Read(copy, 0, (int)e.Length);

                        form.Add(e.Name, (e.Encoding ?? ContentEncoding).GetString(copy, 0, copy.Length));
                    }
                    else
                    {
                        // We use a substream, as in 2.x we will support large uploads streamed to disk,
                        var sub = new HttpPostedFile(e.Filename, e.ContentType, input, e.Start, e.Length);
                        files[e.Name] = sub;
                    }
                }
            }
        }

        public async Task<QueryParamCollection> GetFormData()
        {
            var form = new WebROCollection();
            files = new Dictionary<string, HttpPostedFile>();

            if (IsContentType("multipart/form-data", true))
            {
                await LoadMultiPart(form).ConfigureAwait(false);
            }
            else if (IsContentType("application/x-www-form-urlencoded", true))
            {
                await LoadWwwForm(form).ConfigureAwait(false);
            }

#if NET_4_0
            if (validateRequestNewMode && !checked_form) {
                // Setting this before calling the validator prevents
                // possible endless recursion
                checked_form = true;
                ValidateNameValueCollection("Form", query_string_nvc, RequestValidationSource.Form);
            } else
#endif
            if (validate_form && !checked_form)
            {
                checked_form = true;
                ValidateNameValueCollection("Form", form);
            }

            return form;
        }

        public string Accept => string.IsNullOrEmpty(request.Headers["Accept"]) ? null : request.Headers["Accept"];

        public string Authorization => string.IsNullOrEmpty(request.Headers["Authorization"]) ? null : request.Headers["Authorization"];

        protected bool validate_cookies { get; set; }
        protected bool validate_query_string { get; set; }
        protected bool validate_form { get; set; }
        protected bool checked_cookies { get; set; }
        protected bool checked_query_string { get; set; }
        protected bool checked_form { get; set; }

        private static void ThrowValidationException(string name, string key, string value)
        {
            string v = "\"" + value + "\"";
            if (v.Length > 20)
            {
                v = v.Substring(0, 16) + "...\"";
            }

            string msg = string.Format(
                CultureInfo.InvariantCulture,
                "A potentially dangerous Request.{0} value was detected from the client ({1}={2}).",
                name,
                key,
                v);

            throw new Exception(msg);
        }

        private static void ValidateNameValueCollection(string name, QueryParamCollection coll)
        {
            if (coll == null)
            {
                return;
            }

            foreach (var pair in coll)
            {
                var key = pair.Name;
                var val = pair.Value;
                if (val != null && val.Length > 0 && IsInvalidString(val))
                {
                    ThrowValidationException(name, key, val);
                }
            }
        }

        internal static bool IsInvalidString(string val)
            => IsInvalidString(val, out var validationFailureIndex);

        internal static bool IsInvalidString(string val, out int validationFailureIndex)
        {
            validationFailureIndex = 0;

            int len = val.Length;
            if (len < 2)
            {
                return false;
            }

            char current = val[0];
            for (int idx = 1; idx < len; idx++)
            {
                char next = val[idx];

                // See http://secunia.com/advisories/14325
                if (current == '<' || current == '\xff1c')
                {
                    if (next == '!' || next < ' '
                        || (next >= 'a' && next <= 'z')
                        || (next >= 'A' && next <= 'Z'))
                    {
                        validationFailureIndex = idx - 1;
                        return true;
                    }
                }
                else if (current == '&' && next == '#')
                {
                    validationFailureIndex = idx - 1;
                    return true;
                }

                current = next;
            }

            return false;
        }

        public void ValidateInput()
        {
            validate_cookies = true;
            validate_query_string = true;
            validate_form = true;
        }

        private bool IsContentType(string ct, bool starts_with)
        {
            if (ct == null || ContentType == null)
            {
                return false;
            }

            if (starts_with)
            {
                return ContentType.StartsWith(ct, StringComparison.OrdinalIgnoreCase);
            }

            return string.Equals(ContentType, ct, StringComparison.OrdinalIgnoreCase);
        }

        private async Task LoadWwwForm(WebROCollection form)
        {
            using (var input = InputStream)
            {
                using (var ms = new MemoryStream())
                {
                    await input.CopyToAsync(ms).ConfigureAwait(false);
                    ms.Position = 0;

                    using (var s = new StreamReader(ms, ContentEncoding))
                    {
                        var key = new StringBuilder();
                        var value = new StringBuilder();
                        int c;

                        while ((c = s.Read()) != -1)
                        {
                            if (c == '=')
                            {
                                value.Length = 0;
                                while ((c = s.Read()) != -1)
                                {
                                    if (c == '&')
                                    {
                                        AddRawKeyValue(form, key, value);
                                        break;
                                    }
                                    else
                                    {
                                        value.Append((char)c);
                                    }
                                }

                                if (c == -1)
                                {
                                    AddRawKeyValue(form, key, value);
                                    return;
                                }
                            }
                            else if (c == '&')
                            {
                                AddRawKeyValue(form, key, value);
                            }
                            else
                            {
                                key.Append((char)c);
                            }
                        }

                        if (c == -1)
                        {
                            AddRawKeyValue(form, key, value);
                        }
                    }
                }
            }
        }

        private static void AddRawKeyValue(WebROCollection form, StringBuilder key, StringBuilder value)
        {
            form.Add(WebUtility.UrlDecode(key.ToString()), WebUtility.UrlDecode(value.ToString()));

            key.Length = 0;
            value.Length = 0;
        }

        private Dictionary<string, HttpPostedFile> files;

        private class WebROCollection : QueryParamCollection
        {
            public override string ToString()
            {
                var result = new StringBuilder();
                foreach (var pair in this)
                {
                    if (result.Length > 0)
                    {
                        result.Append('&');
                    }

                    var key = pair.Name;
                    if (key != null && key.Length > 0)
                    {
                        result.Append(key);
                        result.Append('=');
                    }

                    result.Append(pair.Value);
                }

                return result.ToString();
            }
        }
        private class HttpMultipart
        {

            public class Element
            {
                public string ContentType { get; set; }

                public string Name { get; set; }

                public string Filename { get; set; }

                public Encoding Encoding { get; set; }

                public long Start { get; set; }

                public long Length { get; set; }

                public override string ToString()
                {
                    return "ContentType " + ContentType + ", Name " + Name + ", Filename " + Filename + ", Start " +
                        Start.ToString(CultureInfo.CurrentCulture) + ", Length " + Length.ToString(CultureInfo.CurrentCulture);
                }
            }

            private const byte LF = (byte)'\n';

            private const byte CR = (byte)'\r';

            private Stream data;

            private string boundary;

            private byte[] boundaryBytes;

            private byte[] buffer;

            private bool atEof;

            private Encoding encoding;

            private StringBuilder sb;

            // See RFC 2046
            // In the case of multipart entities, in which one or more different
            // sets of data are combined in a single body, a "multipart" media type
            // field must appear in the entity's header.  The body must then contain
            // one or more body parts, each preceded by a boundary delimiter line,
            // and the last one followed by a closing boundary delimiter line.
            // After its boundary delimiter line, each body part then consists of a
            // header area, a blank line, and a body area.  Thus a body part is
            // similar to an RFC 822 message in syntax, but different in meaning.

            public HttpMultipart(Stream data, string b, Encoding encoding)
            {
                this.data = data;
                boundary = b;
                boundaryBytes = encoding.GetBytes(b);
                buffer = new byte[boundaryBytes.Length + 2]; // CRLF or '--'
                this.encoding = encoding;
                sb = new StringBuilder();
            }

            public Element ReadNextElement()
            {
                if (atEof || ReadBoundary())
                {
                    return null;
                }

                var elem = new Element();
                ReadOnlySpan<char> header;
                while ((header = ReadHeaders()) != null)
                {
                    if (header.StartsWith("Content-Disposition:", StringComparison.OrdinalIgnoreCase))
                    {
                        elem.Name = GetContentDispositionAttribute(header, "name");
                        elem.Filename = StripPath(GetContentDispositionAttributeWithEncoding(header, "filename"));
                    }
                    else if (header.StartsWith("Content-Type:", StringComparison.OrdinalIgnoreCase))
                    {
                        elem.ContentType = header.Slice("Content-Type:".Length).Trim().ToString();
                        elem.Encoding = GetEncoding(elem.ContentType);
                    }
                }

                long start = data.Position;
                elem.Start = start;
                long pos = MoveToNextBoundary();
                if (pos == -1)
                {
                    return null;
                }

                elem.Length = pos - start;
                return elem;
            }

            private string ReadLine()
            {
                // CRLF or LF are ok as line endings.
                bool got_cr = false;
                int b = 0;
                sb.Length = 0;
                while (true)
                {
                    b = data.ReadByte();
                    if (b == -1)
                    {
                        return null;
                    }

                    if (b == LF)
                    {
                        break;
                    }

                    got_cr = b == CR;
                    sb.Append((char)b);
                }

                if (got_cr)
                {
                    sb.Length--;
                }

                return sb.ToString();
            }

            private static string GetContentDispositionAttribute(ReadOnlySpan<char> l, string name)
            {
                int idx = l.IndexOf(name + "=\"", StringComparison.Ordinal);
                if (idx < 0)
                {
                    return null;
                }

                int begin = idx + name.Length + "=\"".Length;
                int end = l.Slice(begin).IndexOf('"');
                if (end < 0)
                {
                    return null;
                }

                if (begin == end)
                {
                    return string.Empty;
                }

                return l.Slice(begin, end - begin).ToString();
            }

            private string GetContentDispositionAttributeWithEncoding(ReadOnlySpan<char> l, string name)
            {
                int idx = l.IndexOf(name + "=\"", StringComparison.Ordinal);
                if (idx < 0)
                {
                    return null;
                }

                int begin = idx + name.Length + "=\"".Length;
                int end = l.Slice(begin).IndexOf('"');
                if (end < 0)
                {
                    return null;
                }

                if (begin == end)
                {
                    return string.Empty;
                }

                ReadOnlySpan<char> temp = l.Slice(begin, end - begin);
                byte[] source = new byte[temp.Length];
                for (int i = temp.Length - 1; i >= 0; i--)
                {
                    source[i] = (byte)temp[i];
                }

                return encoding.GetString(source, 0, source.Length);
            }

            private bool ReadBoundary()
            {
                try
                {
                    string line;
                    do
                    {
                        line = ReadLine();
                    }
                    while (line.Length == 0);

                    if (line[0] != '-' || line[1] != '-')
                    {
                        return false;
                    }

                    if (!line.EndsWith(boundary, StringComparison.Ordinal))
                    {
                        return true;
                    }
                }
                catch
                {

                }

                return false;
            }

            private string ReadHeaders()
            {
                string s = ReadLine();
                if (s.Length == 0)
                {
                    return null;
                }

                return s;
            }

            private static bool CompareBytes(byte[] orig, byte[] other)
            {
                for (int i = orig.Length - 1; i >= 0; i--)
                {
                    if (orig[i] != other[i])
                    {
                        return false;
                    }
                }

                return true;
            }

            private long MoveToNextBoundary()
            {
                long retval = 0;
                bool got_cr = false;

                int state = 0;
                int c = data.ReadByte();
                while (true)
                {
                    if (c == -1)
                    {
                        return -1;
                    }

                    if (state == 0 && c == LF)
                    {
                        retval = data.Position - 1;
                        if (got_cr)
                        {
                            retval--;
                        }

                        state = 1;
                        c = data.ReadByte();
                    }
                    else if (state == 0)
                    {
                        got_cr = c == CR;
                        c = data.ReadByte();
                    }
                    else if (state == 1 && c == '-')
                    {
                        c = data.ReadByte();
                        if (c == -1)
                        {
                            return -1;
                        }

                        if (c != '-')
                        {
                            state = 0;
                            got_cr = false;
                            continue; // no ReadByte() here
                        }

                        int nread = data.Read(buffer, 0, buffer.Length);
                        int bl = buffer.Length;
                        if (nread != bl)
                        {
                            return -1;
                        }

                        if (!CompareBytes(boundaryBytes, buffer))
                        {
                            state = 0;
                            data.Position = retval + 2;
                            if (got_cr)
                            {
                                data.Position++;
                                got_cr = false;
                            }

                            c = data.ReadByte();
                            continue;
                        }

                        if (buffer[bl - 2] == '-' && buffer[bl - 1] == '-')
                        {
                            atEof = true;
                        }
                        else if (buffer[bl - 2] != CR || buffer[bl - 1] != LF)
                        {
                            state = 0;
                            data.Position = retval + 2;
                            if (got_cr)
                            {
                                data.Position++;
                                got_cr = false;
                            }

                            c = data.ReadByte();
                            continue;
                        }

                        data.Position = retval + 2;
                        if (got_cr)
                        {
                            data.Position++;
                        }

                        break;
                    }
                    else
                    {
                        // state == 1
                        state = 0; // no ReadByte() here
                    }
                }

                return retval;
            }

            private static string StripPath(string path)
            {
                if (path == null || path.Length == 0)
                {
                    return path;
                }

                if (path.IndexOf(":\\", StringComparison.Ordinal) != 1
                    && !path.StartsWith("\\\\", StringComparison.Ordinal))
                {
                    return path;
                }

                return path.Substring(path.LastIndexOf('\\') + 1);
            }
        }
    }
}