-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathHttpClient.cs
More file actions
278 lines (230 loc) · 8.46 KB
/
HttpClient.cs
File metadata and controls
278 lines (230 loc) · 8.46 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
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
/*
* 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.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, 8192);
Logger.InfoFormat("Got Client {0}", _remoteEndPoint);
Task.Factory.StartNew(Process);
UpdateLastOperationTime();
}
private async void Process()
{
try
{
while (_client.Connected)
{
// TODO : Configuration.
var limitedStream = new NotFlushingStream(new LimitedStream(_stream, readLimit: 1024*1024, writeLimit: 1024*1024));
var streamReader = new StreamReader(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) { AutoFlush = false };
await WriteResponse(context, streamWriter).ConfigureAwait(false);
await limitedStream.ExplicitFlushAsync().ConfigureAwait(false);
if (!request.Headers.KeepAliveConnection() || context.Response.CloseConnection)
{
_client.Close();
}
}
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.WriteLineAsync(string.Format("HTTP/1.1 {0} {1}",
(int)response.ResponseCode,
response.ResponseCode))
.ConfigureAwait(false);
foreach (var header in response.Headers)
{
await writer.WriteLineAsync(string.Format("{0}: {1}", header.Key, header.Value)).ConfigureAwait(false);
}
// Cookies
if (context.Cookies.Touched)
{
await writer.WriteAsync(context.Cookies.ToCookieData())
.ConfigureAwait(false);
}
// Empty Line
await writer.WriteLineAsync().ConfigureAwait(false);
// Body
await response.WriteBody(writer).ConfigureAwait(false);
await writer.FlushAsync().ConfigureAwait(false);
}
public IClient Client
{
get { return _client; }
}
public void ForceClose()
{
_client.Close();
}
public DateTime LastOperationTime
{
get
{
return _lastOperationTime;
}
}
private void UpdateLastOperationTime()
{
// _lastOperationTime = DateTime.Now;
}
}
internal class NotFlushingStream : Stream
{
private readonly Stream _child;
public NotFlushingStream(Stream child)
{
_child = child;
}
public void ExplicitFlush()
{
_child.Flush();
}
public Task ExplicitFlushAsync()
{
return _child.FlushAsync();
}
public override void Flush()
{
// _child.Flush();
}
public override long Seek(long offset, SeekOrigin origin)
{
return _child.Seek(offset, origin);
}
public override void SetLength(long value)
{
_child.SetLength(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
return _child.Read(buffer, offset, count);
}
public override int ReadByte()
{
return _child.ReadByte();
}
public override void Write(byte[] buffer, int offset, int count)
{
_child.Write(buffer, offset, count);
}
public override void WriteByte(byte value)
{
_child.WriteByte(value);
}
public override bool CanRead
{
get { return _child.CanRead; }
}
public override bool CanSeek
{
get { return _child.CanSeek; }
}
public override bool CanWrite
{
get { return _child.CanWrite; }
}
public override long Length
{
get { return _child.Length; }
}
public override long Position
{
get { return _child.Position; }
set { _child.Position = value; }
}
public override int ReadTimeout
{
get { return _child.ReadTimeout; }
set { _child.ReadTimeout = value; }
}
public override int WriteTimeout
{
get { return _child.WriteTimeout; }
set { _child.WriteTimeout = value; }
}
}
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));
}
}
}