-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
337 lines (285 loc) · 12.9 KB
/
Copy pathProgram.cs
File metadata and controls
337 lines (285 loc) · 12.9 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
/*
MIT License
Copyright (c) 2025 Martin Fredriksson
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
using System.IO.Compression;
using System.Net;
using System.Net.Http.Headers;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Text;
// Not available in args[0], due to top-level statements...
var programName = Path.GetFileNameWithoutExtension(Environment.GetCommandLineArgs()[0]);
if (args.Contains("--version", StringComparer.OrdinalIgnoreCase))
{
var version = Assembly.GetExecutingAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "unknown";
Console.WriteLine($"{programName} version {version}");
return;
}
if (args.Contains("--help", StringComparer.OrdinalIgnoreCase) || args.Contains("-h"))
{
Console.WriteLine($"\nUsage: {programName} <localUrl> <targetUrl> <certSubject> [options]\n");
Console.WriteLine("Options:");
Console.WriteLine(" --preserve-encoding Preserve incoming encoding when forwarding (default: UTF-8)");
Console.WriteLine(" --log-body=false Disable body logging");
Console.WriteLine(" --version Print version info");
Console.WriteLine(" --help, -h Show this help message\n");
Console.WriteLine("Ctrl+L to clear the console.\n");
Console.WriteLine("Ctrl+C to stop the proxy.\n");
return;
}
// ==== Logging target ====
var logPath = Path.Combine(
OperatingSystem.IsWindows()
? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
: Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + "/.local/share",
programName,
"proxy.log"
);
Directory.CreateDirectory(Path.GetDirectoryName(logPath)!);
// ==== Argument handling ====
if (args.Length < 3)
{
Console.WriteLine($"Usage: {programName} <localUrl> <targetUrl> <certSubject> [--preserve-encoding] [--log-body=false]");
return;
}
var localUrl = args[0];
var targetUrl = args[1];
var certSubject = args[2];
if (!Uri.TryCreate(localUrl, UriKind.Absolute, out var localUri) || (localUri.Scheme != Uri.UriSchemeHttp && localUri.Scheme != Uri.UriSchemeHttps))
{
Console.WriteLine("[ERROR] Invalid localUrl. It must be a valid HTTP or HTTPS URL.");
return;
}
if (!Uri.TryCreate(targetUrl, UriKind.Absolute, out var targetUri) || (targetUri.Scheme != Uri.UriSchemeHttp && targetUri.Scheme != Uri.UriSchemeHttps))
{
Console.WriteLine("[ERROR] Invalid targetUrl. It must be a valid HTTP or HTTPS URL.");
return;
}
if (string.IsNullOrWhiteSpace(certSubject))
{
Console.WriteLine("[ERROR] Invalid certSubject. It cannot be null or empty.");
return;
}
var preserveEncoding = args.Contains("--preserve-encoding", StringComparer.OrdinalIgnoreCase);
var logBody = !args.Contains("--log-body=false", StringComparer.OrdinalIgnoreCase);
Log($"Listen on: {localUrl}");
Log($"Forward to: {targetUrl}");
Log($"Client certificate: {certSubject}");
Log($"Preserve encoding forward: {(preserveEncoding ? "YES" : "NO (UTF-8 used)")}");
Log($"Log to: {logPath}");
var clientCert = FindCertificate(certSubject);
if (clientCert == null)
{
Log("[ERROR] Certificate not found.");
return;
}
Log($"[OK] Client certificate found: {clientCert.Subject}");
// ==== Cancellation Token Setup ====
var cts = new CancellationTokenSource();
var cancellationToken = cts.Token;
// Handle Ctrl+C or SIGTERM
Console.CancelKeyPress += (_, e) =>
{
Log("[INFO] Shutdown signal received. Stopping...");
cts.Cancel();
e.Cancel = true; // Prevent immediate termination
};
_ = Task.Run(async () =>
{
while (!cts.Token.IsCancellationRequested)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true);
if (key is { Modifiers: ConsoleModifiers.Control, Key: ConsoleKey.L })
{
Console.Clear();
Log("[INFO] Console cleared via Ctrl+L");
}
}
await Task.Delay(100, cts.Token); // CPU-snål väntan
}
});
// ==== HTTP och proxy ====
var listener = new HttpListener();
listener.Prefixes.Add(localUrl);
listener.Start();
Log($"[OK] HttpListener started on {localUrl}");
var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCert);
handler.ServerCertificateCustomValidationCallback = (_, _, _, _) => true;
var httpClient = new HttpClient(handler);
try
{
while (!cancellationToken.IsCancellationRequested)
{
HttpListenerContext? context = null;
try
{
var getContextTask = listener.GetContextAsync(); // Blocking call, do not await
var completedTask = await Task.WhenAny(getContextTask, Task.Delay(Timeout.Infinite, cancellationToken));
if (completedTask == getContextTask) context = getContextTask.Result;
else break; // Cancellation requested
_ = Task.Run(async () =>
{
try
{
var request = context.Request;
var clientEncoding = request.ContentEncoding;
var forwardEncoding = preserveEncoding ? clientEncoding : Encoding.UTF8;
var forwardUriBase = new Uri(targetUrl);
var finalTarget = new Uri(forwardUriBase, request.RawUrl);
var forwardRequest = new HttpRequestMessage(new HttpMethod(request.HttpMethod), finalTarget);
Log($">>> Client request: {request.HttpMethod} {request.Url}");
Log($">>> Client encoding: {clientEncoding.WebName}");
Log($">>> Forward request: {forwardRequest.Method} {forwardRequest.RequestUri!.AbsoluteUri}");
Log($">>> Forward encoding: {forwardEncoding.WebName}");
Log($">>> Headers ({request.Headers.Count}):");
foreach (string header in request.Headers)
Log($">>> {header}: {request.Headers[header]}");
foreach (string header in request.Headers)
{
if (!WebHeaderCollection.IsRestricted(header) &&
!string.Equals(header, "Content-Length", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(header, "Host", StringComparison.OrdinalIgnoreCase))
{
forwardRequest.Headers.TryAddWithoutValidation(header, request.Headers[header]);
}
}
if (logBody)
{
using var reader = new StreamReader(request.InputStream, clientEncoding);
var requestBody = await reader.ReadToEndAsync();
Log($">>> Body:\n\n{requestBody}\n");
var forwardBytes = forwardEncoding.GetBytes(requestBody);
forwardRequest.Content = new ByteArrayContent(forwardBytes);
forwardRequest.Content.Headers.ContentType =
MediaTypeHeaderValue.Parse(request.ContentType ?? "application/octet-stream");
forwardRequest.Content.Headers.ContentType.CharSet = forwardEncoding.WebName;
}
else
{
forwardRequest.Content = new StreamContent(request.InputStream);
forwardRequest.Content.Headers.ContentType =
MediaTypeHeaderValue.Parse(request.ContentType ?? "application/octet-stream");
}
HttpResponseMessage response;
try
{
response = await httpClient.SendAsync(forwardRequest, HttpCompletionOption.ResponseHeadersRead);
}
catch (HttpRequestException ex)
{
Log($"[ERROR] Failed to forward request: {ex.Message}");
context.Response.StatusCode = (int)HttpStatusCode.BadGateway;
context.Response.Close();
return;
}
Log($"<<< {((int)response.StatusCode)} {response.ReasonPhrase}");
Log($"<<< Headers ({response.Headers.Count()}):");
foreach (var header in response.Headers)
Log($"<<< {header.Key}: {string.Join(", ", header.Value)}");
var isCompressed = response.Content.Headers.ContentEncoding.Contains("gzip", StringComparer.OrdinalIgnoreCase);
if (logBody)
{
if (isCompressed)
{
await using var rawStream = await response.Content.ReadAsStreamAsync();
await using var gzipStream = new GZipStream(rawStream, CompressionMode.Decompress);
using var reader = new StreamReader(gzipStream, clientEncoding);
var decompressed = await reader.ReadToEndAsync();
Log($"<<< Body (decompressed):\n\n{decompressed}\n");
}
else
{
var responseBody = await response.Content.ReadAsStringAsync();
Log($"<<< Body:\n\n{responseBody}\n");
}
}
context.Response.StatusCode = (int)response.StatusCode;
context.Response.ContentType = response.Content.Headers.ContentType?.ToString() ?? "application/octet-stream";
if (response.Content.Headers.ContentLength.HasValue)
context.Response.ContentLength64 = response.Content.Headers.ContentLength.Value;
foreach (var header in response.Content.Headers)
{
foreach (var value in header.Value)
{
context.Response.Headers[header.Key] = value;
}
}
await using var forwardStream = await response.Content.ReadAsStreamAsync();
await forwardStream.CopyToAsync(context.Response.OutputStream);
}
catch (Exception ex)
{
Log($"[ERROR] An error occurred while processing the request: {ex.Message}");
try
{
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
context.Response.Close();
}
catch
{
// Ignore errors during response cleanup
}
}
});
}
catch (Exception ex)
{
Log($"[ERROR] An error occurred while accepting a connection: {ex.Message}");
}
}
}
finally
{
listener.Stop();
Log("[INFO] HttpListener stopped.");
}
Log($"[INFO] {programName} terminated.");
return;
// ==== Logging ====
void Log(string line)
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
var formatted = $"[{timestamp}] {line}";
Console.WriteLine(formatted);
File.AppendAllText(logPath, formatted + Environment.NewLine);
}
// ==== Certificate ====
X509Certificate2? FindCertificate(string subjectName)
{
foreach (var location in new[] { StoreLocation.CurrentUser, StoreLocation.LocalMachine })
{
using var store = new X509Store(StoreName.My, location);
try
{
store.Open(OpenFlags.ReadOnly);
var certs = store.Certificates.Find(X509FindType.FindBySubjectName, subjectName, false);
if (certs.Count > 0)
return certs[0];
}
catch
{
// Ignore error
}
}
return null;
}