-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathProgram.cs
1322 lines (1208 loc) · 47.9 KB
/
Program.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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
namespace WebOne
{
public static class Program
{
public static LogWriter Log = new LogWriter();
private static HttpServer Server;
public const string ConfigFileAutoName = "**auto**webone.conf";
public static string CustomConfigFile = "";
public static string ConfigFileName = ConfigFileAutoName;
public static string OverrideLogFile = "";
public static int Port = -1;
public static int Load = 0;
public static string Protocols = "HTTP 1.1";
public static bool DaemonMode = false;
static bool ShutdownInitiated = false;
static bool RebuildCA = false;
const string CmdLineArgUnnamed = "--wo-short";
static List<KeyValuePair<string, string>> CmdLineOptions = new List<KeyValuePair<string, string>>();
public static System.Net.Http.SocketsHttpHandler HTTPHandler = new();
public static System.Net.Http.HttpClient HTTPClient = new(HTTPHandler);
public static string LocalIP = "127.0.0.1"; //localhost IP or detected external IP
private const string DefaultPACheader = "function FindProxyForURL(url, host){\n";
private const string DefaultPAChttp = "if (url.substring(0, 5) == 'http:')\n{ return 'PROXY %PACProxy%'; }\n";
private const string DefaultPAChttps = "if (url.substring(0, 6) == 'https:')\n{ return 'PROXY %PACProxy%'; }\n";
private const string DefaultPACftp = "if (url.substring(0, 4) == 'ftp:')\n{ return 'PROXY %PACProxy%'; }\n";
private const string DefaultPACfooter = "} /*WebOne PAC*/ ";
public static string DefaultPAC = DefaultPACheader + DefaultPAChttp + DefaultPACfooter;
private static bool DefaultPACoverriden = false;
public static X509Certificate2 RootCertificate;
public static Dictionary<string, X509Certificate2> FakeCertificates = new();
/// <summary>
/// The entry point of webone.dll (WebOne.exe, /usr/local/bin/webone, ./webone)
/// </summary>
/// <param name="args">Command line arguments of WebOne.exe</param>
static void Main(string[] args)
{
Variables.Add("WOVer",
Assembly.GetExecutingAssembly().GetName().Version.Major + "." +
Assembly.GetExecutingAssembly().GetName().Version.Minor + "." +
Assembly.GetExecutingAssembly().GetName().Version.Build
//+ "-pre"
);
Variables.Add("WOSystem", RuntimeInformation.OSDescription);
Console.Title = "WebOne";
Console.WriteLine("WebOne HTTP Proxy Server {0}\nhttps://github.com/atauenis/webone\n\n", Variables["WOVer"]);
//process command line arguments
ProcessCommandLine(args);
ConfigFileName = GetConfigurationFileName();
//load configuration file and set port number
try
{
ConfigFileLoader.LoadFile(ConfigFileName);
ConfigFileLoader.ProcessConfiguration();
if (Port < 1) Port = ConfigFile.Port; else ConfigFile.Port = Port;
}
catch (Exception ConfigLoadException)
{
Console.WriteLine("Error while loading configuration: {0}", ConfigLoadException.Message);
if (!DaemonMode) try
{
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
catch (InvalidOperationException) { /* prevent crash on non-interactive terminals */ }
Log.WriteLine(false, false, "WebOne has been exited due to lack of configuration.");
return;
}
//process remaining command line arguments and override configuration file options
ProcessCommandLineOptions();
//if log is not declared, say "Not using log file"
if (OverrideLogFile == null) LogAgent.OpenLogFile(null);
//check for --daemon mode
if (DaemonMode)
{
if (!LogAgent.IsLoggingEnabled)
{
Console.WriteLine("Error: log file is not available, please fix the problem. Exiting.");
return;
}
Console.Title = "WebOne (silent) @ " + ConfigFile.DefaultHostName + ":" + ConfigFile.Port;
Console.WriteLine("The proxy runs in daemon mode. See all messages in the log file.");
}
//initialize system HTTP socket message handler for static HttpClient used by HttpOperation class instances
HTTPHandler.SslOptions.RemoteCertificateValidationCallback = CheckServerCertificate;
HTTPHandler.AllowAutoRedirect = false;
HTTPHandler.AutomaticDecompression = ConfigFile.AllowHttpCompression ? DecompressionMethods.All : DecompressionMethods.None;
HTTPHandler.UseCookies = false;
if (ConfigFile.UpperProxy != "")
{
if (ConfigFile.UpperProxy == "no" || ConfigFile.UpperProxy == "off" || ConfigFile.UpperProxy == "disable" || ConfigFile.UpperProxy == "false" || ConfigFile.UpperProxy == "direct")
{
HTTPHandler.UseProxy = false;
}
else
{
WebProxy UpperProxy = new(ConfigFile.UpperProxy);
HTTPHandler.Proxy = UpperProxy;
}
}
HTTPHandler.EnableMultipleHttp2Connections = ConfigFile.MultipleHttp2Connections;
//set console window title
if (!DaemonMode) Console.Title = "WebOne @ " + ConfigFile.DefaultHostName + ":" + ConfigFile.Port;
//prepare PAC script if it's not set via configuration files
DefaultPACoverriden = ConfigFile.PAC != DefaultPAC;
if (!DefaultPACoverriden) { DefaultPAC = DefaultPACheader + DefaultPAChttp; }
if (ConfigFile.SslEnable)
{
//load or create & load SSL PEM (.crt & .key files) for CA (aka root certificate)
try
{
const int MinPemLentgh = 52; //minimum size of PEM files - header&footer only
bool HaveCrtKey = File.Exists(ConfigFile.SslCertificate) && File.Exists(ConfigFile.SslPrivateKey);
if (HaveCrtKey) HaveCrtKey = (new FileInfo(ConfigFile.SslCertificate).Length > MinPemLentgh) && (new FileInfo(ConfigFile.SslPrivateKey).Length > MinPemLentgh);
if (HaveCrtKey)
{ Log.WriteLine(false, false, "Using as SSL Certificate Authority: {0}, {1}.", ConfigFile.SslCertificate, ConfigFile.SslPrivateKey); }
else if (!RebuildCA)
{
CreateRootCertificate();
}
if (RebuildCA)
{
Console.WriteLine();
Log.WriteLine(true, false, "CA Certificate will be new, so import it to browser(s) after build succeeds.");
CreateRootCertificate();
RootCertificate = new X509Certificate2(X509Certificate2.CreateFromPemFile(ConfigFile.SslCertificate, ConfigFile.SslPrivateKey).Export(X509ContentType.Pkcs12));
Log.WriteLine(true, false, "The new certificate is called \"" + RootCertificate.GetNameInfo(X509NameType.SimpleName, false) + "\".");
Log.WriteLine(true, false, "WebOne will now exit.");
Environment.Exit(0);
}
try
{
RootCertificate = new X509Certificate2(X509Certificate2.CreateFromPemFile(ConfigFile.SslCertificate, ConfigFile.SslPrivateKey).Export(X509ContentType.Pkcs12));
Protocols += ", HTTPS 1.1";
if (!DefaultPACoverriden) DefaultPAC += DefaultPAChttps;
//check validness period
if (RootCertificate.NotAfter < DateTime.Now || RootCertificate.NotBefore > DateTime.Now)
{
Log.WriteLine(true, false, "Warning! CA Certificate is out of date: {0}-{1}, now {2}.", RootCertificate.NotBefore, RootCertificate.NotAfter, DateTime.Now);
}
if (RootCertificate.NotAfter < DateTimeOffset.Now.AddDays(ConfigFile.SslCertVaildAfterNow) ||
RootCertificate.NotBefore > DateTimeOffset.Now.AddDays(ConfigFile.SslCertVaildBeforeNow))
{
Log.WriteLine(true, false, "Warning! CA Certificate is too fresh or expires too soon. Check configuration.");
}
}
catch (Exception CertLoadEx)
{
if (CertLoadEx.InnerException != null)
{
Log.WriteLine(true, false, "Unable to load CA Certificate: {0}.", CertLoadEx.InnerException.Message);
}
else
{
Log.WriteLine(true, false, "Unable to load CA Certificate: {0}.", CertLoadEx.Message);
}
ConfigFile.SslEnable = false;
}
}
catch (Exception CertCreateEx)
{
Log.WriteLine(true, false, "Unable to create CA Certificate: {0}.", CertCreateEx.Message);
ConfigFile.SslEnable = false;
}
if (!string.IsNullOrWhiteSpace(ConfigFile.SslSiteCertGenerator) && string.IsNullOrWhiteSpace(ConfigFile.SslSiteCerts))
{
Log.WriteLine(true, false, "Warning: `SslSiteCertGenerator` is set but `SslSiteCerts` is not. Will use internal certificate generator.");
ConfigFile.SslSiteCertGenerator = "";
}
}
if (!ConfigFile.UseMsHttpApi)
{
Protocols += ", CERN-compatible";
if (!DefaultPACoverriden) DefaultPAC += DefaultPACftp;
}
else { ConfigFile.SslEnable = false; }
if (!DefaultPACoverriden) DefaultPAC += DefaultPACfooter;
if (!DefaultPACoverriden) ConfigFile.PAC = DefaultPAC;
Log.WriteLine(false, false, "Configured to http://{1}:{2}/, {3}", ConfigFileName, ConfigFile.DefaultHostName, ConfigFile.Port, Protocols);
//initialize server
try
{
if (ConfigFile.UseMsHttpApi)
Server = new HttpServer1(ConfigFile.Port);
else
Server = new HttpServer2(ConfigFile.Port);
}
catch (Exception ex)
{
Log.WriteLine(true, false, "Server initialize failed: {0}", ex.Message);
Shutdown(ex.HResult);
return;
}
//start the server from 1 or 2 attempts
for (int StartAttempts = 0; StartAttempts < 2; StartAttempts++)
{
try
{
//Log.WriteLine(true, false, "Starting servers...");
Server.Start();
//Log.WriteLine(true, false, "Ready for incoming connections.");
Log.WriteLine(true, false, "Listening for HTTP 1.x on port {0}.", Port);
break;
}
catch (HttpListenerException ex)
{
Log.WriteLine(true, false, "Cannot start server: {0}", ex.Message);
if (!DaemonMode && ex.NativeErrorCode == 5)
{
//access (for listen TCP port) denied, show troubleshooting help
if (ex.NativeErrorCode == 5 && Environment.OSVersion.Platform == PlatformID.Unix) //access denied @ *nix
{
Console.WriteLine();
Console.WriteLine(@"You need to use ""sudo WebOne"" or use Port greater than 1024.");
Shutdown(ex.NativeErrorCode);
break;
}
if (ex.NativeErrorCode == 5 && Environment.OSVersion.Platform == PlatformID.Win32NT && StartAttempts == 0) //access denied @ Win32
{
Console.WriteLine();
Console.WriteLine("Seems that Windows has been blocked running WebOne with non-admin rights.");
Console.WriteLine("Read more in project's wiki:");
Console.WriteLine("https://github.com/atauenis/webone/wiki/Windows-installation#how-to-run-without-admin-privileges");
Console.Write("Do you want to add a Windows Network Shell rule to run WebOne with user rights? (Y/N)");
if (Console.ReadKey().Key == ConsoleKey.Y)
{
ConfigureWindowsNetShell(Port);
continue;
}
else
{
Console.WriteLine("\nYou always can configure the system using instructions from WebOne wiki.");
Shutdown(ex.NativeErrorCode);
break;
}
}
}
Shutdown(ex.NativeErrorCode);
break;
}
catch (Exception ex)
{
Log.WriteLine(true, false, "Server start failed: {0}", ex.Message);
Shutdown(ex.HResult);
break;
}
}
//register Ctrl+C/kill handler
System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (ctx) => { Shutdown(); };
Console.CancelKeyPress += (s, e) => { Shutdown(); };
//wait while server is in work
while (Server.Working) { Thread.Sleep(250); }
//the end
Shutdown();
}
/// <summary>
/// Create certificate and private key files for WebOne Certificate Authority
/// </summary>
private static void CreateRootCertificate()
{
Log.WriteLine(true, false, "Creating root SSL Certificate & Private Key for CA...");
CertificateUtil.MakeSelfSignedCert(ConfigFile.SslCertificate, ConfigFile.SslPrivateKey, ConfigFile.SslRootSubject, ConfigFile.SslHashAlgorithm);
Log.WriteLine(true, false, "CA Certificate: {0}; Key: {1}.", ConfigFile.SslCertificate, ConfigFile.SslPrivateKey);
}
/// <summary>
/// Shut down server and terminate process
/// </summary>
/// <param name="Code">Process exit code</param>
public static void Shutdown(int Code = 0)
{
if (ShutdownInitiated) return;
ShutdownInitiated = true;
if (Server != null && Server.Working) Server.Stop();
if (!DaemonMode && !Environment.HasShutdownStarted && !ShutdownInitiated) try
{
Console.WriteLine("\nPress any key to exit.");
Console.ReadKey();
}
catch (InvalidOperationException) { /* prevent crash on non-interactive terminals */ }
Log.WriteLine(false, false, "WebOne has been exited.");
Environment.ExitCode = Code;
new Task(() => { Environment.Exit(Code); }).Start();
Process.GetCurrentProcess().Kill();
}
/// <summary>
/// Process command line arguments
/// </summary>
/// <param name="args">Array of WebOne.exe startup arguments</param>
private static void ProcessCommandLine(string[] args)
{
string ArgName = CmdLineArgUnnamed;
string ArgValue = "";
List<KeyValuePair<string, string>> Args = new List<KeyValuePair<string, string>>();
KeyValuePair<string, string> LastArg = new KeyValuePair<string, string>();
bool LastWasValue = false;
foreach (string arg in args)
{
if (arg.StartsWith("-") || (Environment.OSVersion.Platform == PlatformID.Win32NT && arg.StartsWith("/")))
{
LastWasValue = false;
LastArg = new KeyValuePair<string, string>(ArgName, ArgValue);
Args.Add(LastArg);
ArgName = arg;
ArgValue = "";
continue;
}
else
{
if (LastWasValue)
{
LastArg = new KeyValuePair<string, string>(ArgName, ArgValue);
Args.Add(LastArg);
}
ArgValue = arg;
LastWasValue = true;
continue;
}
}
LastArg = new KeyValuePair<string, string>(ArgName, ArgValue);
Args.Add(LastArg);
foreach (KeyValuePair<string, string> kvp in Args)
{
CmdLineOptions.Add(kvp);
// Console.WriteLine("Arg: '{0}' = '{1}'", kvp.Key, kvp.Value);
switch (kvp.Key)
{
case "/cfg":
case "-cfg":
case "-config":
CustomConfigFile = ExpandMaskedVariables(kvp.Value);
break;
case "/l":
case "-l":
case "--log":
if (kvp.Value == "" || kvp.Value == "no") { OverrideLogFile = null; break; }
OverrideLogFile = ExpandMaskedVariables(kvp.Value);
LogAgent.OpenLogFile(OverrideLogFile);
break;
case "/t":
case "-t":
case "--tmp":
case "--temp":
case "/p":
case "-p":
case "--port":
case "--http-port":
case "/h":
case "-h":
case "--host":
case "--hostname":
case "/a":
case "-a":
case "--proxy-authenticate":
case "--dump":
case "--dump-headers":
case "--dump-requests":
//all will be processed in ProcessCommandLineOptions()
break;
case "--rebuild-ca":
RebuildCA = true;
break;
case "--daemon":
DaemonMode = true;
break;
case "--help":
case "-?":
case "/?":
Console.WriteLine("All command line arguments can be found in WebOne Wiki:");
Console.WriteLine("https://github.com/atauenis/webone/wiki");
Console.WriteLine();
Console.WriteLine("Initially made by Alexander Tauenis. Moscow, Russian Federation.");
Environment.Exit(0);
break;
case CmdLineArgUnnamed:
if (string.IsNullOrWhiteSpace(kvp.Value)) break;
if (int.TryParse(kvp.Value, out int CustomPort))
{
Port = CustomPort;
Console.WriteLine("Using custom port {0}.", Port);
break;
}
CustomConfigFile = kvp.Value;
break;
default:
Console.WriteLine("Unknown command line argument: {0}.", kvp.Key);
break;
}
}
}
/// <summary>
/// Get an character <see cref="System.Text.Encoding"/> from code page number or alias.
/// </summary>
/// <param name="CP">Code page number.</param>
internal static Encoding GetCodePage(string CP)
{
switch (CP.ToLower())
{
case "windows":
case "win":
case "ansi":
return CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ANSICodePage);
/* Microsoft Windows code pages:
* windows-1250 Czech, Polish, Slovak, Hungarian, Slovene, Serbo-Croatian, Montenegrian, Romanian (<1993), Gagauz, Rotokas, Albanian, English, German, Luxembourgish
* windows-1251 Russian, Ukrainian, Belarusian, Bulgarian, Serbian Cyrillic, Bosnian Cyrillic, Macedonian, Rusyn
* windows-1252 (All of ISO-8859-1 plus full support for French and Finnish)
* windows-1253 Greek
* windows-1254 Turkish
* windows-1255 Hebrew
* windows-1256 Arabic
* windows-1257 Estonian, Latvian, Lithuanian, Latgalian
* windows-1258 Vietnamese
* windows-874 Thai
*/
case "dos":
case "oem":
case "ascii":
return CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
/* MS-DOS, IBM OS/2 code pages:
* 437 Default: English, German, Swedish
* 720 Arabic in Egypt, Iraq, Jordan, Saudi Arabia, and Syria
* 737 Greek
* 775 Estonian, Lithuanian and Latvian
* 850 West European: at least Spanish, Italian, French
* 852 Bosnian, Croatian, Czech, Hungarian, Polish, Romanian, Moldavian, Serbian, Slovak or Slovene
* 855 Serbian, Macedonian and Bulgarian
* 857 Turkish
* 860 Portuguese (mostly - Brasilian)
* 861 Icelandic
* 862 Hebrew
* 863 French in Canada (mainly in Quebec province)
* 864 Arabic in Egypt, Iraq, Jordan, Saudi Arabia, and Syria (?)
* 865 Danish and Norwegian
* 866 Russian, Ukrainian, Byelarussian
* 874 Thai
* 932 Japan
* 936 Chinese simplified (PRC)
* 949 Korean
* 950 Chinese traditional (Taiwan island)
*/
case "mac":
case "apple":
return CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.MacCodePage);
/* Apple MacOS (Classic) code pages:
* macintosh (Latin default)
* x-mac-arabic
* x-mac-ce (Czech, Slovak, Polish, Estonian, Latvian, Lithuanian)
* x-mac-chinesetrad (Taiwan island)
* x-mac-croatian
* x-mac-cyrillic (Russian, Bulgarian, Belarusian, Macedonian, Serbian)
* x-mac-greek
* x-mac-hebrew
* x-mac-icelandic
* x-mac-japanese
* x-mac-romanian (Romanian & Moldavian)
* x-mac-thai
* x-mac-turkish
* x-mac-ukrainian
*/
case "ebcdic":
case "ibm":
/* Old IBM mainframes (EBCDIC) code pages:
* ---== To be written ==---
*/
return CodePagesEncodingProvider.Instance.GetEncoding(System.Globalization.CultureInfo.CurrentCulture.TextInfo.EBCDICCodePage);
case "iso":
case "iso-8859":
case "iso8859":
CultureInfo ci = CultureInfo.CurrentCulture;
switch (ci.TwoLetterISOLanguageName.ToLower())
{
default:
/*
* ISO-8859-1 = Latin-1 (Western European)
* English, Faeroese, German, Icelandic, Irish, Italian, Norwegian, Portuguese, Rhaeto-Romanic, Scottish Gaelic, Spanish, Catalan, and Swedish
* Danish (partial), Dutch (partial), Finnish (partial), French (partial)
* Not supported on some macOS servers! To skip NULL return, use CP1252, which is 75% same as Latin-1.
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-1") ?? CodePagesEncodingProvider.Instance.GetEncoding("windows-1252");
case "bs":
case "pl":
case "cr":
case "cz":
case "sk":
case "sl":
//case "sr":
case "hu":
/*
* ISO-8859-2 = Latin-2 (Central European)
* Bosnian, Polish, Croatian, Czech, Slovak, Slovene, Serbian Latin, and Hungarian
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-2");
case "mt":
case "eo":
/*
* ISO-8859-3 = Latin-3 (South European)
* Maltese and Esperanto
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-3");
case "kl":
case "se":
/*
* ISO-8859-4 = Latin-4 (North European)
* Greenlandic, and Sami
* Sometimes also Estonian, Latvian, Lithuanian
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-4");
case "be":
case "bu":
case "mk":
case "ru":
case "sr":
case "ua":
/*
* ISO-8859-5 = Cyrillic
* Belarusian, Bulgarian, Macedonian, Russian, Serbian Cyrillic, and Ukrainian (partial)
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-5");
case "ar":
/*
* ISO-8859-6 = Arabic
* Arabic language
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-6");
case "gr":
/*
* ISO-8859-7 = Greek
* Modern Greek, Ancient Greek
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-7");
case "hw":
/*
* ISO-8859-8 = Hebrew
* Hebrew
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-8");
case "tr":
/*
* ISO-8859-9 = Latin-9 (Turkish)
* Turkish
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-9");
//case "es":
case "lv":
case "lt":
/*
* ISO-8859-13 - Latin-7 (Baltic Rim)
* Estonian, Latvian and Lithuanian
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-13");
case "fr":
case "fi":
case "es":
/*
* ISO-8859-15 - Latin-9 / Latin-0
* French, Finnish and Estonian.
*/
return CodePagesEncodingProvider.Instance.GetEncoding("iso-8859-15");
/*
* ISO-8859 parts # 10, 11, 12, 14, 16 are not supported by .NET 6.0:
* 10 - Latin-6 (Nordic)
* 11 - Thai
* 12 - Devanagari
* 14 - Latin-8 (Celtic)
* 16 - Latin-10 (South-Eastern)
*/
}
case "0":
case "asis":
return null;
default:
//parse from specified number or name
try
{
Encoding enc = CodePagesEncodingProvider.Instance.GetEncoding(CP);
if (enc == null)
try { return CodePagesEncodingProvider.Instance.GetEncoding(int.Parse(CP)); } catch { }
else return enc;
if (enc == null && CP.ToLower().StartsWith("utf"))
{
switch (CP.ToLower())
{
case "utf-7":
#pragma warning disable SYSLIB0001 // The UTF-7 encoding is insecure since .NET 5.0
return Encoding.UTF7;
#pragma warning restore SYSLIB0001
case "utf-8":
return Encoding.UTF8;
case "utf-16":
case "utf-16le":
return Encoding.Unicode;
case "utf-16be":
return Encoding.BigEndianUnicode;
case "utf-32":
case "utf-32le":
return Encoding.UTF32;
}
}
Log.WriteLine(true, false, "Warning: Unknown codepage {0}, using AsIs. See MSDN 'Encoding.GetEncodings Method' article for list of valid encodings.", CP);
return null;
}
catch (ArgumentException)
{
Log.WriteLine(true, false, "Warning: Bad codepage {0}, using {1}. Get list of available encodings at http://{2}:{3}/!codepages/.", CP, ConfigFile.OutputEncoding.EncodingName, ConfigFile.DefaultHostName, ConfigFile.Port);
return null;
}
}
}
/// <summary>
/// Process command line options that overrides webone.conf
/// </summary>
private static void ProcessCommandLineOptions()
{
foreach (KeyValuePair<string, string> kvp in CmdLineOptions)
{
try
{
//Console.WriteLine("Opt: '{0}' = '{1}'", kvp.Key, kvp.Value);
switch (kvp.Key)
{
case "/t":
case "-t":
case "--tmp":
case "--temp":
ConfigFile.TemporaryDirectory = ExpandMaskedVariables(kvp.Value);
break;
case "/p":
case "-p":
case "--port":
case "--http-port":
case "--https-port":
case "--ftp-port":
Port = Convert.ToInt32(kvp.Value);
ConfigFile.Port = Convert.ToInt32(kvp.Value);
break;
case "/h":
case "-h":
case "--host":
case "--hostname":
ConfigFile.DefaultHostName = kvp.Value;
break;
case "/a":
case "-a":
case "--proxy-authenticate":
ConfigFile.Authenticate = new List<string>() { kvp.Value }; //will override all set credentials
break;
case "--dump":
case "--dump-headers":
case "--dump-requests":
string DumpFilePath = "dump-%Url%.log";
if (kvp.Value != "") DumpFilePath = kvp.Value;
Log.WriteLine(true, false, "Will save all HTTP traffic to: {0}.", DumpFilePath);
ConfigFileSection DumpSection = new ConfigFileSection("[Edit]", "[command line]");
DumpSection.Options.Add(new ConfigFileOption("AddDumping=" + DumpFilePath, "[command line]"));
ConfigFile.EditRules.Add(new EditSet(DumpSection));
break;
}
}
catch (Exception ex)
{
Console.WriteLine("Warning: Wrong argument '{1} {2}': {0}.", ex.Message, kvp.Key, kvp.Value);
}
}
}
/// <summary>
/// Make info string (footer) for message pages
/// </summary>
/// <returns>HTML: WebOne vX.Y.Z on Windows NT 6.2.9200 Service Pack 6</returns>
public static string GetInfoString()
{
return "<hr>WebOne Proxy Server " + Variables["WOVer"] + "<br>on " + Variables["WOSystem"];
}
/// <summary>
/// Check a string for containing a something from list of patterns
/// </summary>
/// <param name="What">What string should be checked</param>
/// <param name="For">Pattern to find</param>
/// <param name="CaseInsensitive">Ignore character case when checking</param>
public static bool CheckString(string What, string[] For, bool CaseInsensitive = false)
{
if (CaseInsensitive)
{
foreach (string str in For) { if (What.Contains(str, StringComparison.InvariantCultureIgnoreCase)) return true; }
return false;
}
else
{
foreach (string str in For) { if (What.Contains(str)) return true; }
return false;
}
}
/// <summary>
/// Check a string for containing a something from list of patterns
/// </summary>
/// <param name="What">What string should be checked</param>
/// <param name="For">Pattern to find</param>
/// <param name="CaseInsensitive">Ignore character case when checking</param>
public static bool CheckString(string What, List<string> For, bool CaseInsensitive = false)
{
return CheckString(What, For.ToArray(), CaseInsensitive);
}
/// <summary>
/// Check a string array for containing a pattern
/// </summary>
/// <param name="Where">Where the search should be do</param>
/// <param name="For">Pattern to find</param>
/// <param name="CaseInsensitive">Ignore character case when checking</param>
public static bool CheckString(string[] Where, string For, bool CaseInsensitive = false)
{
if (CaseInsensitive)
{
foreach (string str in Where) { if (str.Contains(For, StringComparison.InvariantCultureIgnoreCase)) return true; }
return false;
}
else
{
foreach (string str in Where) { if (str.Contains(For)) return true; }
return false;
}
}
/// <summary>
/// Check a string for containing a something from list of RegExp patterns
/// </summary>
/// <param name="What">What string should be checked</param>
/// <param name="For">Pattern to find</param>
public static bool CheckStringRegExp(string What, string[] For)
{
foreach (string str in For) { if (System.Text.RegularExpressions.Regex.IsMatch(What, str)) return true; }
return false;
}
/// <summary>
/// Check a string array for containing a RegExp pattern
/// </summary>
/// <param name="Where">Where the search should be do</param>
/// <param name="For">Pattern to find</param>
public static bool CheckStringRegExp(string[] Where, string For)
{
foreach (string str in Where) { if (System.Text.RegularExpressions.Regex.IsMatch(str, For)) return true; }
return false;
}
/// <summary>
/// Make a string with timestamp
/// </summary>
/// <param name="BeginTime">Initial time</param>
/// <returns>The initial time and difference with the current time</returns>
public static string GetTime(DateTime BeginTime)
{
TimeSpan difference = DateTime.Now - BeginTime;
return BeginTime.ToString("dd.MM.yyyy HH:mm:ss.fff") + "+" + difference.Ticks / 2;
}
/// Read all bytes from a Stream (like StreamReader.ReadToEnd)
/// </summary>
/// <param name="stream">Source Stream</param>
/// <returns>All bytes of it</returns>
public static byte[] ReadAllBytes(Stream stream)
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
/// <summary>
/// Get CPU load for process.
/// </summary>
/// <param name="process">The process.</param>
/// <returns>CPU usage in percents.</returns>
internal static double GetUsage(Process process)
{
//thx to: https://stackoverflow.com/a/49064915/7600726
//see also https://www.mono-project.com/archived/mono_performance_counters/
if (process.HasExited) return double.MinValue;
// Preparing variable for application instance name
string name = "";
foreach (string instance in new PerformanceCounterCategory("Process").GetInstanceNames())
{
if (process.HasExited) return double.MinValue;
if (instance.StartsWith(process.ProcessName))
{
using (PerformanceCounter processId = new PerformanceCounter("Process", "ID Process", instance, true))
{
if (process.Id == (int)processId.RawValue)
{
name = instance;
break;
}
}
}
}
PerformanceCounter cpu = new PerformanceCounter("Process", "% Processor Time", name, true);
// Getting first initial values
cpu.NextValue();
// Creating delay to get correct values of CPU usage during next query
Thread.Sleep(500);
if (process.HasExited) return double.MinValue;
return Math.Round(cpu.NextValue() / Environment.ProcessorCount, 2);
}
/// <summary>
/// Check a process for idle state (long period of no CPU load) and kill if it's idle.
/// </summary>
/// <param name="Proc">The process.</param>
/// <param name="AverageLoad">Average CPU load by the process.</param>
internal static void PreventProcessIdle(ref Process Proc, ref float AverageLoad, LogWriter Log)
{
AverageLoad = (float)(AverageLoad + GetUsage(Proc)) / 2;
if (!Proc.HasExited)
if (Math.Round(AverageLoad, 6) <= 0 && !Proc.HasExited)
{
//the process is counting crows. Fire!
Proc.Kill();
if (Console.GetCursorPosition().Left > 0) Console.WriteLine();
Log.WriteLine(" Idle process {0} killed.", Proc.ProcessName);
}
}
/// <summary>
/// Fill %masks% on an URI template
/// </summary>
/// <param name="MaskedURL">URI template</param>
/// <param name="PossibleURL">Previous URI (for "%URL%" mask and similar)</param>
/// <param name="DontTouchURL">Do not edit previous URI (%URL% mask) in any cases</param>
/// <param name="AdditionalVariables">Additional %masks% which can be processed</param>
/// <returns>Ready URL</returns>
public static string ProcessUriMasks(string MaskedURL, string PossibleURL = "http://webone.github.io:80/index.htm", bool DontTouchURL = false, Dictionary<string, string> AdditionalVariables = null)
{
//this function should be rewritten or removed in future,
//when will implement more powerful manipulation of headers, cookies, content. (v0.12?)
string str = MaskedURL;
string URL = null;
if (CheckString(PossibleURL, ConfigFile.ForceHttps) && !DontTouchURL)
URL = new UriBuilder(PossibleURL) { Scheme = "https" }.Uri.ToString();
else
URL = PossibleURL;
UriBuilder builder = new UriBuilder(URL);
var UrlVars = new Dictionary<string, string>
{
{ "URL", URL },
{ "Url", Uri.EscapeDataString(URL) },
{ "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) }
};
if (AdditionalVariables != null) foreach (var entry in AdditionalVariables) { UrlVars.TryAdd(entry.Key, entry.Value); }
str = ExpandMaskedVariables(str, UrlVars);
return str;
}
/// <summary>
/// Internal variables which can be used in strings
/// </summary>
public static Dictionary<string, string> Variables = new Dictionary<string, string>();
/// <summary>
/// Replace all environment/WebOne variable %masks% ($masks) in a string with their real values
/// </summary>
/// <param name="MaskedString">A string with some %masks% inside</param>
/// <param name="AdditionalVariables">Additional variables, which also can be used in masked string</param>
/// <returns>A string with real variable values</returns>
public static string ExpandMaskedVariables(string MaskedString, Dictionary<string, string> AdditionalVariables = null)
{
//Workaround for https://github.com/dotnet/runtime/issues/25792
//So this is a better version of Environment.ExpandEnvironmentVariables(String)
//where both UNIX ($EnvVar) and DOS (%EnvVar%) syntaxes are allowed, and %TEMP% and $TMPDIR are synonyms.
//Also any WebOne internal variables can be used here.
string str = MaskedString, tempdir = Path.GetTempPath(), logdir = GetDefaultLogDirectory();
str = str.Replace("$TMPDIR", tempdir).Replace("%TEMP%", tempdir, StringComparison.CurrentCultureIgnoreCase);
str = str.Replace("$SYSLOGDIR", logdir).Replace("%SYSLOGDIR%", logdir, StringComparison.CurrentCultureIgnoreCase);
//get custom variables (e.g. HTTP headers, etc)
Dictionary<string, string> AddVars = new Dictionary<string, string>(Variables);
if (AdditionalVariables != null) foreach (var entry in AdditionalVariables) { AddVars.TryAdd(entry.Key, entry.Value); }
foreach (KeyValuePair<string, string> Var in AddVars)
{
str = str
.Replace("%" + (string)Var.Key + "%", (string)Var.Value)
.Replace("$" + (string)Var.Key, (string)Var.Value);
}
//get environment variables and home directory
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
foreach (System.Collections.DictionaryEntry EnvVar in Environment.GetEnvironmentVariables())
{
str = str
.Replace("%" + (string)EnvVar.Key + "%", (string)EnvVar.Value, StringComparison.CurrentCultureIgnoreCase)
.Replace("$" + (string)EnvVar.Key, (string)EnvVar.Value);
}
str = str.Replace("~/", Environment.SpecialFolder.UserProfile + "/");
}
else
{
str = Environment.ExpandEnvironmentVariables(str);
}
return str;
}
/// <summary>
/// Get user-agent string for a request
/// </summary>
/// <param name="ClientUA">Client's user-agent</param>
/// <returns>Something like "Mozilla/3.04Gold (U; Windows NT 3.51) WebOne/1.0.0.0 (Unix)"</returns>
public static string GetUserAgent(string ClientUA = "")
{
return ExpandMaskedVariables(ConfigFile.UserAgent, new Dictionary<string, string> { { "Original", ClientUA ?? "Mozilla/5.0 (Kundryuchy-Leshoz)" } });
}
/// <summary>
/// Get all server IP addresses
/// </summary>
/// <returns>All IPv4/IPv6 addresses of this machine</returns>