-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathHttpReverseProxyResource.cs
More file actions
578 lines (500 loc) · 18.7 KB
/
HttpReverseProxyResource.cs
File metadata and controls
578 lines (500 loc) · 18.7 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
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
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Waher.Content;
using Waher.Content.Getters;
using Waher.Events;
using Waher.Runtime.IO;
using Waher.Script;
using Waher.Security;
namespace Waher.Networking.HTTP
{
/// <summary>
/// An HTTP Reverse proxy resource. Incoming requests are reverted to a another web server for processing. Responses
/// are returned asynchronously as they are received.
/// </summary>
public class HttpReverseProxyResource : HttpAsynchronousResource, IHttpGetMethod, IHttpGetRangesMethod,
IHttpPostMethod, IHttpPostRangesMethod, IHttpPutMethod, IHttpPutRangesMethod, IHttpOptionsMethod,
IHttpDeleteMethod, IHttpPatchMethod, IHttpPatchRangesMethod, IHttpTraceMethod
{
private readonly TimeSpan timeout;
private readonly string baseUri;
private readonly bool useSession;
private readonly bool encryption;
/// <summary>
/// An HTTP Reverse proxy resource. Incoming requests are reverted to a another web server for processing. Responses
/// are returned asynchronously as they are received.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="RemoteHost">Host of remote web server.</param>
/// <param name="Port">Port number of remote web server.</param>
/// <param name="RemoteFolder">Optional remote folder where remote content is hosted.</param>
/// <param name="Encryption">If encryption (https) should be used.</param>
/// <param name="Timeout">Timeout threshold.</param>
public HttpReverseProxyResource(string ResourceName, string RemoteHost, int Port,
string RemoteFolder, bool Encryption, TimeSpan Timeout)
: this(ResourceName, RemoteHost, Port, RemoteFolder, Encryption, Timeout, false)
{
}
/// <summary>
/// An HTTP Reverse proxy resource. Incoming requests are reverted to a another web server for processing. Responses
/// are returned asynchronously as they are received.
/// </summary>
/// <param name="ResourceName">Name of resource.</param>
/// <param name="RemoteHost">Host of remote web server.</param>
/// <param name="Port">Port number of remote web server.</param>
/// <param name="RemoteFolder">Optional remote folder where remote content is hosted.</param>
/// <param name="Encryption">If encryption (https) should be used.</param>
/// <param name="Timeout">Timeout threshold.</param>
/// <param name="UseProxySession">If the proxy resource should add a session requirement
/// as well. This allows the proxy resource to forward user infomration to underlying
/// services, etc. (Default=false)</param>
public HttpReverseProxyResource(string ResourceName, string RemoteHost, int Port,
string RemoteFolder, bool Encryption, TimeSpan Timeout, bool UseProxySession)
: base(ResourceName)
{
this.timeout = Timeout;
this.useSession = UseProxySession;
StringBuilder sb = new StringBuilder();
int DefaultPort;
sb.Append("http");
if (Encryption)
{
sb.Append('s');
DefaultPort = HttpServer.DefaultHttpsPort;
}
else
DefaultPort = HttpServer.DefaultHttpPort;
sb.Append("://");
sb.Append(RemoteHost);
if (Port != DefaultPort)
{
sb.Append(':');
sb.Append(Port.ToString());
}
if (!string.IsNullOrEmpty(RemoteFolder))
sb.Append(RemoteFolder);
this.baseUri = sb.ToString();
this.encryption = Encryption;
}
/// <summary>
/// If the resource uses user sessions.
/// </summary>
public override bool UserSessions => this.useSession;
/// <summary>
/// If the resource handles sub-paths.
/// </summary>
public override bool HandlesSubPaths => true;
/// <summary>
/// If forwarding is encrypted.
/// </summary>
public bool Encrypted => this.encryption;
/// <summary>
/// If the GET method is allowed.
/// </summary>
public bool AllowsGET => true;
/// <summary>
/// If the POST method is allowed.
/// </summary>
public bool AllowsPOST => true;
/// <summary>
/// If the PUT method is allowed.
/// </summary>
public bool AllowsPUT => true;
/// <summary>
/// If the DELETE method is allowed.
/// </summary>
public bool AllowsDELETE => true;
/// <summary>
/// If the PATCH method is allowed.
/// </summary>
public bool AllowsPATCH => true;
/// <summary>
/// If the TRACE method is allowed.
/// </summary>
public bool AllowsTRACE => true;
/// <summary>
/// Executes the GET method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task GET(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the ranged GET method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <param name="FirstInterval">First byte range interval.</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task GET(HttpRequest Request, HttpResponse Response, ByteRangeInterval FirstInterval)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the POST method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task POST(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the ranged POST method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <param name="Interval">Content byte range.</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task POST(HttpRequest Request, HttpResponse Response, ContentByteRangeInterval Interval)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the PUT method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task PUT(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the ranged PUT method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <param name="Interval">Content byte range.</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task PUT(HttpRequest Request, HttpResponse Response, ContentByteRangeInterval Interval)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the OPTIONS method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public override Task OPTIONS(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the DELETE method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task DELETE(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the PATCH method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task PATCH(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the ranged PATCH method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <param name="Interval">Content byte range.</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task PATCH(HttpRequest Request, HttpResponse Response, ContentByteRangeInterval Interval)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes the TRACE method on the resource.
/// </summary>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
/// <exception cref="HttpException">If an error occurred when processing the method.</exception>
public Task TRACE(HttpRequest Request, HttpResponse Response)
{
return Task.CompletedTask; // Never called. Request processed by custom Execute method below.
}
/// <summary>
/// Executes a method on the resource. The default behaviour is to call the corresponding execution methods defined in the specialized
/// interfaces <see cref="IHttpGetMethod"/>, <see cref="IHttpPostMethod"/>, <see cref="IHttpPutMethod"/> and <see cref="IHttpDeleteMethod"/>
/// if they are defined for the resource.
/// </summary>
/// <param name="Server">HTTP Server</param>
/// <param name="Request">HTTP Request</param>
/// <param name="Response">HTTP Response</param>
public override Task Execute(HttpServer Server, HttpRequest Request, HttpResponse Response)
{
this.ProcessProxyRequest(Server, Request, Response);
return Task.CompletedTask;
}
private async void ProcessProxyRequest(HttpServer Server, HttpRequest Request, HttpResponse Response)
{
try
{
SessionVariables Session = Request.Session;
if (this.useSession)
{
string HttpSessionID;
if (Session is null)
{
HttpSessionID = GetSessionId(Request, Response);
Request.Session = Session = Server.GetSession(HttpSessionID);
}
else if (Request.tempSession)
{
HttpSessionID = Convert.ToBase64String(Hashes.ComputeSHA512Hash(Guid.NewGuid().ToByteArray()));
Response.SetCookie(new Cookie(HttpResource.HttpSessionID, HttpSessionID, null, "/", null, false, true));
Session = Server.SetSession(HttpSessionID, Request.Session);
Request.tempSession = false;
}
}
else
Session = null;
StringBuilder sb = new StringBuilder();
sb.Append(this.baseUri);
sb.Append(Request.SubPath);
if (!string.IsNullOrEmpty(Request.Header.QueryString))
{
sb.Append('?');
sb.Append(Request.Header.QueryString);
}
if (!Uri.TryCreate(sb.ToString(), UriKind.Absolute, out Uri RemoteUri))
{
await Response.SendResponse(new BadRequestException());
return;
}
byte[] Data;
if (Request.HasData)
{
Request.DataStream.Position = 0;
Data = await Request.DataStream.ReadAllAsync();
}
else
Data = null;
HttpClientHandler Handler = WebGetter.GetClientHandler();
string s;
using (HttpClient HttpClient = new HttpClient(Handler, true)
{
Timeout = this.timeout
})
{
using (HttpRequestMessage ProxyRequest = new HttpRequestMessage()
{
RequestUri = RemoteUri,
Method = new HttpMethod(Request.Header.Method)
})
{
if (!(Data is null))
ProxyRequest.Content = new ByteArrayContent(Data);
foreach (HttpField Field in Request.Header)
{
switch (Field.Key)
{
case "Accept":
if (!ProxyRequest.Headers.Accept.TryParseAdd(Field.Value))
throw new InvalidOperationException("Invalid Accept header value: " + Field.Value);
break;
case "Authorization":
int i = Field.Value.IndexOf(' ');
if (i < 0)
ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue(Field.Value);
else
ProxyRequest.Headers.Authorization = new AuthenticationHeaderValue(Field.Value.Substring(0, i), Field.Value.Substring(i + 1).TrimStart());
break;
case "Cookie":
foreach (KeyValuePair<string, string> P in CommonTypes.ParseFieldValues(Field.Value))
{
if (this.useSession && P.Key == HttpSessionID && !(Session is null))
{
if (Session.TryGetVariable(SpacePrefixedHttpSessionID, out Variable v) &&
v.ValueObject is Cookie ProxyCookie)
{
Handler.CookieContainer.Add(ProxyRequest.RequestUri, new System.Net.Cookie(ProxyCookie.Name, ProxyCookie.Value));
}
}
else
Handler.CookieContainer.Add(ProxyRequest.RequestUri, new System.Net.Cookie(P.Key, P.Value));
}
break;
case "Content-Encoding":
case "Content-Length":
case "Transfer-Encoding":
case "Host":
case "Accept-Encoding":
// Igore; will be re-coded.
break;
case "Allow":
case "Content-Disposition":
case "Content-Language":
case "Content-Location":
case "Content-MD5":
case "Content-Range":
case "Content-Type":
case "Last-Modified":
ProxyRequest.Content?.Headers.Add(Field.Key, Field.Value);
break;
default:
if (!Field.Key.StartsWith(':')) // Avoid HTTP/2 pseudo-headers
ProxyRequest.Headers.Add(Field.Key, Field.Value);
break;
}
}
// Forwarded: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Forwarded
// X-Forwarded-Host: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Host
// X-Forwarded-For https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For
// X-Forwarded-Proto https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
// Via https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Via
sb.Clear();
sb.Append("by=");
sb.Append(Request.LocalEndPoint);
sb.Append(";for=");
sb.Append(s = Request.RemoteEndPoint);
if (Request.Header.TryGetHeaderField("X-Forwarded-For", out HttpField ForwardedFor))
ProxyRequest.Headers.Add("X-Forwarded-For", s + ", " + ForwardedFor.Value);
else
ProxyRequest.Headers.Add("X-Forwarded-For", s);
sb.Append(";proto=http");
if (Request.Encrypted)
{
sb.Append('s');
ProxyRequest.Headers.Add("X-Forwarded-Proto", "https");
}
else
ProxyRequest.Headers.Add("X-Forwarded-Proto", "http");
if (!(Request.Header.Host is null))
{
sb.Append(";host=");
sb.Append(s = Request.Header.Host.Value);
ProxyRequest.Headers.Add("X-Forwarded-Host", s);
ProxyRequest.Headers.Add("Forwarded", sb.ToString());
sb.Clear();
sb.Append("HTTP/");
sb.Append(CommonTypes.Encode(Request.Header.HttpVersion, 1));
sb.Append(' ');
sb.Append(s);
if (Request.Header.TryGetHeaderField("Via", out HttpField Via))
{
sb.Append(", ");
sb.Append(Via.Value);
}
ProxyRequest.Headers.Add("Via", sb.ToString());
}
else
ProxyRequest.Headers.Add("Forwarded", sb.ToString());
await this.BeforeForwardRequest.Raise(this, new ProxyRequestEventArgs(ProxyRequest, Request, Response), false);
HttpResponseMessage ProxyResponse = await HttpClient.SendAsync(ProxyRequest);
Response.StatusCode = (int)ProxyResponse.StatusCode;
Response.StatusMessage = ProxyResponse.ReasonPhrase;
foreach (KeyValuePair<string, IEnumerable<string>> Header in ProxyResponse.Headers)
{
switch (Header.Key)
{
case "Transfer-Encoding":
case "X-Content-Type-Options":
break;
case "Set-Cookie":
if (!(Session is null))
{
foreach (string Value in Header.Value)
{
Cookie Cookie = Cookie.FromSetCookie(Value);
if (Cookie is null)
continue;
if (Cookie.Name == HttpSessionID)
Session[SpacePrefixedHttpSessionID] = Cookie;
else
Response.SetCookie(Cookie);
}
}
else
{
foreach (string Value in Header.Value)
{
Cookie Cookie = Cookie.FromSetCookie(Value);
if (Cookie is null)
continue;
Response.SetCookie(Cookie);
}
}
break;
default:
foreach (string Value in Header.Value)
Response.SetHeader(Header.Key, Value);
break;
}
}
if (!(ProxyResponse.Content is null))
{
foreach (KeyValuePair<string, IEnumerable<string>> Header in ProxyResponse.Content.Headers)
{
switch (Header.Key)
{
case "Content-Length":
case "Content-Encoding":
break;
default:
foreach (string Value in Header.Value)
Response.SetHeader(Header.Key, Value);
break;
}
}
byte[] Bin = await ProxyResponse.Content.ReadAsByteArrayAsync();
Response.ContentLength = Bin.Length;
await this.BeforeForwardResponse.Raise(this, new ProxyResponseEventArgs(ProxyResponse, Request, Response), false);
await Response.Write(true, Bin);
}
else
await this.BeforeForwardResponse.Raise(this, new ProxyResponseEventArgs(ProxyResponse, Request, Response), false);
await Response.SendResponse();
}
}
}
catch (HttpException ex)
{
try
{
await Response.SendResponse(ex);
}
catch (Exception)
{
// Ignore
}
}
catch (Exception ex)
{
try
{
await Response.SendResponse(ex);
}
catch (Exception)
{
// Ignore
}
}
}
/// <summary>
/// Event raised before a request is forwarded
/// </summary>
public event EventHandlerAsync<ProxyRequestEventArgs> BeforeForwardRequest;
/// <summary>
/// Event raised before a response is forwarded
/// </summary>
public event EventHandlerAsync<ProxyResponseEventArgs> BeforeForwardResponse;
}
}