forked from atauenis/webone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpTransit.cs
2242 lines (2046 loc) · 90.1 KB
/
HttpTransit.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
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
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using static WebOne.Program;
namespace WebOne
{
/// <summary>
/// Transit transfer of content with applying some edits (HTTP)
/// </summary>
class HttpTransit
{
HttpRequest ClientRequest;
HttpResponse ClientResponse;
LogWriter Log;
byte[] UTF8BOM = Encoding.UTF8.GetPreamble();
const string NoContentType = "webone/unknown-content-type";
Dictionary<string, string> Variables = new();
Uri RequestURL = new("about:blank");
static string LastURL = "http://999.999.999.999/CON";
static HttpStatusCode LastCode = HttpStatusCode.OK;
static string LastContentType = "not-a-carousel";
List<EditSet> EditSets = new();
bool Stop = false;
HttpOperation operation;
int ResponseCode = 502;
string ResponseBody = ":(";
Stream TransitStream = null;
string ContentType = NoContentType;
Encoding SourceContentEncoding = Encoding.Default;
Encoding OutputContentEncoding = ConfigFile.OutputEncoding;
bool EnableTransliteration = false;
string DumpFile = null;
/// <summary>
/// Initialize the Web 2.0 to Web 1.0 HTTP traffic transit operator.
/// </summary>
/// <param name="ClientRequest">Request from HTTP Listener</param>
/// <param name="ClientResponse">Response for HTTP Listener</param>
public HttpTransit(HttpRequest ClientRequest, HttpResponse ClientResponse, LogWriter Log)
{
this.ClientRequest = ClientRequest;
this.ClientResponse = ClientResponse;
this.Log = Log;
}
/// <summary>
/// Convert a Web 2.0 content to Web 1.0-like.
/// </summary>
public void ProcessTransit()
{
#if DEBUG
Log.WriteLine(" Begin process.");
#endif
try
{
//check IP black list
if (CheckString(ClientRequest.RemoteEndPoint.ToString(), ConfigFile.IpBanList))
{
Log.WriteLine(" Banned client.");
ClientResponse.Close();
return;
}
//check IP white list
if (ConfigFile.IpWhiteList.Count > 0)
if (!CheckString(ClientRequest.RemoteEndPoint.ToString(), ConfigFile.IpWhiteList))
{
SendError(403, "You are not in the list of allowed clients. Contact proxy server's administrator to add your IP address in it.");
Log.WriteLine(" Non-whitelisted client.");
return;
}
//check for login to proxy if need
if (ConfigFile.Authenticate.Count > 0 && !ClientRequest.IsSecureConnection)
{
var url = ClientRequest.Url ?? new Uri("http://example.com/");
switch (url.PathAndQuery ?? "")
{
case "/!pac/":
case "/auto/":
case "/auto":
case "/auto.pac":
case "/wpad.dat":
case "/wpad.da":
//PAC is always unprotected
break;
default:
if (string.IsNullOrEmpty(ClientRequest.Headers["Proxy-Authorization"]))
{
Log.WriteLine(" Unauthorized client.");
ClientResponse.AddHeader("Proxy-Authenticate", @"Basic realm=""" + ConfigFile.AuthenticateRealm + @"""");
SendError(407, ConfigFile.AuthenticateMessage);
return;
}
else
{
string auth = Encoding.Default.GetString(Convert.FromBase64String(ClientRequest.Headers["Proxy-Authorization"].Substring(6)));
if (!ConfigFile.Authenticate.Contains(auth))
{
Log.WriteLine(" Incorrect login: '{0}'.", auth);
ClientResponse.AddHeader("Proxy-Authenticate", @"Basic realm=""" + ConfigFile.AuthenticateRealm + @" (retry)""");
SendError(407, ConfigFile.AuthenticateMessage + "<p>Your login or password is not correct. Please try again.</p>");
return;
}
}
break;
}
}
//check for Secure (HTTPS) Proxy mode
if (ClientRequest.HttpMethod.ToUpper() == "CONNECT")
{
try
{
//check validness of request
if (!ClientRequest.RawUrl.Contains(':'))
{
Log.WriteLine(" Invalid CONNECT target: {0}", ClientRequest.RawUrl);
SendError(400, "Invalid request. Correct format is <pre>CONNECT example.com:443 HTTP/1.1</pre>");
return;
}
//work as HTTPS proxy
if (ClientRequest.RawUrl.EndsWith(":443"))
{
new HttpSecureServer(ClientRequest, ClientResponse, Log).Accept();
}
else
{
new HttpSecureNonHttpServer(
ClientRequest,
ClientResponse,
CheckString(ClientRequest.RawUrl.ToLowerInvariant(), ConfigFile.NonHttpSslServers),
Log)
.Accept();
}
return;
}
catch (Exception ex)
{
Log.WriteLine(" Cannot made SSL connection: {0}", ex);
SendError(501, "Sorry, an error occured on creating client SSL tunnel: " + ex.Message + "<br>Error " + ex.StackTrace.Replace("\n", "<br>")); ;
return;
}
}
//get request URL and referer URL
//think: may be need only RequestURL = ClientRequest.Url ?
try { RequestURL = new UriBuilder(ClientRequest.RawUrl).Uri; }
catch { RequestURL = ClientRequest.Url; };
string RefererUri = ClientRequest.Headers["Referer"];
if (RefererUri == "") RefererUri = null;
//check for blacklisted URL
if (CheckString(RequestURL.ToString(), ConfigFile.UrlBlackList))
{
Log.WriteLine(" Blacklisted URL.");
SendError(403, "Access to this web page is disallowed by proxy settings.");
return;
}
//check for HTTP/1.0-only client
if (!string.IsNullOrWhiteSpace(ClientRequest.Headers["User-Agent"]) && CheckStringRegExp(ClientRequest.Headers["User-Agent"], ConfigFile.Http10Only.ToArray()))
{ ClientResponse.SimpleContentType = true; }
//set protocol version
ClientResponse.ProtocolVersion = ClientRequest.ProtocolVersion;
//get proxy's IP address
if (ClientRequest.LocalEndPoint.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
LocalIP = ClientRequest.LocalEndPoint.Address.ToString(); // IPv4
else
LocalIP = "[" + ClientRequest.LocalEndPoint.Address.ToString() + "]"; //IPv6
//fill variables
UriBuilder builder = new UriBuilder(RequestURL);
var DefaultVars = new Dictionary<string, string>
{
{ "URL", RequestURL.ToString() },
{ "Url", Uri.EscapeDataString(RequestURL.ToString()) },
{ "UrlDomain", builder.Host },
{ "UrlNoDomain", (builder.Query == "" ? builder.Path : builder.Path + "?" + builder.Query) },
{ "UrlNoQuery", builder.Scheme + "://" + builder.Host + "/" + builder.Path },
{ "UrlNoPort", builder.Scheme + "://" + builder.Host + "/" + (builder.Query == "" ? builder.Path : builder.Path + "?" + builder.Query) },
{ "UrlHttps", "https://" + builder.Host + "/" + (builder.Query == "" ? builder.Path : builder.Path + "?" + builder.Query) },
{ "UrlHttp", "http://" + builder.Host + "/" + (builder.Query == "" ? builder.Path : builder.Path + "?" + builder.Query) },
{ "Proxy", GetServerName() },
{ "ProxyHost", ConfigFile.DefaultHostName == Environment.MachineName ? LocalIP : ConfigFile.DefaultHostName },
{ "Method", ClientRequest.HttpMethod },
{ "HttpVersion", ClientRequest.ProtocolVersion.ToString() }
};
foreach (var entry in Program.Variables) { DefaultVars.TryAdd(entry.Key, entry.Value); }
//check for internal URL
if (ClientRequest.Kind == HttpUtil.RequestKind.StandardHttp)
{
// Internal URIs
string InternalPage = "/";
if (RequestURL.Segments.Length > 1) InternalPage = RequestURL.Segments[1].ToLower();
InternalPage = "/" + InternalPage.TrimEnd('/');
SendInternalPage(InternalPage);
return;
}
if (ClientRequest.Kind == HttpUtil.RequestKind.AlternateProxy)
{
// "Local proxy mode"
string FixedUrl = ClientRequest.RawUrl[1..];
RequestURL = new Uri(FixedUrl);
Log.WriteLine(" Alternate: {0}", RequestURL);
}
if (ClientRequest.Kind == HttpUtil.RequestKind.DirtyAlternateProxy)
{
// "Dirty local proxy mode", try to use last used host: http://localhost/favicon.ico = http://example.com/favicon.ico
string FixedUrl = "http://" + new Uri(LastURL).Host + RequestURL.LocalPath;
RequestURL = new Uri(FixedUrl);
if (RequestURL.Host == "999.999.999.999") { SendError(404, "The proxy server cannot guess domain name."); return; }
Log.WriteLine(" Dirty alternate: {0}", RequestURL);
}
//if (LocalMode && ClientRequest.Headers["User-Agent"] != null && ClientRequest.Headers["User-Agent"].Contains("WebOne"))
if (ClientRequest.Headers["User-Agent"] != null && ClientRequest.Headers["User-Agent"].Contains("WebOne"))
{
SendError(403, "Loop requests are probhited.");
return;
}
//check for FTP/GOPHER/WAIS-over-HTTP requests (a.k.a. CERN Proxy Mode)
//https://support.microsoft.com/en-us/help/166961/how-to-ftp-with-cern-based-proxy-using-wininet-api
if (RequestURL.ToString().Contains("://"))
{
if (!RequestURL.Scheme.StartsWith("http")) Log.WriteLine(" CERN Proxy request to {0} detected.", RequestURL.Scheme.ToUpper());
string[] KnownProtocols = { "http", "https", "ftp" };
if (!CheckString(RequestURL.Scheme, KnownProtocols))
{
string BadProtocolMessage =
"<p>You're attempted to request content from <i>" + ClientRequest.RawUrl + "</i>. " +
"The protocol specified in the URL is not supported by this proxy server.</p>" +
"<p>Consider connect directly to the server, bypassing the proxy. This error message may also appear if your Web browser settings have enabled " +
"<b>"Use proxy for all protocols"</b> option. Uncheck it and set only for protocols supported by WebOne. List of them can be found in project's Wiki.</p>";
SendInfoPage(RequestURL.Scheme.ToUpper() + " Is Not Supported", "Unsupported protocol", BadProtocolMessage, 501);
return;
}
//all CERN-style requests are processed only with HttpServer2 used to listen traffic
//old HttpServer1 does not accept them as HttpListener (used since WebOne 0.8.5) ignores non-HTTP addresses
}
if (ClientRequest.RawUrl.ToLower().StartsWith("ftp://"))
{
//HTTP->FTP mode (CERN-compatible)
InfoPage WebFtpRedirect = new();
WebFtpRedirect.Title = "CERN Proxy Emulation Redirect";
WebFtpRedirect.HttpStatusCode = 302;
WebFtpRedirect.HttpHeaders.Add("Location", "http://" + GetServerName() + "/!ftp/?client=-1&uri=" + Uri.EscapeDataString(ClientRequest.RawUrl));
SendInfoPage(WebFtpRedirect);
return;
}
if (ClientRequest.RawUrl.ToLower().StartsWith("http://ftp:"))
{
//HTTP->FTP mode (Netscape)
InfoPage WebFtpRedirect = new();
WebFtpRedirect.Title = "CERN Proxy Emulation Redirect (NS)";
WebFtpRedirect.HttpStatusCode = 302;
WebFtpRedirect.HttpHeaders.Add("Location", "http://" + GetServerName() + "/!ftp/?client=-1&uri=" + Uri.EscapeDataString(ClientRequest.RawUrl.Substring(7)));
SendInfoPage(WebFtpRedirect);
return;
}
if (ClientRequest.RawUrl.ToLower().StartsWith("http://ftp//"))
{
//HTTP->FTP mode (MS IE)
InfoPage WebFtpRedirect = new();
WebFtpRedirect.Title = "CERN Proxy Emulation Redirect (IE)";
WebFtpRedirect.HttpStatusCode = 302;
WebFtpRedirect.HttpHeaders.Add("Location", "http://" + GetServerName() + "/!ftp/?client=-1&uri=" + Uri.EscapeDataString("ftp://" + ClientRequest.RawUrl.Substring(12)));
SendInfoPage(WebFtpRedirect);
return;
}
//dirty workarounds for HTTP>HTTPS redirection bugs ("carousels")
//should redirect on 302s or reloadings from 200 and only on htmls
if ((RequestURL.AbsoluteUri == RefererUri || RequestURL.AbsoluteUri == LastURL) &&
RequestURL.AbsoluteUri != "" &&
(LastContentType.StartsWith("text/htm") || LastContentType == "") &&
(((int)LastCode > 299 && (int)LastCode < 400) || LastCode == HttpStatusCode.OK) &&
ClientRequest.HttpMethod != "POST" &&
ClientRequest.HttpMethod != "CONNECT" &&
!Program.CheckString(RequestURL.AbsoluteUri, ConfigFile.ForceHttps) &&
RequestURL.Host.ToLower() != Environment.MachineName.ToLower() &&
RequestURL.Host.ToLower() != LocalIP &&
RequestURL.Host.ToLower() != ConfigFile.DefaultHostName.ToLower())
{
Log.WriteLine(" Carousel detected.");
if (!LastURL.StartsWith("https") && !RequestURL.AbsoluteUri.StartsWith("https")) //if http is gone, try https
RequestURL = new Uri("https" + RequestURL.AbsoluteUri.Substring(4));
if (LastURL.StartsWith("https")) //if can't use https, try again http
RequestURL = new Uri("http" + RequestURL.AbsoluteUri.Substring(4));
}
//make referer secure if need
try
{
if (RequestURL.Host == new Uri(RefererUri ?? "about:blank").Host)
if (RequestURL.AbsoluteUri.StartsWith("https://") && !RefererUri.StartsWith("https://"))
RefererUri = "https" + RefererUri.Substring(4);
}
catch { }
LastURL = RequestURL.AbsoluteUri;
LastContentType = "unknown/unknown"; //will be populated in MakeOutput
LastCode = HttpStatusCode.OK; //same
//make reply
//SendError(200, "Okay, bro! Open " + RequestURL);
if (RequestURL.AbsoluteUri.Contains("??")) { SendError(400, "Too many questions."); return; }
if (RequestURL.AbsoluteUri.Length == 0) { SendError(400, "Empty URL."); return; }
if (RequestURL.AbsoluteUri == "") return;
if (RequestURL.AbsoluteUri.Contains(" ")) RequestURL = new Uri(RequestURL.AbsoluteUri.Replace(" ", "%20")); //fix spaces in wrong-formed URLs
//check for available edit sets
foreach (EditSet set in ConfigFile.EditRules)
{
if (!set.CorrectHostOS) continue;
if (CheckStringRegExp(RequestURL.AbsoluteUri, set.UrlMasks.ToArray()) &&
!CheckStringRegExp(RequestURL.AbsoluteUri, set.UrlIgnoreMasks.ToArray()))
{
if (set.HttpOnly && ClientRequest.IsSecureConnection) continue;
if (set.HttpsOnly && !ClientRequest.IsSecureConnection) continue;
if (set.HeaderMasks.Count > 0 && ClientRequest.Headers != null)
{
//check if there are headers listed in OnHeader detection rules
bool HaveGoodMask = false;
foreach (string HdrMask in set.HeaderMasks)
{
foreach (string RqHdrName in ClientRequest.Headers.AllKeys)
{
string header = RqHdrName + ": " + ClientRequest.Headers[RqHdrName];
if (Regex.IsMatch(header, HdrMask))
{
HaveGoodMask = true;
EditSets.Add(set);
break;
}
}
if (HaveGoodMask) break;
}
}
else
{
EditSets.Add(set);
}
}
}
//check for URL white list (if any)
if (ConfigFile.UrlWhiteList.Count > 0)
if (!CheckString(RequestURL.ToString(), ConfigFile.UrlWhiteList))
{
SendError(403, "Proxy server administrator has been limited this proxy server to work with several web sites only.");
Log.WriteLine(" URL out of white list.");
return;
}
try
{
int CL = 0;
if (ClientRequest.Headers["Content-Length"] != null) CL = Int32.Parse(ClientRequest.Headers["Content-Length"]);
//make and send HTTPS request to destination server
WebHeaderCollection whc = new WebHeaderCollection();
//prepare headers
if (RequestURL.Scheme.ToLower() == "https" || CheckString(RequestURL.Host, ConfigFile.ForceHttps))
{
foreach (string h in ClientRequest.Headers.Keys)
{
whc.Add(h, ClientRequest.Headers[h].Replace("http://", "https://"));
}
}
else
{
foreach (string h in ClientRequest.Headers.Keys)
{
whc.Add(h, ClientRequest.Headers[h]);
}
}
if (whc["Origin"] == null & whc["Referer"] != null) whc.Add("Origin: " + new Uri(whc["Referer"]).Scheme + "://" + new Uri(whc["Referer"]).Host);
if (whc["User-Agent"] != null) whc["User-Agent"] = GetUserAgent(whc["User-Agent"]);
//perform edits on the request
foreach (EditSet Set in EditSets)
{
if (Set.IsForRequest)
{
//if URL mask is single, allow use RegEx groups (if any) for replace
bool UseRegEx = (Set.UrlMasks.Count == 1 && new Regex(Set.UrlMasks[0]).GetGroupNames().Count() > 1);
#if DEBUG
if (UseRegEx) Log.WriteLine(" RegExp groups are available on {0}.", Set.UrlMasks[0]);
#endif
foreach (EditSetRule Edit in Set.Edits)
{
switch (Edit.Action)
{
case "AddHeaderDumping":
case "AddRequestDumping":
case "AddDumping":
//dump initializing must be first
DumpFile = ProcessUriMasks(Edit.Value)
.Replace(":", "-")
.Replace("<", "(")
.Replace(">", ")")
.Replace("?", "-")
.Replace("|", "!");
if (DumpFile.Length > 128) { DumpFile = DumpFile.Substring(0, 128) + "-CUT.log"; } //about half of Windows path limitation
Dump(ClientRequest.HttpMethod + " " + ClientRequest.RawUrl + " HTTP/" + ClientRequest.ProtocolVersion.ToString());
break;
case "AddInternalRedirect":
string NewUrlInternal = UseRegEx ? ProcessUriMasks(new Regex(Set.UrlMasks[0]).Replace(RequestURL.AbsoluteUri, Edit.Value))
: ProcessUriMasks(Edit.Value);
Log.WriteLine(" Fix to {0} internally", NewUrlInternal);
Dump("~Internal redirect to: " + NewUrlInternal);
RequestURL = new Uri(NewUrlInternal);
break;
case "AddRedirect":
//string NewUrl302 = UseRegEx ? ProcessUriMasks(new Regex(Set.UrlMasks[0]).Replace(RequestURL.AbsoluteUri, Edit.Value))
// : ProcessUriMasks(Edit.Value);
string NewUrl302 = "";
if (UseRegEx)
{
var match = new Regex(Set.UrlMasks[0]).Match(RequestURL.AbsoluteUri);
if (match.Groups.Count > 0)
NewUrl302 = ProcessUriMasks(new Regex(Set.UrlMasks[0]).Replace(match.Groups[0].Value, Edit.Value));
else NewUrl302 = ProcessUriMasks(Edit.Value);
}
else NewUrl302 = ProcessUriMasks(Edit.Value);
Log.WriteLine(" Fix to {0}", NewUrl302);
Dump("~Redirect using 302 to: " + NewUrl302);
SendRedirect(NewUrl302, "Брось каку!");
return;
case "AddRequestHeader":
case "AddHeader":
string Header = ProcessUriMasks(Edit.Value);
Dump("~Add request header: " + Header);
if (whc[Edit.Value.Substring(0, Edit.Value.IndexOf(": "))] == null) whc.Add(Header);
break;
case "AddRequestHeaderFindReplace":
FindReplaceEditSetRule hdr_rule = (FindReplaceEditSetRule)Edit;
foreach (var hdr in whc.AllKeys)
{
whc[hdr] = whc[hdr].Replace(hdr_rule.Find, hdr_rule.Replace);
Dump("~Request header find&replace: '" + hdr_rule.Find + "' / '" + hdr_rule.Replace + "'");
}
break;
case "AddOutputEncoding":
OutputContentEncoding = GetCodePage(Edit.Value);
Dump("~Output encoding set to: " + OutputContentEncoding.BodyName);
break;
case "AddTranslit":
EnableTransliteration = ToBoolean(Edit.Value);
Dump("~Enable transliteration");
break;
}
}
}
}
foreach (var hdr in whc.AllKeys)
{
Variables.Add("Request." + hdr, whc[hdr]);
Dump(hdr + ": " + whc[hdr]);
}
Dump();
//send the request
operation = new HttpOperation(Log);
operation.Method = ClientRequest.HttpMethod;
operation.RequestHeaders = whc;
operation.URL = RequestURL;
SendRequest(operation);
}
catch (System.Net.Http.HttpRequestException httpex)
{
//an network error has been catched
Log.WriteLine(" Cannot load this page: {0}.", httpex.Message);
Dump("!Network error: " + httpex.Message);
//try to load the page from Archive.org, then return error message if need
if (!LookInWebArchive())
{
#if DEBUG
//return full debug output
string err = GetFullExceptionMessage(httpex);
SendInfoPage("WebOne cannot load the page", "Can't load the page: " + httpex.Message, "<i>" + err.ToString().Replace("\n", "<br>") + "</i><br>URL: " + RequestURL.AbsoluteUri + "<br>Debug mode enabled.");
return;
#else
//return nice error message
string ErrorTitle = "connection error", ErrorMessageHeader = "Cannot load this page", ErrorMessage = "";
if (httpex.InnerException != null)
{
switch (httpex.InnerException.GetType().ToString())
{
case "System.Net.Sockets.SocketException":
System.Net.Sockets.SocketException sockerr = httpex.InnerException as System.Net.Sockets.SocketException;
switch (sockerr.SocketErrorCode)
{
case System.Net.Sockets.SocketError.HostNotFound:
//server not found
ErrorMessageHeader = "Cannot find the server";
ErrorMessage = "<p><big>" + sockerr.Message + "</big></p>" +
"<ul><li>Check the address for typing errors such as <strong>ww</strong>.example.com instead of <strong>www</strong>.example.com.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>" +
"</ul>";
break;
case System.Net.Sockets.SocketError.TimedOut:
//connection timeout
ErrorMessageHeader = "The connection has timed out";
ErrorMessage = "<p><big>" + sockerr.Message + "</big></p>" +
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>" +
"</ul>";
break;
case System.Net.Sockets.SocketError.ConnectionRefused:
//connection broken
ErrorMessageHeader = "The connection was refused";
ErrorMessage = "<p><big>" + sockerr.Message + "</big></p>" +
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>" +
"</ul>";
break;
case System.Net.Sockets.SocketError.ConnectionReset:
//connection reset
ErrorMessageHeader = "The connection has been reset";
ErrorMessage = "<p><big>" + sockerr.Message + "</big></p>" +
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>" +
"</ul>";
break;
default:
ErrorMessageHeader = "The connection can't be stablished";
ErrorMessage = "<p><big>" + sockerr.Message + "</big></p>" +
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>" +
"</ul><br>Error code: " + sockerr.SocketErrorCode;
break;
}
break;
case "WebOne.TlsPolicyErrorException":
//certificate is invalid (bad date, domain name, etc)
string polerr = "";
switch((httpex.InnerException as TlsPolicyErrorException).PolicyError){
case System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable:
polerr = "Certificate is not available.";
break;
case System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch:
polerr = "The certificate is issued for another site.";
break;
case System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors:
polerr = "Certificate chain is incorrect.";
break;
default:
polerr = httpex.InnerException.Message;
break;
}
ErrorMessageHeader = "Secure connection could not be established";
ErrorMessage = "<p><big>" + polerr + "</big></p>" +
"<ul><li>The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.</li>" +
"<li>Make sure that the OS on the proxy server have all updates installed.</li>" +
"<li>Check date and time on the proxy server.</li>" +
"<li>Verify that the proxy server operating system have proper support for TLS/SSL version and chiphers used on the site.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>To disable this security check, set <q><b>ValidateCertificates=no</b></q> in proxy configuration file. But this will make the proxy less secure, do this at your own risk.</li>" +
"</ul>";
break;
default:
ErrorTitle = httpex.InnerException.GetType().ToString();
ErrorMessage = "There are problems, that are preventing from displaying the page:<br>" + GetFullExceptionMessage(httpex).Replace("\n", "<br>");
break;
}
}
else
{
ErrorTitle = httpex.InnerException.GetType().ToString();
ErrorMessage = "An error occured: " + httpex.Message;
}
ErrorMessage += "<br>URL: " + RequestURL.AbsoluteUri;
SendInfoPage("WebOne: " + ErrorTitle, ErrorMessageHeader, ErrorMessage);
return;
#endif
}
}
catch (System.Threading.Tasks.TaskCanceledException)
{
Dump("!Connection timeout (100 sec)");
string ErrorMessageHeader = "The connection has timed out";
string ErrorMessage = "<p><big>The request was canceled due to Timeout of 100 seconds elapsing.</big></p>" +
"<ul><li>The site could be temporarily unavailable or too busy. Try again in a few moments.</li>" +
"<li>Try to use an <a href=\"http://web.archive.org/web/" + DateTime.Now.Year + "/" + RequestURL.AbsoluteUri + "\">" + "archived copy</a> of the web site.</li>" +
"<li>Internet Archive sometimes became busy. Be patient, wait a some time.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"<li>If your proxy server or network is protected by a firewall, make sure that WebOne is permitted to access the Web.</li>" +
"</ul>";
ErrorMessage += "<br>URL: " + RequestURL.AbsoluteUri;
SendInfoPage("WebOne: Operation timeout", ErrorMessageHeader, ErrorMessage);
return;
}
catch (InvalidDataException)
{
Dump("!Decompression failed");
string ErrorMessageHeader = "Invalid data has been recieved";
string ErrorMessage = "<p><big>Cannot decode HTTP data.</big></p>" +
"<ul>Remote server may use unsupported HTTP compression algorithm." +
"<li>Try to set AllowHttpCompression=false option in configuration file to skip HTTP decompression, which may cause this error due to .NET bug.</li>" +
"<li>Installing a newer version of .NET Runtime also <i>may</i> solve the problem.</li>" +
"<li>If you are unable to load any pages, check your proxy server's network connection.</li>" +
"</ul>";
ErrorMessage += "<br>URL: " + RequestURL.AbsoluteUri;
SendInfoPage("WebOne: Decompression failed", ErrorMessageHeader, ErrorMessage, 500);
return;
}
catch (UriFormatException)
{
Dump("!Invalid URL");
SendError(400, "The URL <b>" + RequestURL.AbsoluteUri + "</b> is not valid.");
return;
}
catch (Exception ex)
{
try { Dump("!Guru meditation: " + ex.Message); } catch { }
Log.WriteLine(" ============GURU MEDITATION:\n{1}\nOn URL '{2}', Method '{3}'. Returning 500.============", null, ex.ToString(), RequestURL.AbsoluteUri, ClientRequest.HttpMethod);
SendError(500, "Guru meditaion at URL " + RequestURL.AbsoluteUri + ":<br><b>" + ex.Message + "</b><br><i>" + ex.StackTrace.Replace("\n", "\n<br>") + "</i>");
return;
}
//look in Web Archive if 404
if (ResponseCode >= 403 && ConfigFile.SearchInArchive && ClientRequest.HttpMethod != "POST" && ClientRequest.HttpMethod != "PUT" && !Stop)
{
LookInWebArchive();
}
//shorten Web Archive error page if need
if (ResponseCode >= 403 && RequestURL.AbsoluteUri.StartsWith("http://web.archive.org/web/") && ConfigFile.ShortenArchiveErrors)
{
Log.WriteLine(" Wayback Machine error page shortened.");
switch (ResponseCode)
{
case 404:
string ErrMsg404 =
"<p><b>The Wayback Machine has not archived that URL.</b></p>" +
"<p>Try to slightly change the URL.</p>" +
"<small><i>You see this message because ShortenArchiveErrors option is enabled.</i></small>";
SendError(404, ErrMsg404);
return;
case 403:
string ErrMsg403 =
"<p><b>This URL has been excluded from the Wayback Machine.</b></p>" +
"<p>This page is not present in Web Archive.</p>" +
"<small><i>You see this message because ShortenArchiveErrors option is enabled.</i></small>";
SendError(404, ErrMsg403);
return;
default:
string ErrMsg000 =
"<p><b>The Wayback Machine cannot give this page.</b></p>" +
"<p>This is reason: " + ((HttpStatusCode)ResponseCode).ToString() + ".</p>" +
"<small><i>You see this message because ShortenArchiveErrors option is enabled.</i></small>";
SendError(404, ErrMsg000);
return;
}
}
//try to return...
try
{
if (true)
{
//ClientResponse.ProtocolVersion = new Version(1, 1);
ClientResponse.StatusCode = ResponseCode;
ClientResponse.AddHeader("Via", "HTTP/1.0 WebOne/" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);
if (string.IsNullOrEmpty(ClientResponse.Headers["Content-Type"]) && !string.IsNullOrEmpty(ContentType))
{
ClientResponse.AddHeader("Content-Type", ContentType);
}
if (TransitStream == null)
{
byte[] RespBuffer;
RespBuffer = (OutputContentEncoding ?? SourceContentEncoding).GetBytes(ResponseBody).ToArray();
ClientResponse.ContentLength64 = RespBuffer.Length;
if (ClientResponse.ContentLength64 > 300 * 1024) Log.WriteLine(" Sending binary.");
if (ClientRequest.KeepAlive) ClientResponse.AddHeader("Proxy-Connection", "keep-alive");
ClientResponse.SendHeaders();
ClientResponse.OutputStream.Write(RespBuffer, 0, RespBuffer.Length);
if (DumpFile != null)
{
foreach (var hdr in ClientResponse.Headers.AllKeys)
{
Dump(hdr + ": " + ClientResponse.Headers[hdr]);
}
Dump("\n");
if (ClientResponse.ContentLength64 < 1024) Dump(ResponseBody);
else Dump("Over 1 KB response body");
}
}
else
{
if (TransitStream.CanSeek) ClientResponse.ContentLength64 = TransitStream.Length;
if (ClientRequest.KeepAlive) ClientResponse.AddHeader("Proxy-Connection", "keep-alive");
ClientResponse.SendHeaders();
TransitStream.CopyTo(ClientResponse.OutputStream);
if (DumpFile != null)
{
foreach (var hdr in ClientResponse.Headers.AllKeys)
{
Dump(hdr + ": " + ClientResponse.Headers[hdr]);
}
Dump("\nBody is binary stream");
}
}
ClientResponse.KeepAlive = true;
ClientResponse.Close();
#if DEBUG
Log.WriteLine(" Document sent.");
#endif
}
}
catch (Exception ex)
{
if (!ConfigFile.HideClientErrors)
#if DEBUG
Log.WriteLine("<Can't return reply. " + ex.Message + ex.StackTrace);
#else
Log.WriteLine("<Can't return reply. " + ex.Message);
#endif
}
}
catch (Exception E)
{
Log.WriteLine(" A error has been catched: {1}\n{0}\t Please report to author.", null, E.ToString().Replace("\n", "\n{0}\t "));
SendError(500, "An error occured: " + E.ToString().Replace("\n", "\n<BR>"));
}
try { Dump("END."); } catch { }
#if DEBUG
Log.WriteLine(" End process.");
#endif
}
/// <summary>
/// Send an internal page.
/// </summary>
/// <param name="InternalPageId">Name of internal page (lowercase, never ends with "/").</param>
private void SendInternalPage(string InternalPageId)
{
try
{
Log.WriteLine(" Internal page: {0} ", InternalPageId);
switch (InternalPageId)
{
case "/":
case "/!":
case "/!/":
SendInternalStatusPage();
return;
case "/!codepages":
case "/!codepages/":
string codepages = "<p>The following code pages are available: <br>\n" +
"<table><tr><td><b>Name</b></td><td><b>#</b></td><td><b>Description</b></td></tr>\n";
codepages += "<tr><td><b>AsIs</b></td><td>0</td><td>Keep original encoding (code page)</td></tr>\n";
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
bool IsOutputEncodingListed = false;
foreach (EncodingInfo cp in Encoding.GetEncodings())
{
codepages += "<tr><td>";
codepages += "<b>" + cp.Name + "</b></td><td>" + cp.CodePage + "</td><td>" + cp.DisplayName;
if (ConfigFile.OutputEncoding != null && cp.CodePage == ConfigFile.OutputEncoding.CodePage)
{
codepages += " <b>(Current)</b>";
IsOutputEncodingListed = true;
}
/*codepages += "<td>";
if (GetCodePage("Win").CodePage == cp.CodePage) codepages += "Windows "ANSI"";
if (GetCodePage("DOS").CodePage == cp.CodePage) codepages += "DOS "OEM"";
if (GetCodePage("Mac").CodePage == cp.CodePage) codepages += "MacOS classic";
if (GetCodePage("ISO").CodePage == cp.CodePage) codepages += "ISO";
if (GetCodePage("EBCDIC").CodePage == cp.CodePage) codepages += "IBM EBCDIC";
codepages += "</td>";*/
codepages += "</td></tr>\n";
}
codepages += "</table><br>Use any of these or from <a href=\"http://docs.microsoft.com/en-us/dotnet/api/system.text.encoding.getencodings?view=net-6.0\">.NET documentation</a>.</p>\n";
codepages += "<p>Code pages for current server's locale:\n" +
"<table>" +
"<tr><td>Windows "ANSI"</td><td>" + GetCodePage("Win").WebName + "</td></tr>\n" +
"<tr><td>DOS "OEM"</td><td>" + GetCodePage("DOS").WebName + "</td></tr>\n" +
"<tr><td>MacOS classic</td><td>" + GetCodePage("Mac").WebName + "</td></tr>\n" +
"<tr><td>ISO</td><td>" + GetCodePage("ISO").WebName + "</td></tr>\n" +
"<tr><td>EBCDIC</td><td>" + GetCodePage("EBCDIC").WebName + "</td></tr>\n" +
"</table>Clients without UTF-8 support will got content in these code pages.</p>\n";
if (!IsOutputEncodingListed && ConfigFile.OutputEncoding != null)
codepages += "<br>Current output encoding: <b>" + ConfigFile.OutputEncoding.WebName + "</b> "" + ConfigFile.OutputEncoding.EncodingName + "" (# " + ConfigFile.OutputEncoding.CodePage + ").\n";
if (ConfigFile.OutputEncoding == null)
codepages += "<br>Current output encoding: <b>same as source</b>.\n";
SendInfoPage("WebOne: List of supported code pages", "Content encodings", codepages);
return;
case "/!img-test":
case "/!img-test/":
if (ConfigFile.EnableManualConverting)
{
SendError(200, @"ImageMagick test.<br><img src=""/!convert/?src=logo.webp&dest=gif&type=image/gif"" alt=""ImageMagick logo"" width=640 height=480><br>A wizard should appear nearby.");
return;
}
else
{
SendError(200, @"ImageMagick test.<br><img src=""/!imagemagicktest.gif"" alt=""ImageMagick logo"" width=640 height=480><br>A wizard should appear nearby.");
return;
}
case "/!imagemagicktest.gif":
foreach (Converter Cvt in ConfigFile.Converters)
{
if (Cvt.Executable == "convert" && !Cvt.SelfDownload)
{
var SrcStream = File.OpenRead("logo.webp");
SendStream(Cvt.Run(Log, SrcStream, "", "", "gif", "https://github.com/atauenis/webone/"), "image/gif", true);
return;
}
}
SendInfoPage("WebOne: ImageMagick error",
"Error",
"<p>ImageMagick's <b>convert</b> utility is not properly registered in <b>[Converters]</b> section of proxy configuration.</p>" +
"<p>Make sure that the line is present in <code>[Converters]</code> section of configuration: <code>convert %SRC% %ARG1% %DESTEXT%:- %ARG2%</code></p>",
500);
return;
case "/!convert":
case "/!convert/":
if (!ConfigFile.EnableManualConverting)
{
SendInfoPage("WebOne: Feature disabled", "Feature disabled", "Manual file converting is disabled for security purposes.<br>Proxy administrator can enable it via <code>[Server]</code> section, <code>EnableManualConverting</code> option.", 500);
return;
}
string SrcUrl = "", Src = "", Dest = "xbm", DestMime = "image/x-xbitmap", Converter = "convert", Args1 = "", Args2 = "";
//parse URL
Match FindSrc = Regex.Match(RequestURL.Query, @"(src)=([^&]+)");
Match FindSrcUrl = Regex.Match(RequestURL.Query, @"(url)=([^&]+)");
Match FindDest = Regex.Match(RequestURL.Query, @"(dest)=([^&]+)");
Match FindDestMime = Regex.Match(RequestURL.Query, @"(type)=([^&]+)");
Match FindConverter = Regex.Match(RequestURL.Query, @"(util)=([^&]+)");
Match FindArg1 = Regex.Match(RequestURL.Query, @"(arg)=([^&]+)");
Match FindArg2 = Regex.Match(RequestURL.Query, @"(arg2)=([^&]+)");
if (FindSrc.Success)
Src = Uri.UnescapeDataString(FindSrc.Groups[2].Value);
if (FindSrcUrl.Success)
SrcUrl = Uri.UnescapeDataString(FindSrcUrl.Groups[2].Value);
//BUG: sometimes URL gets unescaped when opening via WMP
// (mostly via UI, and all load retries via FF plugin, strange but 1st plugin's attempt is valid)
if (FindDest.Success)
Dest = Uri.UnescapeDataString(FindDest.Groups[2].Value);
if (FindDestMime.Success)
DestMime = Uri.UnescapeDataString(FindDestMime.Groups[2].Value);
if (FindConverter.Success)
Converter = Uri.UnescapeDataString(FindConverter.Groups[2].Value);
if (FindArg1.Success)
Args1 = Uri.UnescapeDataString(FindArg1.Groups[2].Value);
if (FindArg2.Success)
Args2 = Uri.UnescapeDataString(FindArg2.Groups[2].Value);
if (Src == "CON:") throw new ArgumentException("Bad source file name");
//detect info page requestion
if (!FindSrcUrl.Success && !FindSrc.Success)
{
SendError(200, "<big>Here you can summon ImageMagick to convert a picture file</big>.<br>" +
"<p>Usage: /!convert/?url=https://example.com/filename.ext&dest=gif&type=image/gif<br>" +
"or: /!convert/?src=filename.ext&dest=gif&type=image/gif</p>" +
"<p>See <a href=\"http://github.com/atauenis/webone/wiki\">WebOne wiki</a> for help on this.</p>");
return;
}
//find converter and use it
foreach (Converter Cvt in ConfigFile.Converters)
{
if (Cvt.Executable == Converter)
{
HttpOperation HOper = new HttpOperation(Log);
Stream SrcStream = null;
//find source file placement
if (FindSrcUrl.Success)
{
//download source file
if (!Cvt.SelfDownload) try
{
HOper.URL = new Uri(SrcUrl);
HOper.Method = "GET";
HOper.RequestHeaders = new WebHeaderCollection();
#if DEBUG
Log.WriteLine(">Downloading source stream (connecting)...");
#else
Log.WriteLine(">Downloading source stream...");
#endif
HOper.SendRequest();
#if DEBUG
Log.WriteLine(">Downloading source stream (receiving)...");
#endif
HOper.GetResponse();
SrcStream = HOper.ResponseStream;
}
catch (Exception DlEx)
{
Log.WriteLine(" Converter cannot download source: {0}", DlEx.Message);
SendError(503,
"<p><big><b>Converter cannot download the source</b>: " + DlEx.Message + "</big></p>" +
"Source URL: " + SrcUrl);
return;
}
}
else
{
//open local source file
SrcUrl = "http://0.0.0.0/localfile";
if (!Cvt.SelfDownload) try
{
if (!File.Exists(Src))
{
if (File.Exists(new FileInfo(AppContext.BaseDirectory).DirectoryName + Path.DirectorySeparatorChar + Src))
Src = new FileInfo(AppContext.BaseDirectory).DirectoryName + Path.DirectorySeparatorChar + Src;
else
throw new FileNotFoundException("No such file: " + Src);
}
SrcStream = File.OpenRead(Src);
}
catch (Exception OpenEx)
{
Log.WriteLine(" Converter cannot open source: {0}", OpenEx.Message);
SendError(503,
"<p><big><b>Converter cannot open the source</b>: " + OpenEx.Message + "</big></p>" +
"Source URL: " + SrcUrl);
return;
}
}
//go to converter
try
{
//run converter & return result
SendStream(Cvt.Run(Log, SrcStream, Args1, Args2, Dest, SrcUrl), DestMime, true);
return;
}
catch (Exception CvtEx)
{
Log.WriteLine(" Converter error: {0}", CvtEx.Message);
SendError(502,