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
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using MediaBrowser.Model.Services;
using SocketHttpListener.Net.WebSockets;
namespace SocketHttpListener.Net
{
public sealed partial class HttpListenerRequest
{
private CookieCollection _cookies;
private bool? _keepAlive;
private string _rawUrl;
private Uri _requestUri;
private Version _version;
public string[] AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]);
public string[] UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]);
private static CookieCollection ParseCookies(Uri uri, string setCookieHeader)
{
var cookies = new CookieCollection();
return cookies;
}
public CookieCollection Cookies
{
get
{
if (_cookies == null)
{
string cookieString = Headers[HttpKnownHeaderNames.Cookie];
if (!string.IsNullOrEmpty(cookieString))
{
_cookies = ParseCookies(RequestUri, cookieString);
}
if (_cookies == null)
{
_cookies = new CookieCollection();
}
}
return _cookies;
}
}
public Encoding ContentEncoding
{
get
{
if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP"))
{
string postDataCharset = Headers["x-up-devcap-post-charset"];
if (postDataCharset != null && postDataCharset.Length > 0)
{
try
{
return Encoding.GetEncoding(postDataCharset);
}
catch (ArgumentException)
{
}
}
}
if (HasEntityBody)
{
if (ContentType != null)
{
string charSet = Helpers.GetCharSetValueFromHeader(ContentType);
if (charSet != null)
{
try
{
return Encoding.GetEncoding(charSet);
}
catch (ArgumentException)
{
}
}
}
}
return Encoding.UTF8;
}
}
public string ContentType => Headers[HttpKnownHeaderNames.ContentType];
public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address);
public bool IsWebSocketRequest
{
get
{
if (!SupportsWebSockets)
{
return false;
}
bool foundConnectionUpgradeHeader = false;
if (string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Connection]) || string.IsNullOrEmpty(Headers[HttpKnownHeaderNames.Upgrade]))
{
return false;
}
foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection))
{
if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase))
{
foundConnectionUpgradeHeader = true;
break;
}
}
if (!foundConnectionUpgradeHeader)
{
return false;
}
foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade))
{
if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
}
public bool KeepAlive
{
get
{
if (!_keepAlive.HasValue)
{
string header = Headers[HttpKnownHeaderNames.ProxyConnection];
if (string.IsNullOrEmpty(header))
{
header = Headers[HttpKnownHeaderNames.Connection];
}
if (string.IsNullOrEmpty(header))
{
if (ProtocolVersion >= HttpVersion.Version11)
{
_keepAlive = true;
}
else
{
header = Headers[HttpKnownHeaderNames.KeepAlive];
_keepAlive = !string.IsNullOrEmpty(header);
}
}
else
{
header = header.ToLower(CultureInfo.InvariantCulture);
_keepAlive =
header.IndexOf("close", StringComparison.OrdinalIgnoreCase) < 0 ||
header.IndexOf("keep-alive", StringComparison.OrdinalIgnoreCase) >= 0;
}
}
return _keepAlive.Value;
}
}
public QueryParamCollection QueryString
{
get
{
var queryString = new QueryParamCollection();
Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding);
return queryString;
}
}
public string RawUrl => _rawUrl;
private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http;
public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent];
public string UserHostAddress => LocalEndPoint.ToString();
public string UserHostName => Headers[HttpKnownHeaderNames.Host];
public Uri UrlReferrer
{
get
{
string referrer = Headers[HttpKnownHeaderNames.Referer];
if (referrer == null)
{
return null;
}
bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out var urlReferrer);
return success ? urlReferrer : null;
}
}
public Uri Url => RequestUri;
public Version ProtocolVersion => _version;
private static class Helpers
{
//
// Get attribute off header value
//
internal static string GetCharSetValueFromHeader(string headerValue)
{
const string AttrName = "charset";
if (headerValue == null)
return null;
int l = headerValue.Length;
int k = AttrName.Length;
// find properly separated attribute name
int i = 1; // start searching from 1
while (i < l)
{
i = CultureInfo.InvariantCulture.CompareInfo.IndexOf(headerValue, AttrName, i, CompareOptions.IgnoreCase);
if (i < 0)
break;
if (i + k >= l)
break;
char chPrev = headerValue[i - 1];
char chNext = headerValue[i + k];
if ((chPrev == ';' || chPrev == ',' || char.IsWhiteSpace(chPrev)) && (chNext == '=' || char.IsWhiteSpace(chNext)))
break;
i += k;
}
if (i < 0 || i >= l)
return null;
// skip to '=' and the following whitespace
i += k;
while (i < l && char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l || headerValue[i] != '=')
return null;
i++;
while (i < l && char.IsWhiteSpace(headerValue[i]))
i++;
if (i >= l)
return null;
// parse the value
string attrValue = null;
int j;
if (i < l && headerValue[i] == '"')
{
if (i == l - 1)
return null;
j = headerValue.IndexOf('"', i + 1);
if (j < 0 || j == i + 1)
return null;
attrValue = headerValue.Substring(i + 1, j - i - 1).Trim();
}
else
{
for (j = i; j < l; j++)
{
if (headerValue[j] == ';')
break;
}
if (j == i)
return null;
attrValue = headerValue.Substring(i, j - i).Trim();
}
return attrValue;
}
internal static string[] ParseMultivalueHeader(string s)
{
if (s == null)
return null;
int l = s.Length;
// collect comma-separated values into list
var values = new List<string>();
int i = 0;
while (i < l)
{
// find next ,
int ci = s.IndexOf(',', i);
if (ci < 0)
ci = l;
// append corresponding server value
values.Add(s.Substring(i, ci - i));
// move to next
i = ci + 1;
// skip leading space
if (i < l && s[i] == ' ')
i++;
}
// return list as array of strings
int n = values.Count;
string[] strings;
// if n is 0 that means s was empty string
if (n == 0)
{
strings = new string[1];
strings[0] = string.Empty;
}
else
{
strings = new string[n];
values.CopyTo(0, strings, 0, n);
}
return strings;
}
private static string UrlDecodeStringFromStringInternal(string s, Encoding e)
{
int count = s.Length;
var helper = new UrlDecoder(count, e);
// go through the string's chars collapsing %XX and %uXXXX and
// appending each char as char, with exception of %XX constructs
// that are appended as bytes
for (int pos = 0; pos < count; pos++)
{
char ch = s[pos];
if (ch == '+')
{
ch = ' ';
}
else if (ch == '%' && pos < count - 2)
{
if (s[pos + 1] == 'u' && pos < count - 5)
{
int h1 = HexToInt(s[pos + 2]);
int h2 = HexToInt(s[pos + 3]);
int h3 = HexToInt(s[pos + 4]);
int h4 = HexToInt(s[pos + 5]);
if (h1 >= 0 && h2 >= 0 && h3 >= 0 && h4 >= 0)
{ // valid 4 hex chars
ch = (char)((h1 << 12) | (h2 << 8) | (h3 << 4) | h4);
pos += 5;
// only add as char
helper.AddChar(ch);
continue;
}
}
else
{
int h1 = HexToInt(s[pos + 1]);
int h2 = HexToInt(s[pos + 2]);
if (h1 >= 0 && h2 >= 0)
{ // valid 2 hex chars
byte b = (byte)((h1 << 4) | h2);
pos += 2;
// don't add as char
helper.AddByte(b);
continue;
}
}
}
if ((ch & 0xFF80) == 0)
helper.AddByte((byte)ch); // 7 bit have to go as bytes because of Unicode
else
helper.AddChar(ch);
}
return helper.GetString();
}
private static int HexToInt(char h)
{
return (h >= '0' && h <= '9') ? h - '0' :
(h >= 'a' && h <= 'f') ? h - 'a' + 10 :
(h >= 'A' && h <= 'F') ? h - 'A' + 10 :
-1;
}
private class UrlDecoder
{
private int _bufferSize;
// Accumulate characters in a special array
private int _numChars;
private char[] _charBuffer;
// Accumulate bytes for decoding into characters in a special array
private int _numBytes;
private byte[] _byteBuffer;
// Encoding to convert chars to bytes
private Encoding _encoding;
private void FlushBytes()
{
if (_numBytes > 0)
{
_numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars);
_numBytes = 0;
}
}
internal UrlDecoder(int bufferSize, Encoding encoding)
{
_bufferSize = bufferSize;
_encoding = encoding;
_charBuffer = new char[bufferSize];
// byte buffer created on demand
}
internal void AddChar(char ch)
{
if (_numBytes > 0)
FlushBytes();
_charBuffer[_numChars++] = ch;
}
internal void AddByte(byte b)
{
{
if (_byteBuffer == null)
_byteBuffer = new byte[_bufferSize];
_byteBuffer[_numBytes++] = b;
}
}
internal string GetString()
{
if (_numBytes > 0)
FlushBytes();
if (_numChars > 0)
return new string(_charBuffer, 0, _numChars);
else
return string.Empty;
}
}
internal static void FillFromString(QueryParamCollection nvc, string s, bool urlencoded, Encoding encoding)
{
int l = (s != null) ? s.Length : 0;
int i = (s.Length > 0 && s[0] == '?') ? 1 : 0;
while (i < l)
{
// find next & while noting first = on the way (and if there are more)
int si = i;
int ti = -1;
while (i < l)
{
char ch = s[i];
if (ch == '=')
{
if (ti < 0)
ti = i;
}
else if (ch == '&')
{
break;
}
i++;
}
// extract the name / value pair
string name = null;
string value = null;
if (ti >= 0)
{
name = s.Substring(si, ti - si);
value = s.Substring(ti + 1, i - ti - 1);
}
else
{
value = s.Substring(si, i - si);
}
// add name / value pair to the collection
if (urlencoded)
nvc.Add(
name == null ? null : UrlDecodeStringFromStringInternal(name, encoding),
UrlDecodeStringFromStringInternal(value, encoding));
else
nvc.Add(name, value);
// trailing '&'
if (i == l - 1 && s[i] == '&')
nvc.Add(null, "");
i++;
}
}
}
}
}
|