forked from bonesoul/uhttpsharp
-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathHttpClient.cs
More file actions
197 lines (156 loc) · 6.48 KB
/
HttpClient.cs
File metadata and controls
197 lines (156 loc) · 6.48 KB
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
/*
* Copyright (C) 2011 uhttpsharp project - http://github.com/raistlinthewiz/uhttpsharp
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System.Globalization;
using System.Text;
using log4net;
using System.Net;
using System.Reflection;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using uhttpsharp.Clients;
using uhttpsharp.Headers;
using uhttpsharp.RequestProviders;
namespace uhttpsharp
{
internal sealed class HttpClientHandler
{
private const string CrLf = "\r\n";
private static readonly byte[] CrLfBuffer = Encoding.UTF8.GetBytes(CrLf);
private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly IClient _client;
private readonly Func<IHttpContext, Task> _requestHandler;
private readonly IHttpRequestProvider _requestProvider;
private readonly EndPoint _remoteEndPoint;
private DateTime _lastOperationTime;
private readonly Stream _stream;
public HttpClientHandler(IClient client, Func<IHttpContext, Task> requestHandler, IHttpRequestProvider requestProvider)
{
_remoteEndPoint = client.RemoteEndPoint;
_client = client;
_requestHandler = requestHandler;
_requestProvider = requestProvider;
_stream = new BufferedStream(_client.Stream);
Logger.InfoFormat("Got Client {0}", _remoteEndPoint);
Task.Factory.StartNew(Process);
UpdateLastOperationTime();
}
private async void Process()
{
try
{
while (_client.Connected)
{
// TODO : Configuration.
var limitedStream = new LimitedStream(_stream, readLimit: 1024*1024, writeLimit: 1024*1024);
IStreamReader streamReader = new MyStreamReader(limitedStream);
var request = await _requestProvider.Provide(streamReader).ConfigureAwait(false);
if (request != null)
{
UpdateLastOperationTime();
var context = new HttpContext(request, _client.RemoteEndPoint);
Logger.InfoFormat("{1} : Got request {0}", request.Uri, _client.RemoteEndPoint);
await _requestHandler(context).ConfigureAwait(false);
if (context.Response != null)
{
var streamWriter = new StreamWriter(limitedStream);
await WriteResponse(context, streamWriter);
}
UpdateLastOperationTime();
}
else
{
_client.Close();
}
}
}
catch (Exception e)
{
// Hate people who make bad calls.
Logger.Warn(string.Format("Error while serving : {0}", _remoteEndPoint), e);
_client.Close();
}
Logger.InfoFormat("Lost Client {0}", _remoteEndPoint);
}
private async Task WriteResponse(HttpContext context, StreamWriter writer)
{
IHttpResponse response = context.Response;
IHttpRequest request = context.Request;
// Headers
await writer.WriteAsync("HTTP/1.1 ").ConfigureAwait(false);
await writer.WriteAsync(((int)response.ResponseCode).ToString(CultureInfo.InvariantCulture)).ConfigureAwait(false);
await writer.WriteAsync(' ').ConfigureAwait(false);
await writer.WriteLineAsync(response.ResponseCode.ToString()).ConfigureAwait(false);
//await writer.WriteLineAsync("HTTP/1.1 " + (int)response.ResponseCode + " " + response.ResponseCode);
foreach (var header in response.Headers)
{
await writer.WriteLineAsync(header.Key + ": " + header.Value);
}
// Cookies
if (context.Cookies.Touched)
{
await writer.WriteAsync(context.Cookies.ToCookieData())
.ConfigureAwait(false);
}
await writer.FlushAsync().ConfigureAwait(false);
// Empty Line
await writer.BaseStream.WriteAsync(CrLfBuffer, 0, CrLfBuffer.Length).ConfigureAwait(false);
// Body
await response.WriteBody(writer).ConfigureAwait(false);
if (!request.Headers.KeepAliveConnection() || response.CloseConnection)
{
_client.Close();
}
}
public IClient Client
{
get { return _client; }
}
public void ForceClose()
{
_client.Close();
}
public DateTime LastOperationTime
{
get
{
return _lastOperationTime;
}
}
private void UpdateLastOperationTime()
{
// _lastOperationTime = DateTime.Now;
}
}
public static class RequestHandlersAggregateExtensions
{
public static Func<IHttpContext, Task> Aggregate(this IList<IHttpRequestHandler> handlers)
{
return handlers.Aggregate(0);
}
private static Func<IHttpContext, Task> Aggregate(this IList<IHttpRequestHandler> handlers, int index)
{
if (index == handlers.Count)
{
return null;
}
var currentHandler = handlers[index];
var nextHandler = handlers.Aggregate(index + 1);
return context => currentHandler.Handle(context, () => nextHandler(context));
}
}
}