Skip to content
This repository was archived by the owner on Jul 9, 2023. It is now read-only.

Commit a4ea380

Browse files
Merge pull request #485 from justcoding121/master
Linux/Unix new line issue fix
2 parents 042a3a0 + 67bfa3b commit a4ea380

File tree

52 files changed

+276
-256
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+276
-256
lines changed

Titanium.Web.Proxy/Helpers/HttpWriter.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ internal class HttpWriter : ICustomStreamWriter
1616
private readonly Stream stream;
1717
private readonly IBufferPool bufferPool;
1818

19-
private static readonly byte[] newLine = ProxyConstants.NewLine;
19+
private static readonly byte[] newLine = ProxyConstants.NewLineBytes;
2020

2121
private static readonly Encoder encoder = Encoding.ASCII.GetEncoder();
2222

@@ -109,9 +109,9 @@ internal async Task WriteHeadersAsync(HeaderCollection headers, bool flush = tru
109109
var headerBuilder = new StringBuilder();
110110
foreach (var header in headers)
111111
{
112-
headerBuilder.AppendLine(header.ToString());
112+
headerBuilder.Append($"{header.ToString()}{ProxyConstants.NewLine}");
113113
}
114-
headerBuilder.AppendLine();
114+
headerBuilder.Append(ProxyConstants.NewLine);
115115

116116
await WriteAsync(headerBuilder.ToString(), cancellationToken);
117117

Titanium.Web.Proxy/Http/HttpWebClient.cs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using Titanium.Web.Proxy.Extensions;
99
using Titanium.Web.Proxy.Models;
1010
using Titanium.Web.Proxy.Network.Tcp;
11+
using Titanium.Web.Proxy.Shared;
1112

1213
namespace Titanium.Web.Proxy.Http
1314
{
@@ -16,7 +17,6 @@ namespace Titanium.Web.Proxy.Http
1617
/// </summary>
1718
public class HttpWebClient
1819
{
19-
2020
internal HttpWebClient(Request request = null, Response response = null)
2121
{
2222
Request = request ?? new Request();
@@ -103,26 +103,28 @@ await writer.WriteLineAsync(Request.CreateRequestLine(Request.Method,
103103
Request.HttpVersion), cancellationToken);
104104

105105
var headerBuilder = new StringBuilder();
106+
106107
// Send Authentication to Upstream proxy if needed
107108
if (!isTransparent && upstreamProxy != null
108109
&& ServerConnection.IsHttps == false
109110
&& !string.IsNullOrEmpty(upstreamProxy.UserName)
110111
&& upstreamProxy.Password != null)
111112
{
112-
headerBuilder.AppendLine(HttpHeader.ProxyConnectionKeepAlive.ToString());
113-
headerBuilder.AppendLine(HttpHeader.GetProxyAuthorizationHeader(upstreamProxy.UserName, upstreamProxy.Password).ToString());
113+
headerBuilder.Append($"{HttpHeader.ProxyConnectionKeepAlive}{ProxyConstants.NewLine}");
114+
headerBuilder.Append($"{HttpHeader.GetProxyAuthorizationHeader(upstreamProxy.UserName, upstreamProxy.Password)}{ProxyConstants.NewLine}");
114115
}
115116

116117
// write request headers
117118
foreach (var header in Request.Headers)
118119
{
119120
if (isTransparent || header.Name != KnownHeaders.ProxyAuthorization)
120121
{
121-
headerBuilder.AppendLine(header.ToString());
122+
headerBuilder.Append($"{header}{ProxyConstants.NewLine}");
122123
}
123124
}
124125

125-
headerBuilder.AppendLine();
126+
headerBuilder.Append(ProxyConstants.NewLine);
127+
126128
await writer.WriteAsync(headerBuilder.ToString(), cancellationToken);
127129

128130
if (enable100ContinueBehaviour)

Titanium.Web.Proxy/Http/Request.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -140,13 +140,13 @@ public override string HeaderText
140140
get
141141
{
142142
var sb = new StringBuilder();
143-
sb.AppendLine(CreateRequestLine(Method, OriginalUrl, HttpVersion));
143+
sb.Append($"{CreateRequestLine(Method, OriginalUrl, HttpVersion)}{ProxyConstants.NewLine}");
144144
foreach (var header in Headers)
145145
{
146-
sb.AppendLine(header.ToString());
146+
sb.Append($"{header.ToString()}{ProxyConstants.NewLine}");
147147
}
148148

149-
sb.AppendLine();
149+
sb.Append(ProxyConstants.NewLine);
150150
return sb.ToString();
151151
}
152152
}

Titanium.Web.Proxy/Http/Response.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -110,13 +110,13 @@ public override string HeaderText
110110
get
111111
{
112112
var sb = new StringBuilder();
113-
sb.AppendLine(CreateResponseLine(HttpVersion, StatusCode, StatusDescription));
113+
sb.Append($"{CreateResponseLine(HttpVersion, StatusCode, StatusDescription)}{ProxyConstants.NewLine}");
114114
foreach (var header in Headers)
115115
{
116-
sb.AppendLine(header.ToString());
116+
sb.Append($"{header.ToString()}{ProxyConstants.NewLine}");
117117
}
118118

119-
sb.AppendLine();
119+
sb.Append(ProxyConstants.NewLine);
120120
return sb.ToString();
121121
}
122122
}
@@ -145,7 +145,7 @@ internal static void ParseResponseLine(string httpStatus, out Version version, o
145145
out string statusDescription)
146146
{
147147
var httpResult = httpStatus.Split(ProxyConstants.SpaceSplit, 3);
148-
if (httpResult.Length != 3)
148+
if (httpResult.Length <= 1)
149149
{
150150
throw new Exception("Invalid HTTP status line: " + httpStatus);
151151
}
@@ -159,7 +159,7 @@ internal static void ParseResponseLine(string httpStatus, out Version version, o
159159
}
160160

161161
statusCode = int.Parse(httpResult[1]);
162-
statusDescription = httpResult[2];
162+
statusDescription = httpResult.Length > 2 ? httpResult[2] : string.Empty;
163163
}
164164
}
165165
}

Titanium.Web.Proxy/Network/Certificate/WinCertificateMaker.cs

Lines changed: 35 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ internal class WinCertificateMaker : ICertificateMaker
5252
internal WinCertificateMaker(ExceptionHandler exceptionFunc)
5353
{
5454
this.exceptionFunc = exceptionFunc;
55+
5556
typeX500DN = Type.GetTypeFromProgID("X509Enrollment.CX500DistinguishedName", true);
5657
typeX509PrivateKey = Type.GetTypeFromProgID("X509Enrollment.CX509PrivateKey", true);
5758
typeOID = Type.GetTypeFromProgID("X509Enrollment.CObjectId", true);
@@ -74,13 +75,41 @@ internal WinCertificateMaker(ExceptionHandler exceptionFunc)
7475
/// <summary>
7576
/// Make certificate.
7677
/// </summary>
77-
/// <param name="sSubjectCN"></param>
78-
/// <param name="isRoot"></param>
79-
/// <param name="signingCert"></param>
80-
/// <returns></returns>
8178
public X509Certificate2 MakeCertificate(string sSubjectCN, bool isRoot, X509Certificate2 signingCert = null)
8279
{
83-
return makeCertificateInternal(sSubjectCN, isRoot, true, signingCert);
80+
return makeCertificate(sSubjectCN, isRoot, true, signingCert);
81+
}
82+
83+
private X509Certificate2 makeCertificate(string sSubjectCN, bool isRoot,
84+
bool switchToMTAIfNeeded, X509Certificate2 signingCert = null,
85+
CancellationToken cancellationToken = default)
86+
{
87+
if (switchToMTAIfNeeded && Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
88+
{
89+
return Task.Run(() => makeCertificate(sSubjectCN, isRoot, false, signingCert),
90+
cancellationToken).Result;
91+
}
92+
93+
// Subject
94+
string fullSubject = $"CN={sSubjectCN}";
95+
96+
// Sig Algo
97+
const string hashAlgo = "SHA256";
98+
99+
// Grace Days
100+
const int graceDays = -366;
101+
102+
// ValiDays
103+
const int validDays = 1825;
104+
105+
// KeyLength
106+
const int keyLength = 2048;
107+
108+
var graceTime = DateTime.Now.AddDays(graceDays);
109+
var now = DateTime.Now;
110+
var certificate = makeCertificate(isRoot, sSubjectCN, fullSubject, keyLength, hashAlgo, graceTime,
111+
now.AddDays(validDays), isRoot ? null : signingCert);
112+
return certificate;
84113
}
85114

86115
private X509Certificate2 makeCertificate(bool isRoot, string subject, string fullSubject,
@@ -271,39 +300,9 @@ private X509Certificate2 makeCertificate(bool isRoot, string subject, string ful
271300

272301
string empty = (string)typeX509Enrollment.InvokeMember("CreatePFX", BindingFlags.InvokeMethod, null,
273302
x509Enrollment, typeValue);
303+
274304
return new X509Certificate2(Convert.FromBase64String(empty), string.Empty, X509KeyStorageFlags.Exportable);
275305
}
276306

277-
private X509Certificate2 makeCertificateInternal(string sSubjectCN, bool isRoot,
278-
bool switchToMTAIfNeeded, X509Certificate2 signingCert = null,
279-
CancellationToken cancellationToken = default)
280-
{
281-
if (switchToMTAIfNeeded && Thread.CurrentThread.GetApartmentState() != ApartmentState.MTA)
282-
{
283-
return Task.Run(() => makeCertificateInternal(sSubjectCN, isRoot, false, signingCert),
284-
cancellationToken).Result;
285-
}
286-
287-
// Subject
288-
string fullSubject = $"CN={sSubjectCN}";
289-
290-
// Sig Algo
291-
const string hashAlgo = "SHA256";
292-
293-
// Grace Days
294-
const int graceDays = -366;
295-
296-
// ValiDays
297-
const int validDays = 1825;
298-
299-
// KeyLength
300-
const int keyLength = 2048;
301-
302-
var graceTime = DateTime.Now.AddDays(graceDays);
303-
var now = DateTime.Now;
304-
var certificate = makeCertificate(isRoot, sSubjectCN, fullSubject, keyLength, hashAlgo, graceTime,
305-
now.AddDays(validDays), isRoot ? null : signingCert);
306-
return certificate;
307-
}
308307
}
309308
}

Titanium.Web.Proxy/Network/CertificateManager.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@ public enum CertificateEngine
2525
BouncyCastle = 0,
2626

2727
/// <summary>
28-
/// Uses Windows Certification Generation API.
28+
/// Uses Windows Certification Generation API and only valid in Windows OS.
29+
/// Observed to be faster than BouncyCastle.
2930
/// Bug #468 Reported.
3031
/// </summary>
3132
DefaultWindows = 1

Titanium.Web.Proxy/RequestHandler.cs

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
using Titanium.Web.Proxy.Http;
1717
using Titanium.Web.Proxy.Models;
1818
using Titanium.Web.Proxy.Network.Tcp;
19+
using Titanium.Web.Proxy.Shared;
1920

2021
namespace Titanium.Web.Proxy
2122
{
@@ -24,15 +25,6 @@ namespace Titanium.Web.Proxy
2425
/// </summary>
2526
public partial class ProxyServer
2627
{
27-
private static readonly Regex uriSchemeRegex =
28-
new Regex("^[a-z]*://", RegexOptions.IgnoreCase | RegexOptions.Compiled);
29-
30-
private static readonly HashSet<string> proxySupportedCompressions =
31-
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
32-
{
33-
"gzip",
34-
"deflate"
35-
};
3628

3729
private bool isWindowsAuthenticationEnabledAndSupported =>
3830
EnableWinAuth && RunTime.IsWindows && !RunTime.IsRunningOnMono;
@@ -96,7 +88,7 @@ await HeaderParser.ReadHeaders(clientStream, args.WebSession.Request.Headers,
9688
cancellationToken);
9789

9890
Uri httpRemoteUri;
99-
if (uriSchemeRegex.IsMatch(httpUrl))
91+
if (ProxyConstants.UriSchemeRegex.IsMatch(httpUrl))
10092
{
10193
try
10294
{
@@ -228,7 +220,7 @@ await handleWebSocketUpgrade(httpCmd, args, request,
228220
}
229221

230222
// construct the web request that we are going to issue on behalf of the client.
231-
await handleHttpSessionRequestInternal(serverConnection, args);
223+
await handleHttpSessionRequest(serverConnection, args);
232224
return true;
233225

234226
}, generator, connection);
@@ -312,7 +304,7 @@ await tcpConnectionFactory.Release(connection,
312304
/// <param name="serverConnection">The tcp connection.</param>
313305
/// <param name="args">The session event arguments.</param>
314306
/// <returns></returns>
315-
private async Task handleHttpSessionRequestInternal(TcpServerConnection serverConnection, SessionEventArgs args)
307+
private async Task handleHttpSessionRequest(TcpServerConnection serverConnection, SessionEventArgs args)
316308
{
317309
var cancellationToken = args.CancellationTokenSource.Token;
318310
var request = args.WebSession.Request;
@@ -400,7 +392,7 @@ private void prepareRequestHeaders(HeaderCollection requestHeaders)
400392
//only allow proxy supported compressions
401393
supportedAcceptEncoding.AddRange(acceptEncoding.Split(',')
402394
.Select(x => x.Trim())
403-
.Where(x => proxySupportedCompressions.Contains(x)));
395+
.Where(x => ProxyConstants.ProxySupportedCompressions.Contains(x)));
404396

405397
//uncompressed is always supported by proxy
406398
supportedAcceptEncoding.Add("identity");

Titanium.Web.Proxy/ResponseHandler.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ private async Task handleHttpSessionResponse(SessionEventArgs args)
8080
{
8181
// clear current response
8282
await args.ClearResponse(cancellationToken);
83-
await handleHttpSessionRequestInternal(args.WebSession.ServerConnection, args);
83+
await handleHttpSessionRequest(args.WebSession.ServerConnection, args);
8484
return;
8585
}
8686

Titanium.Web.Proxy/Shared/ProxyConstants.cs

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
using System.Text.RegularExpressions;
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Text.RegularExpressions;
24

35
namespace Titanium.Web.Proxy.Shared
46
{
@@ -14,9 +16,20 @@ internal class ProxyConstants
1416
internal static readonly char[] SemiColonSplit = { ';' };
1517
internal static readonly char[] EqualSplit = { '=' };
1618

17-
internal static readonly byte[] NewLine = { (byte)'\r', (byte)'\n' };
19+
internal static readonly string NewLine = "\r\n";
20+
internal static readonly byte[] NewLineBytes = { (byte)'\r', (byte)'\n' };
1821

19-
public static readonly Regex CNRemoverRegex =
22+
internal static readonly Regex UriSchemeRegex =
23+
new Regex("^[a-z]*://", RegexOptions.IgnoreCase | RegexOptions.Compiled);
24+
25+
internal static readonly HashSet<string> ProxySupportedCompressions =
26+
new HashSet<string>(StringComparer.OrdinalIgnoreCase)
27+
{
28+
"gzip",
29+
"deflate"
30+
};
31+
32+
internal static readonly Regex CNRemoverRegex =
2033
new Regex(@"^CN\s*=\s*", RegexOptions.IgnoreCase | RegexOptions.Compiled);
2134
}
2235
}

docs/api/Titanium.Web.Proxy.EventArguments.AsyncEventHandler-1.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Delegate AsyncEventHandler&lt;TEventArgs&gt;
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.BeforeSslAuthenticateEventArgs.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class BeforeSslAuthenticateEventArgs
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.CertificateSelectionEventArgs.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class CertificateSelectionEventArgs
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.CertificateValidationEventArgs.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class CertificateValidationEventArgs
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.MultipartRequestPartSentEventArgs.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class MultipartRequestPartSentEventArgs
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgs.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class SessionEventArgs
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class SessionEventArgsBase
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

docs/api/Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
<meta name="viewport" content="width=device-width">
1111
<meta name="title" content="Class TunnelConnectSessionEventArgs
1212
| Titanium Web Proxy ">
13-
<meta name="generator" content="docfx 2.37.2.0">
13+
<meta name="generator" content="docfx 2.38.1.0">
1414

1515
<link rel="shortcut icon" href="../favicon.ico">
1616
<link rel="stylesheet" href="../styles/docfx.vendor.css">

0 commit comments

Comments
 (0)