This repository has been archived by the owner on May 28, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RequestParser.cs
69 lines (60 loc) · 2.44 KB
/
RequestParser.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
using System.Text;
using System.Text.RegularExpressions;
namespace Fleck
{
public class RequestParser
{
const string pattern = @"^(?<method>[^\s]+)\s(?<path>[^\s]+)\sHTTP\/1\.1\r\n" + // request line
@"((?<field_name>[^:\r\n]+):(?([^\r\n])\s)*(?<field_value>[^\r\n]*)\r\n)+" + //headers
@"\r\n" + //newline
@"(?<body>.+)?";
const string FlashSocketPolicyRequestPattern = @"^[<]policy-file-request\s*[/][>]";
private static readonly Regex _regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
private static readonly Regex _FlashSocketPolicyRequestRegex = new Regex(FlashSocketPolicyRequestPattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
public static WebSocketHttpRequest Parse(byte[] bytes)
{
return Parse(bytes, "ws");
}
public static WebSocketHttpRequest Parse(byte[] bytes, string scheme)
{
// Check for websocket request header
var body = Encoding.UTF8.GetString(bytes);
Match match = _regex.Match(body);
if (!match.Success)
{
// No websocket request header found, check for a flash socket policy request
match = _FlashSocketPolicyRequestRegex.Match(body);
if (match.Success)
{
// It's a flash socket policy request, so return
return new WebSocketHttpRequest
{
Body = body,
Bytes = bytes
};
}
else
{
return null;
}
}
var request = new WebSocketHttpRequest
{
Method = match.Groups["method"].Value,
Path = match.Groups["path"].Value,
Body = match.Groups["body"].Value,
Bytes = bytes,
Scheme = scheme
};
var fields = match.Groups["field_name"].Captures;
var values = match.Groups["field_value"].Captures;
for (var i = 0; i < fields.Count; i++)
{
var name = fields[i].ToString();
var value = values[i].ToString();
request.Headers[name] = value;
}
return request;
}
}
}