-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathProgram.cs
203 lines (167 loc) · 5.96 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
namespace HttpReverseProxy
{
using Fclp;
using HttpReverseProxyLib.DataTypes.Enum;
using System;
using System.IO;
using System.Net.NetworkInformation;
using System.Security.Cryptography.X509Certificates;
public class Program
{
#region PUBLIC METHODS
/// <summary>
///
/// </summary>
/// <param name="args"></param>
public static void Main(string[] args)
{
var certificateHost = string.Empty;
var parser = new FluentCommandLineParser();
parser.IsCaseSensitive = false;
parser.Setup<string>("createCertificate")
.Callback(item => { certificateHost = item; })
.WithDescription("Create selfsigned certificate for HOSTNAME");
parser.Setup<int>("httpPort")
.Callback(item => { Config.LocalHttpServerPort = item; })
.SetDefault(80)
.WithDescription("Define TCP port for incoming HTTP requests. Default port is \"80\"");
parser.Setup<int>("httpsPort")
.Callback(item => { Config.LocalHttpsServerPort = item; })
.SetDefault(443)
.WithDescription("Define TCP port for incoming HTTPS requests. Default port is \"443\"");
parser.Setup<string>("certificate")
.Callback(item => { Config.CertificatePath = item; })
.WithDescription("Define certificate file path");
parser.Setup<Loglevel>("loglevel")
.Callback(item => Config.CurrentLoglevel = item)
.SetDefault(Loglevel.Info)
.WithDescription("Define log level. Default level is \"Info\". Possible values are: " + string.Join(", ", Enum.GetNames(typeof(Loglevel))));
// sets up the parser to execute the callback when -? or --help is detected
parser.SetupHelp("?", "help")
.UseForEmptyArgs()
.Callback(text => Console.WriteLine(text));
ICommandLineParserResult result = parser.Parse(args);
if (result.HasErrors == true)
{
Console.WriteLine("{0}\r\n\r\n", result.ErrorText);
}
else if (!string.IsNullOrEmpty(certificateHost) &&
!string.IsNullOrWhiteSpace(certificateHost))
{
Lib.CertificateHandler.Inst.CreateCertificate(certificateHost);
}
else if (string.IsNullOrEmpty(Config.CertificatePath))
{
Console.WriteLine("You did not define a certificate file");
}
else
{
StartProxyServer();
}
}
// For the sake of testability this method remains public.
public static void StartProxyServer()
{
Config.LocalIp = Lib.Common.GetLocalIpAddress();
HttpReverseProxyLib.Logging.Instance.CurrentLoggingLevel = Config.CurrentLoglevel;
HttpReverseProxyLib.Logging.Instance.LogMessage("Main", ProxyProtocol.Undefined, Loglevel.Info, "StartProxyServer(): Current loglevel= {0}", Config.CurrentLoglevel.ToString());
// Parse HTTP port parameter
try
{
if (IsPortAvailable(Config.LocalHttpServerPort) == false)
{
Console.WriteLine("The HTTP port ({0}) is used by another proces", Config.LocalHttpServerPort);
return;
}
// Initialize TLS/SSL parameters for HTTPS connections
if (IsPortAvailable(Config.LocalHttpsServerPort) == false)
{
Console.WriteLine("The HTTPS port ({0}) is used by another proces", Config.LocalHttpsServerPort);
return;
}
// Check if certificate is valid
if (VerifyCertificateValidity(Config.CertificatePath) == false)
{
Console.WriteLine("The certificate \"{0}\" is invalid", Config.CertificatePath);
return;
}
}
catch (Exception ex)
{
Console.WriteLine("Exception occurred: {0}", ex.Message);
return;
}
// Start HTTP proxy server
try
{
if (HttpReverseProxy.Server.Start(Config.LocalHttpServerPort) == false)
{
throw new Exception("HTTP reverse proxy server could not be started");
}
if (HttpsReverseProxy.Server.Start(Config.LocalHttpsServerPort, Config.CertificatePath) == false)
{
throw new Exception("HTTPS reverse proxy server could nor be started");
}
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Something went wrong: {0}", ex.ToString());
}
HttpReverseProxy.Server.Stop();
HttpsReverseProxy.Server.Stop();
}
#endregion
#region PRIVATE
private static bool VerifyCertificateValidity(string certificateFilePath)
{
if (string.IsNullOrEmpty(certificateFilePath))
{
throw new Exception("The certificate file parameter is invalid");
}
if (!File.Exists(certificateFilePath))
{
throw new Exception("The certificate file does not exist");
}
X509Certificate2Collection collection = new X509Certificate2Collection();
try
{
collection.Import(certificateFilePath, string.Empty, X509KeyStorageFlags.PersistKeySet);
}
catch (Exception ex)
{
throw new Exception($"The following error occurred while loading certificate file: {ex.Message}");
}
if (collection.Count < 1)
{
throw new Exception("No valid certificate data found");
}
if (collection.Count > 1)
{
throw new Exception("No valid certificate data found");
}
return true;
}
private static bool IsPortAvailable(int portNo)
{
if (portNo <= 0 || portNo > 65535)
{
throw new Exception("The port is invalid");
}
bool isPortAvailable = true;
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
System.Net.IPEndPoint[] ipEndPoints = ipGlobalProperties.GetActiveTcpListeners();
foreach (System.Net.IPEndPoint endPoint in ipEndPoints)
{
if (endPoint.Port == portNo)
{
isPortAvailable = false;
break;
}
}
return isPortAvailable;
}
#endregion
}
}