├── .github
├── docfx.json
├── install-unit-test-certificate.ps1
├── lib
│ └── rootCert.pfx
└── workflows
│ └── dotnetcore.yml
├── .gitignore
├── .vscode
├── launch.json
├── settings.json
└── tasks.json
├── LICENSE
├── NuGet.config
├── PULL_REQUEST_TEMPLATE.md
├── README.md
├── _config.yml
├── docs
├── api
│ ├── Titanium.Web.Proxy.EventArguments.AsyncEventHandler-1.html
│ ├── Titanium.Web.Proxy.EventArguments.BeforeSslAuthenticateEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.CertificateSelectionEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.CertificateValidationEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.DataEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.EmptyProxyEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.MultipartRequestPartSentEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.ProxyEventArgsBase.html
│ ├── Titanium.Web.Proxy.EventArguments.SessionEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.SessionEventArgsBase.html
│ ├── Titanium.Web.Proxy.EventArguments.TunnelConnectSessionEventArgs.html
│ ├── Titanium.Web.Proxy.EventArguments.html
│ ├── Titanium.Web.Proxy.ExceptionHandler.html
│ ├── Titanium.Web.Proxy.Exceptions.BodyNotFoundException.html
│ ├── Titanium.Web.Proxy.Exceptions.ProxyAuthorizationException.html
│ ├── Titanium.Web.Proxy.Exceptions.ProxyConnectException.html
│ ├── Titanium.Web.Proxy.Exceptions.ProxyException.html
│ ├── Titanium.Web.Proxy.Exceptions.ProxyHttpException.html
│ ├── Titanium.Web.Proxy.Exceptions.RetryableServerConnectionException.html
│ ├── Titanium.Web.Proxy.Exceptions.ServerConnectionException.html
│ ├── Titanium.Web.Proxy.Exceptions.html
│ ├── Titanium.Web.Proxy.Extensions.SslApplicationProtocol.html
│ ├── Titanium.Web.Proxy.Extensions.SslClientAuthenticationOptions.html
│ ├── Titanium.Web.Proxy.Extensions.SslServerAuthenticationOptions.html
│ ├── Titanium.Web.Proxy.Extensions.html
│ ├── Titanium.Web.Proxy.Helpers.ProxyProtocolType.html
│ ├── Titanium.Web.Proxy.Helpers.Ref-1.html
│ ├── Titanium.Web.Proxy.Helpers.RunTime.html
│ ├── Titanium.Web.Proxy.Helpers.html
│ ├── Titanium.Web.Proxy.Http.ConnectRequest.html
│ ├── Titanium.Web.Proxy.Http.ConnectResponse.html
│ ├── Titanium.Web.Proxy.Http.HeaderCollection.html
│ ├── Titanium.Web.Proxy.Http.HttpWebClient.html
│ ├── Titanium.Web.Proxy.Http.KnownHeader.html
│ ├── Titanium.Web.Proxy.Http.KnownHeaders.html
│ ├── Titanium.Web.Proxy.Http.Request.html
│ ├── Titanium.Web.Proxy.Http.RequestResponseBase.html
│ ├── Titanium.Web.Proxy.Http.Response.html
│ ├── Titanium.Web.Proxy.Http.Responses.GenericResponse.html
│ ├── Titanium.Web.Proxy.Http.Responses.OkResponse.html
│ ├── Titanium.Web.Proxy.Http.Responses.RedirectResponse.html
│ ├── Titanium.Web.Proxy.Http.Responses.html
│ ├── Titanium.Web.Proxy.Http.TunnelType.html
│ ├── Titanium.Web.Proxy.Http.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.Decoder.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.DynamicTable.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.Encoder.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.HpackUtil.IndexType.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.HpackUtil.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.HuffmanDecoder.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.HuffmanEncoder.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.IHeaderListener.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.StaticTable.html
│ ├── Titanium.Web.Proxy.Http2.Hpack.html
│ ├── Titanium.Web.Proxy.Models.ExplicitProxyEndPoint.html
│ ├── Titanium.Web.Proxy.Models.ExternalProxy.html
│ ├── Titanium.Web.Proxy.Models.ExternalProxyType.html
│ ├── Titanium.Web.Proxy.Models.HttpHeader.html
│ ├── Titanium.Web.Proxy.Models.IExternalProxy.html
│ ├── Titanium.Web.Proxy.Models.ProxyAuthenticationContext.html
│ ├── Titanium.Web.Proxy.Models.ProxyAuthenticationResult.html
│ ├── Titanium.Web.Proxy.Models.ProxyEndPoint.html
│ ├── Titanium.Web.Proxy.Models.ProxyProtocolType.html
│ ├── Titanium.Web.Proxy.Models.SocksProxyEndPoint.html
│ ├── Titanium.Web.Proxy.Models.TransparentBaseProxyEndPoint.html
│ ├── Titanium.Web.Proxy.Models.TransparentProxyEndPoint.html
│ ├── Titanium.Web.Proxy.Models.html
│ ├── Titanium.Web.Proxy.Network.Certificate.AlternativeNameType.html
│ ├── Titanium.Web.Proxy.Network.Certificate.EncodingType.html
│ ├── Titanium.Web.Proxy.Network.Certificate.html
│ ├── Titanium.Web.Proxy.Network.CertificateEngine.html
│ ├── Titanium.Web.Proxy.Network.CertificateManager.html
│ ├── Titanium.Web.Proxy.Network.DefaultCertificateDiskCache.html
│ ├── Titanium.Web.Proxy.Network.ICertificateCache.html
│ ├── Titanium.Web.Proxy.Network.WinAuth.WinAuthHandler.html
│ ├── Titanium.Web.Proxy.Network.WinAuth.html
│ ├── Titanium.Web.Proxy.Network.html
│ ├── Titanium.Web.Proxy.ProxyServer.html
│ ├── Titanium.Web.Proxy.StreamExtended.BufferPool.IBufferPool.html
│ ├── Titanium.Web.Proxy.StreamExtended.BufferPool.html
│ ├── Titanium.Web.Proxy.StreamExtended.ClientHelloInfo.html
│ ├── Titanium.Web.Proxy.StreamExtended.Models.SslExtension.html
│ ├── Titanium.Web.Proxy.StreamExtended.Models.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.DataEventArgs.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.IHttpStreamReader.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.IHttpStreamWriter.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.ILineStream.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.IPeekStream.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.TaskResult-1.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.TaskResult.html
│ ├── Titanium.Web.Proxy.StreamExtended.Network.html
│ ├── Titanium.Web.Proxy.StreamExtended.ServerHelloInfo.html
│ ├── Titanium.Web.Proxy.StreamExtended.html
│ ├── Titanium.Web.Proxy.WebSocketDecoder.html
│ ├── Titanium.Web.Proxy.WebSocketFrame.html
│ ├── Titanium.Web.Proxy.WebsocketOpCode.html
│ ├── Titanium.Web.Proxy.html
│ └── toc.html
├── favicon.ico
├── fonts
│ ├── glyphicons-halflings-regular.eot
│ ├── glyphicons-halflings-regular.svg
│ ├── glyphicons-halflings-regular.ttf
│ ├── glyphicons-halflings-regular.woff
│ └── glyphicons-halflings-regular.woff2
├── index.json
├── logo.svg
├── search-stopwords.json
├── styles
│ ├── docfx.css
│ ├── docfx.js
│ ├── docfx.vendor.css
│ ├── docfx.vendor.js
│ ├── lunr.js
│ ├── lunr.min.js
│ ├── main.css
│ ├── main.js
│ └── search-worker.js
└── xrefmap.yml
├── examples
├── Titanium.Web.Proxy.Examples.Basic
│ ├── App.config
│ ├── Capture.PNG
│ ├── Helpers
│ │ └── ConsoleHelper.cs
│ ├── Program.cs
│ ├── ProxyEventArgsBaseExtensions.cs
│ ├── ProxyTestController.cs
│ ├── SampleClientState.cs
│ └── Titanium.Web.Proxy.Examples.Basic.csproj
├── Titanium.Web.Proxy.Examples.WindowsService
│ ├── App.config
│ ├── Program.cs
│ ├── Properties
│ │ ├── AssemblyInfo.cs
│ │ ├── Settings.Designer.cs
│ │ └── Settings.settings
│ ├── ProxyService.Designer.cs
│ ├── ProxyService.cs
│ ├── ProxyService.resx
│ ├── Titanium.Web.Proxy.Examples.WindowsService.csproj
│ ├── install.ps1
│ └── remove.ps1
└── Titanium.Web.Proxy.Examples.Wpf
│ ├── App.config
│ ├── App.xaml
│ ├── App.xaml.cs
│ ├── Capture.PNG
│ ├── MainWindow.xaml
│ ├── MainWindow.xaml.cs
│ ├── ObservableCollectionEx.cs
│ ├── Properties
│ ├── Annotations.cs
│ ├── Resources.Designer.cs
│ ├── Resources.resx
│ ├── Settings.Designer.cs
│ └── Settings.settings
│ ├── SessionListItem.cs
│ └── Titanium.Web.Proxy.Examples.Wpf.csproj
├── omnisharp.json
├── src
├── Titanium.Web.Proxy.Docs.sln
├── Titanium.Web.Proxy.sln
└── Titanium.Web.Proxy
│ ├── Certificates
│ ├── Cache
│ │ ├── CachedCertificate.cs
│ │ ├── DefaultCertificateDiskCache.cs
│ │ └── ICertificateCache.cs
│ ├── CertificateManager.cs
│ └── Makers
│ │ ├── BCCertificateMaker.cs
│ │ ├── BCCertificateMakerFast.cs
│ │ ├── ICertificateMaker.cs
│ │ └── WinCertificateMaker.cs
│ ├── Compression
│ ├── CompressionFactory.cs
│ └── DecompressionFactory.cs
│ ├── EventArguments
│ ├── BeforeBodyWriteEventArgs.cs
│ ├── BeforeSslAuthenticateEventArgs.cs
│ ├── CertificateSelectionEventArgs.cs
│ ├── CertificateValidationEventArgs.cs
│ ├── DataEventArgs.cs
│ ├── EmptyProxyEventArgs.cs
│ ├── MultipartRequestPartSentEventArgs.cs
│ ├── ProxyEventArgsBase.cs
│ ├── SessionEventArgs.cs
│ ├── SessionEventArgsBase.cs
│ ├── TransformationMode.cs
│ └── TunnelConnectEventArgs.cs
│ ├── Exceptions
│ ├── BodyNotFoundException.cs
│ ├── ProxyAuthorizationException.cs
│ ├── ProxyConnectException.cs
│ ├── ProxyException.cs
│ ├── ProxyHttpException.cs
│ └── RetryableServerConnectionException.cs
│ ├── ExplicitClientHandler.cs
│ ├── Extensions
│ ├── FuncExtensions.cs
│ ├── HttpHeaderExtensions.cs
│ ├── SslExtensions.cs
│ ├── StreamExtensions.cs
│ ├── StringExtensions.cs
│ ├── TcpExtensions.cs
│ └── UriExtensions.cs
│ ├── Handlers
│ ├── AsyncEventHandler.cs
│ ├── CertificateHandler.cs
│ ├── ExceptionHandler.cs
│ ├── ProxyAuthorizationHandler.cs
│ ├── WebSocketHandler.cs
│ └── WinAuthHandler.cs
│ ├── Helpers
│ ├── CompressionUtil.cs
│ ├── HttpHelper.cs
│ ├── NativeMethods.SystemProxy.cs
│ ├── NativeMethods.Tcp.cs
│ ├── Net45Compatibility.cs
│ ├── Network.cs
│ ├── ProxyInfo.cs
│ ├── RunTime.cs
│ ├── SystemProxy.cs
│ ├── TcpHelper.cs
│ └── WinHttp
│ │ ├── NativeMethods.WinHttp.cs
│ │ ├── WinHttpHandle.cs
│ │ └── WinHttpWebProxyFinder.cs
│ ├── Http
│ ├── ConnectRequest.cs
│ ├── ConnectResponse.cs
│ ├── HeaderBuilder.cs
│ ├── HeaderCollection.cs
│ ├── HeaderParser.cs
│ ├── InternalDataStore.cs
│ ├── KnownHeader.cs
│ ├── KnownHeaders.cs
│ ├── Request.cs
│ ├── RequestResponseBase.cs
│ ├── Response.cs
│ ├── Responses
│ │ ├── GenericResponse.cs
│ │ ├── OkResponse.cs
│ │ └── RedirectResponse.cs
│ └── TunnelType.cs
│ ├── Http2
│ ├── Hpack
│ │ ├── Decoder.cs
│ │ ├── DynamicTable.cs
│ │ ├── Encoder.cs
│ │ ├── HpackUtil.cs
│ │ ├── HuffmanDecoder.cs
│ │ ├── HuffmanEncoder.cs
│ │ ├── IHeaderListener.cs
│ │ └── StaticTable.cs
│ ├── Http2FrameFlag.cs
│ ├── Http2FrameHeader.cs
│ ├── Http2FrameType.cs
│ └── Http2Helper.cs
│ ├── Models
│ ├── ByteString.cs
│ ├── ExplicitProxyEndPoint.cs
│ ├── ExternalProxy.cs
│ ├── HttpCompression.cs
│ ├── HttpHeader.cs
│ ├── IExternalProxy.cs
│ ├── KnownMethod.cs
│ ├── ProxyAuthenticationContext.cs
│ ├── ProxyEndPoint.cs
│ ├── ProxyProtocolType.cs
│ ├── RequestStatusInfo.cs
│ ├── ResponseStatusInfo.cs
│ ├── SocksProxyEndPoint.cs
│ ├── TransparentBaseProxyEndPoint.cs
│ └── TransparentProxyEndPoint.cs
│ ├── Network
│ ├── BufferPool
│ │ ├── DefaultBufferPool.cs
│ │ └── IBufferPool.cs
│ ├── HttpWebClient.cs
│ ├── Models
│ │ ├── SslCiphers.cs
│ │ ├── SslExtension.cs
│ │ └── TaskResult.cs
│ ├── Readers
│ │ ├── IHttpStreamReader.cs
│ │ └── PeekStreamReader.cs
│ ├── RetryPolicy.cs
│ ├── Ssl
│ │ ├── ClientHelloInfo.cs
│ │ ├── ServerHelloInfo.cs
│ │ └── SslTools.cs
│ ├── Streams
│ │ ├── CopyStream.cs
│ │ ├── HttpClientStream.cs
│ │ ├── HttpServerStream.cs
│ │ ├── HttpStream.cs
│ │ ├── ILineStream.cs
│ │ ├── IPeekStream.cs
│ │ └── LimitedStream.cs
│ ├── TcpConnection
│ │ ├── TcpClientConnection.cs
│ │ ├── TcpConnectionFactory.cs
│ │ └── TcpServerConnection.cs
│ ├── WinAuth
│ │ ├── Security
│ │ │ ├── Common.cs
│ │ │ ├── LittleEndian.cs
│ │ │ ├── Message.cs
│ │ │ ├── State.cs
│ │ │ └── WinAuthEndPoint.cs
│ │ └── WinAuthHandler.cs
│ └── Writers
│ │ ├── IHttpStreamWriter.cs
│ │ └── NullWriter.cs
│ ├── Properties
│ └── AssemblyInfo.cs
│ ├── ProxyServer.cs
│ ├── ProxySocket
│ ├── Authentication
│ │ ├── AuthMethod.cs
│ │ ├── AuthNone.cs
│ │ └── AuthUserPass.cs
│ ├── HttpsHandler.cs
│ ├── IAsyncProxyResult.cs
│ ├── ProxyException.cs
│ ├── ProxySocket.cs
│ ├── Socks4Handler.cs
│ ├── Socks5Handler.cs
│ └── SocksHandler.cs
│ ├── RequestHandler.cs
│ ├── ResponseHandler.cs
│ ├── Shared
│ └── ProxyConstants.cs
│ ├── SocksClientHandler.cs
│ ├── StrongNameKey.snk
│ ├── Titanium.Web.Proxy.csproj
│ ├── TransparentClientHandler.cs
│ ├── WebSocket
│ ├── WebSocketDecoder.cs
│ ├── WebSocketFrame.cs
│ └── WebsocketOpCode.cs
│ └── app.config
└── tests
├── Titanium.Web.Proxy.IntegrationTests
├── .editorconfig
├── ExpectContinueTests.cs
├── Helpers
│ ├── HttpContinueClient.cs
│ ├── HttpContinueServer.cs
│ ├── HttpMessageParsing.cs
│ └── TestHelper.cs
├── HttpsTests.cs
├── InterceptionTests.cs
├── NestedProxyTests.cs
├── ReverseProxyTests.cs
├── Setup
│ ├── TestProxyServer.cs
│ ├── TestServer.cs
│ └── TestSuite.cs
├── StressTests.cs
├── StrongNameKey.snk
├── Titanium.Web.Proxy.IntegrationTests.csproj
└── Titanium.Web.Proxy.IntegrationTests.sln
└── Titanium.Web.Proxy.UnitTests
├── CertificateManagerTests.cs
├── Properties
└── AssemblyInfo.cs
├── ProxyServerTests.cs
├── StrongNameKey.snk
├── SystemProxyTest.cs
├── Titanium.Web.Proxy.UnitTests.csproj
└── WinAuthTests.cs
/.github/docfx.json:
--------------------------------------------------------------------------------
1 | {
2 | "metadata": [
3 | {
4 | "src": [
5 | {
6 | "files": ["Titanium.Web.Proxy.Docs.sln"],
7 | "src": "../src/"
8 | }
9 | ],
10 | "dest": "obj/api"
11 | }
12 | ],
13 | "build": {
14 | "content": [
15 | {
16 | "files": ["**/*.yml"],
17 | "src": "obj/api",
18 | "dest": "api"
19 | },
20 | {
21 | "files": ["*.md"]
22 | }
23 | ],
24 | "resource": [
25 | {
26 | "files": [""]
27 | }
28 | ],
29 | "overwrite": "specs/*.md",
30 | "globalMetadata": {
31 | "_appTitle": "Titanium Web Proxy",
32 | "_enableSearch": true
33 | },
34 | "dest": "../docs",
35 | "xrefService": ["https://xref.docs.microsoft.com/query?uid={uid}"]
36 | }
37 | }
--------------------------------------------------------------------------------
/.github/install-unit-test-certificate.ps1:
--------------------------------------------------------------------------------
1 | $Here = "$(Split-Path -parent $MyInvocation.MyCommand.Definition)"
2 | $certPath = "$Here\lib\rootCert.pfx"
3 | $pfx = New-Object -TypeName System.Security.Cryptography.X509Certificates.X509Certificate2($certPath,"","Exportable,PersistKeySet")
4 | $store = new-object System.Security.Cryptography.X509Certificates.X509Store([System.Security.Cryptography.X509Certificates.StoreName]::Root, "localmachine")
5 | $store.open("MaxAllowed")
6 | $store.add($pfx)
7 | $store.close()
--------------------------------------------------------------------------------
/.github/lib/rootCert.pfx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/.github/lib/rootCert.pfx
--------------------------------------------------------------------------------
/.github/workflows/dotnetcore.yml:
--------------------------------------------------------------------------------
1 | name: .NET Core
2 |
3 | on:
4 | push:
5 | branches:
6 | - develop
7 | - beta
8 | - stable
9 | pull_request:
10 | branches:
11 | - develop
12 | - beta
13 | - stable
14 |
15 | jobs:
16 | build:
17 | runs-on: windows-latest
18 | steps:
19 | - uses: actions/checkout@v2
20 |
21 | - name: Install DocFX
22 | if: github.ref == 'refs/heads/develop'
23 | run: choco install docfx -y
24 |
25 | - name: Build
26 | run: dotnet build src/Titanium.Web.Proxy/Titanium.Web.Proxy.csproj
27 |
28 | - name: Test
29 | shell: pwsh
30 | run: |
31 | .\.github\install-unit-test-certificate.ps1
32 | dotnet test tests/Titanium.Web.Proxy.UnitTests/Titanium.Web.Proxy.UnitTests.csproj
33 | dotnet test tests/Titanium.Web.Proxy.IntegrationTests/Titanium.Web.Proxy.IntegrationTests.csproj
34 |
35 | - name: Update Documentation
36 | if: github.ref == 'refs/heads/develop'
37 | run: docfx .github/docfx.json
38 |
39 | - name: Publish Documentation
40 | if: github.ref == 'refs/heads/develop'
41 | uses: EndBug/add-and-commit@v9
42 | with:
43 | default_author: github_actions
44 | message: Update documentation
45 | committer_name: GitHub Actions
46 | committer_email: actions@github.com
47 |
48 | - name: Publish Beta
49 | if: github.ref == 'refs/heads/beta'
50 | run: |
51 | dotnet pack src/Titanium.Web.Proxy/Titanium.Web.Proxy.csproj --version-suffix "beta"
52 | dotnet nuget push **\*.nupkg -s "nuget" -k "${{ secrets.NUGET_TOKEN }}"
53 |
54 | - name: Publish Stable
55 | if: github.ref == 'refs/heads/stable'
56 | run: |
57 | dotnet pack src/Titanium.Web.Proxy/Titanium.Web.Proxy.csproj
58 | dotnet nuget push **\*.nupkg -s "nuget" -k "${{ secrets.NUGET_TOKEN }}"
59 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 |
4 | # User-specific files
5 | *.suo
6 | *.user
7 | *.userosscache
8 | *.sln.docstates
9 |
10 | # User-specific files (MonoDevelop/Xamarin Studio)
11 | *.userprefs
12 |
13 | # Build results
14 | [Dd]ebug/
15 | [Dd]ebugPublic/
16 | [Rr]elease/
17 | [Rr]eleases/
18 | x64/
19 | x86/
20 | build/
21 | bld/
22 | [Bb]in/
23 | [Oo]bj/
24 |
25 | # Visual Studio 2015 cache/options directory
26 | .vs/
27 |
28 | # MSTest test Results
29 | [Tt]est[Rr]esult*/
30 | [Bb]uild[Ll]og.*
31 |
32 | # NUNIT
33 | *.VisualState.xml
34 | TestResult.xml
35 |
36 | # Build Results of an ATL Project
37 | [Dd]ebugPS/
38 | [Rr]eleasePS/
39 | dlldata.c
40 |
41 | # DNX
42 | project.lock.json
43 | artifacts/
44 |
45 | *_i.c
46 | *_p.c
47 | *_i.h
48 | *.ilk
49 | *.meta
50 | *.obj
51 | *.pch
52 | *.pdb
53 | *.pgc
54 | *.pgd
55 | *.rsp
56 | *.sbr
57 | *.tlb
58 | *.tli
59 | *.tlh
60 | *.tmp
61 | *.tmp_proj
62 | *.log
63 | *.vspscc
64 | *.vssscc
65 | .builds
66 | *.pidb
67 | *.svclog
68 | *.scc
69 |
70 | # Chutzpah Test files
71 | _Chutzpah*
72 |
73 | # Visual C++ cache files
74 | ipch/
75 | *.aps
76 | *.ncb
77 | *.opensdf
78 | *.sdf
79 | *.cachefile
80 |
81 | # Visual Studio profiler
82 | *.psess
83 | *.vsp
84 | *.vspx
85 |
86 | # TFS 2012 Local Workspace
87 | $tf/
88 |
89 | # Guidance Automation Toolkit
90 | *.gpState
91 |
92 | # ReSharper is a .NET coding add-in
93 | _ReSharper*/
94 | *.[Rr]e[Ss]harper
95 | *.DotSettings.user
96 |
97 | # JustCode is a .NET coding add-in
98 | .JustCode
99 |
100 | # TeamCity is a build add-in
101 | _TeamCity*
102 |
103 | # DotCover is a Code Coverage Tool
104 | *.dotCover
105 |
106 | # NCrunch
107 | _NCrunch_*
108 | .*crunch*.local.xml
109 |
110 | # MightyMoose
111 | *.mm.*
112 | AutoTest.Net/
113 |
114 | # Web workbench (sass)
115 | .sass-cache/
116 |
117 | # Installshield output folder
118 | [Ee]xpress/
119 |
120 | # DocProject is a documentation generator add-in
121 | DocProject/buildhelp/
122 | DocProject/Help/*.HxT
123 | DocProject/Help/*.HxC
124 | DocProject/Help/*.hhc
125 | DocProject/Help/*.hhk
126 | DocProject/Help/*.hhp
127 | DocProject/Help/Html2
128 | DocProject/Help/html
129 |
130 | # Click-Once directory
131 | publish/
132 |
133 | # Publish Web Output
134 | *.[Pp]ublish.xml
135 | *.azurePubxml
136 | # TODO: Comment the next line if you want to checkin your web deploy settings
137 | # but database connection strings (with potential passwords) will be unencrypted
138 | *.pubxml
139 | *.publishproj
140 |
141 | # NuGet Packages
142 | *.nupkg
143 | # The packages folder can be ignored because of Package Restore
144 | **/packages/*
145 | # except build/, which is used as an MSBuild target.
146 | !**/packages/build/
147 | # Uncomment if necessary however generally it will be regenerated when needed
148 | #!**/packages/repositories.config
149 |
150 | # Windows Azure Build Output
151 | csx/
152 | *.build.csdef
153 |
154 | # Windows Store app package directory
155 | AppPackages/
156 |
157 | # Visual Studio cache files
158 | # files ending in .cache can be ignored
159 | *.[Cc]ache
160 | # but keep track of directories ending in .cache
161 | !*.[Cc]ache/
162 |
163 | # Others
164 | ClientBin/
165 | [Ss]tyle[Cc]op.*
166 | ~$*
167 | *~
168 | *.dbmdl
169 | *.dbproj.schemaview
170 | *.pfx
171 | *.publishsettings
172 | node_modules/
173 | orleans.codegen.cs
174 |
175 | # RIA/Silverlight projects
176 | Generated_Code/
177 |
178 | # Backup & report files from converting an old project file
179 | # to a newer Visual Studio version. Backup files are not needed,
180 | # because we have git ;-)
181 | _UpgradeReport_Files/
182 | Backup*/
183 | UpgradeLog*.XML
184 | UpgradeLog*.htm
185 |
186 | # SQL Server files
187 | *.mdf
188 | *.ldf
189 |
190 | # Business Intelligence projects
191 | *.rdl.data
192 | *.bim.layout
193 | *.bim_*.settings
194 |
195 | # Microsoft Fakes
196 | FakesAssemblies/
197 |
198 | # Node.js Tools for Visual Studio
199 | .ntvs_analysis.dat
200 |
201 | # Visual Studio 6 build log
202 | *.plg
203 |
204 | # Visual Studio 6 workspace options file
205 | *.opt
206 |
207 | # Docfx
208 | docs/manifest.json
209 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "0.2.0",
3 | "configurations": [
4 | {
5 | "name": "NetCore|Debug|Basic Example",
6 | "type": "coreclr",
7 | "request": "launch",
8 | "program": "${workspaceRoot}/examples/Titanium.Web.Proxy.Examples.Basic/bin/Debug/netcoreapp3.1/Titanium.Web.Proxy.Examples.Basic.NetCore.dll",
9 | "args": [],
10 | "cwd": "${workspaceRoot}",
11 | "stopAtEntry": false,
12 | "console": "integratedTerminal",
13 | "preLaunchTask": "build-basic-example-netcore-debug"
14 | },
15 | {
16 | "name": "NetCore|Release|Basic Example",
17 | "type": "coreclr",
18 | "request": "launch",
19 | "program": "${workspaceRoot}/examples/Titanium.Web.Proxy.Examples.Basic/bin/Release/netcoreapp3.1/Titanium.Web.Proxy.Examples.Basic.NetCore.dll",
20 | "args": [],
21 | "cwd": "${workspaceRoot}",
22 | "stopAtEntry": false,
23 | "console": "integratedTerminal",
24 | "preLaunchTask": "build-basic-example-netcore-release"
25 | }
26 | ]
27 | }
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | // The following will hide the js and map files in the editor
3 | "files.exclude": {
4 | "**/.build": true,
5 | "**/.nuget": true,
6 | "**/.vs": true,
7 | "**/docs": true,
8 | "**/packages": true,
9 | "**/bin": true,
10 | "**/obj": true,
11 | "**/*.DotSettings": true,
12 | "**/*.sln": true,
13 | "**/tests/" : true,
14 | "**/Titanium.Web.Proxy.Examples.Wpf/" : true,
15 | "**/*.Basic.csproj/": true,
16 | "**/*.Docs.csproj/": true,
17 | "**/*.Proxy.csproj/": true,
18 | "**/*.Mono.csproj" : true
19 | },
20 | "search.exclude": {
21 | "**/.build": true,
22 | "**/.nuget": true,
23 | "**/.vs": true,
24 | "**/docs": true,
25 | "**/packages": true,
26 | "**/bin": true,
27 | "**/obj": true,
28 | "**/*.DotSettings": true,
29 | "**/*.sln": true,
30 | "**/tests/" : true,
31 | "**/Titanium.Web.Proxy.Examples.Wpf/" : true,
32 | "**/*.Basic.csproj/": true,
33 | "**/*.Docs.csproj/": true,
34 | "**/*.Proxy.csproj/": true,
35 | "**/*.Mono.csproj" : true
36 | }
37 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | {
2 | "version": "2.0.0",
3 | "tasks": [
4 | {
5 | "label": "build-basic-example-netcore-debug",
6 | "type": "process",
7 | "command": "dotnet",
8 | "args": ["build","${workspaceFolder}/examples/Titanium.Web.Proxy.Examples.Basic/Titanium.Web.Proxy.Examples.Basic.NetCore.csproj"],
9 | "problemMatcher": "$msCompile",
10 | "group": {
11 | "kind": "build",
12 | "isDefault": true
13 | }
14 | },
15 | {
16 | "label": "build-basic-example-netcore-release",
17 | "type": "process",
18 | "command": "dotnet",
19 | "args": ["build","${workspaceFolder}/examples/Titanium.Web.Proxy.Examples.Basic/Titanium.Web.Proxy.Examples.Basic.NetCore.csproj", "-c", "Release"],
20 | "problemMatcher": "$msCompile"
21 | }
22 | ]
23 | }
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 titanium007
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
23 |
--------------------------------------------------------------------------------
/NuGet.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | Doneness:
2 | - [ ] Build is okay - I made sure that this change is building successfully.
3 | - [ ] No Bugs - I made sure that this change is working properly as expected. It doesn't have any bugs that you are aware of.
4 | - [ ] Branching - If this is not a hotfix, I am making this request against the develop branch
5 |
--------------------------------------------------------------------------------
/_config.yml:
--------------------------------------------------------------------------------
1 | baseurl: /Titanium-Web-Proxy
2 |
--------------------------------------------------------------------------------
/docs/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/docs/favicon.ico
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.eot:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/docs/fonts/glyphicons-halflings-regular.eot
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/docs/fonts/glyphicons-halflings-regular.ttf
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.woff:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/docs/fonts/glyphicons-halflings-regular.woff
--------------------------------------------------------------------------------
/docs/fonts/glyphicons-halflings-regular.woff2:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/docs/fonts/glyphicons-halflings-regular.woff2
--------------------------------------------------------------------------------
/docs/logo.svg:
--------------------------------------------------------------------------------
1 |
2 |
4 |
26 |
--------------------------------------------------------------------------------
/docs/search-stopwords.json:
--------------------------------------------------------------------------------
1 | [
2 | "a",
3 | "able",
4 | "about",
5 | "across",
6 | "after",
7 | "all",
8 | "almost",
9 | "also",
10 | "am",
11 | "among",
12 | "an",
13 | "and",
14 | "any",
15 | "are",
16 | "as",
17 | "at",
18 | "be",
19 | "because",
20 | "been",
21 | "but",
22 | "by",
23 | "can",
24 | "cannot",
25 | "could",
26 | "dear",
27 | "did",
28 | "do",
29 | "does",
30 | "either",
31 | "else",
32 | "ever",
33 | "every",
34 | "for",
35 | "from",
36 | "get",
37 | "got",
38 | "had",
39 | "has",
40 | "have",
41 | "he",
42 | "her",
43 | "hers",
44 | "him",
45 | "his",
46 | "how",
47 | "however",
48 | "i",
49 | "if",
50 | "in",
51 | "into",
52 | "is",
53 | "it",
54 | "its",
55 | "just",
56 | "least",
57 | "let",
58 | "like",
59 | "likely",
60 | "may",
61 | "me",
62 | "might",
63 | "most",
64 | "must",
65 | "my",
66 | "neither",
67 | "no",
68 | "nor",
69 | "not",
70 | "of",
71 | "off",
72 | "often",
73 | "on",
74 | "only",
75 | "or",
76 | "other",
77 | "our",
78 | "own",
79 | "rather",
80 | "said",
81 | "say",
82 | "says",
83 | "she",
84 | "should",
85 | "since",
86 | "so",
87 | "some",
88 | "than",
89 | "that",
90 | "the",
91 | "their",
92 | "them",
93 | "then",
94 | "there",
95 | "these",
96 | "they",
97 | "this",
98 | "tis",
99 | "to",
100 | "too",
101 | "twas",
102 | "us",
103 | "wants",
104 | "was",
105 | "we",
106 | "were",
107 | "what",
108 | "when",
109 | "where",
110 | "which",
111 | "while",
112 | "who",
113 | "whom",
114 | "why",
115 | "will",
116 | "with",
117 | "would",
118 | "yet",
119 | "you",
120 | "your"
121 | ]
122 |
--------------------------------------------------------------------------------
/docs/styles/main.css:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/docs/styles/main.css
--------------------------------------------------------------------------------
/docs/styles/main.js:
--------------------------------------------------------------------------------
1 | // Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE file in the project root for full license information.
2 |
--------------------------------------------------------------------------------
/docs/styles/search-worker.js:
--------------------------------------------------------------------------------
1 | (function () {
2 | importScripts('lunr.min.js');
3 |
4 | var lunrIndex;
5 |
6 | var stopWords = null;
7 | var searchData = {};
8 |
9 | lunr.tokenizer.separator = /[\s\-\.\(\)]+/;
10 |
11 | var stopWordsRequest = new XMLHttpRequest();
12 | stopWordsRequest.open('GET', '../search-stopwords.json');
13 | stopWordsRequest.onload = function () {
14 | if (this.status != 200) {
15 | return;
16 | }
17 | stopWords = JSON.parse(this.responseText);
18 | buildIndex();
19 | }
20 | stopWordsRequest.send();
21 |
22 | var searchDataRequest = new XMLHttpRequest();
23 |
24 | searchDataRequest.open('GET', '../index.json');
25 | searchDataRequest.onload = function () {
26 | if (this.status != 200) {
27 | return;
28 | }
29 | searchData = JSON.parse(this.responseText);
30 |
31 | buildIndex();
32 |
33 | postMessage({ e: 'index-ready' });
34 | }
35 | searchDataRequest.send();
36 |
37 | onmessage = function (oEvent) {
38 | var q = oEvent.data.q;
39 | var hits = lunrIndex.search(q);
40 | var results = [];
41 | hits.forEach(function (hit) {
42 | var item = searchData[hit.ref];
43 | results.push({ 'href': item.href, 'title': item.title, 'keywords': item.keywords });
44 | });
45 | postMessage({ e: 'query-ready', q: q, d: results });
46 | }
47 |
48 | function buildIndex() {
49 | if (stopWords !== null && !isEmpty(searchData)) {
50 | lunrIndex = lunr(function () {
51 | this.pipeline.remove(lunr.stopWordFilter);
52 | this.ref('href');
53 | this.field('title', { boost: 50 });
54 | this.field('keywords', { boost: 20 });
55 |
56 | for (var prop in searchData) {
57 | if (searchData.hasOwnProperty(prop)) {
58 | this.add(searchData[prop]);
59 | }
60 | }
61 |
62 | var docfxStopWordFilter = lunr.generateStopWordFilter(stopWords);
63 | lunr.Pipeline.registerFunction(docfxStopWordFilter, 'docfxStopWordFilter');
64 | this.pipeline.add(docfxStopWordFilter);
65 | this.searchPipeline.add(docfxStopWordFilter);
66 | });
67 | }
68 | }
69 |
70 | function isEmpty(obj) {
71 | if(!obj) return true;
72 |
73 | for (var prop in obj) {
74 | if (obj.hasOwnProperty(prop))
75 | return false;
76 | }
77 |
78 | return true;
79 | }
80 | })();
81 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/Capture.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/examples/Titanium.Web.Proxy.Examples.Basic/Capture.PNG
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/Helpers/ConsoleHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Titanium.Web.Proxy.Examples.Basic.Helpers
5 | {
6 | ///
7 | /// Adapted from
8 | /// http://stackoverflow.com/questions/13656846/how-to-programmatic-disable-c-sharp-console-applications-quick-edit-mode
9 | ///
10 | internal static class ConsoleHelper
11 | {
12 | private const uint EnableQuickEdit = 0x0040;
13 |
14 | // STD_INPUT_HANDLE (DWORD): -10 is the standard input device.
15 | private const int StdInputHandle = -10;
16 |
17 | [DllImport("kernel32.dll", SetLastError = true)]
18 | private static extern IntPtr GetStdHandle(int nStdHandle);
19 |
20 | [DllImport("kernel32.dll")]
21 | private static extern bool GetConsoleMode(IntPtr hConsoleHandle, out uint lpMode);
22 |
23 | [DllImport("kernel32.dll")]
24 | private static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);
25 |
26 | internal static bool DisableQuickEditMode()
27 | {
28 | var consoleHandle = GetStdHandle(StdInputHandle);
29 |
30 | // get current console mode
31 | if (!GetConsoleMode(consoleHandle, out var consoleMode))
32 | // ERROR: Unable to get console mode.
33 | return false;
34 |
35 | // Clear the quick edit bit in the mode flags
36 | consoleMode &= ~EnableQuickEdit;
37 |
38 | // set the new mode
39 | if (!SetConsoleMode(consoleHandle, consoleMode))
40 | // ERROR: Unable to set console mode
41 | return false;
42 |
43 | return true;
44 | }
45 | }
46 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Titanium.Web.Proxy.Examples.Basic.Helpers;
3 | using Titanium.Web.Proxy.Helpers;
4 |
5 | namespace Titanium.Web.Proxy.Examples.Basic
6 | {
7 | public class Program
8 | {
9 | private static readonly ProxyTestController controller = new ProxyTestController();
10 |
11 | public static void Main(string[] args)
12 | {
13 | if (RunTime.IsWindows)
14 | // fix console hang due to QuickEdit mode
15 | ConsoleHelper.DisableQuickEditMode();
16 |
17 | // Start proxy controller
18 | controller.StartProxy();
19 |
20 | Console.WriteLine("Hit any key to exit..");
21 | Console.WriteLine();
22 | Console.Read();
23 |
24 | controller.Stop();
25 | }
26 | }
27 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/ProxyEventArgsBaseExtensions.cs:
--------------------------------------------------------------------------------
1 | using Titanium.Web.Proxy.EventArguments;
2 |
3 | namespace Titanium.Web.Proxy.Examples.Basic
4 | {
5 | public static class ProxyEventArgsBaseExtensions
6 | {
7 | public static SampleClientState GetState(this ProxyEventArgsBase args)
8 | {
9 | if (args.ClientUserData == null) args.ClientUserData = new SampleClientState();
10 |
11 | return (SampleClientState)args.ClientUserData;
12 | }
13 | }
14 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/SampleClientState.cs:
--------------------------------------------------------------------------------
1 | using System.Text;
2 |
3 | namespace Titanium.Web.Proxy.Examples.Basic
4 | {
5 | public class SampleClientState
6 | {
7 | public StringBuilder PipelineInfo { get; } = new StringBuilder();
8 | }
9 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Basic/Titanium.Web.Proxy.Examples.Basic.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net48;net60
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
7 |
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 | 8080
35 |
36 |
37 | True
38 |
39 |
40 | NoCheck
41 |
42 |
43 | 30
44 |
45 |
46 | False
47 |
48 |
49 | True
50 |
51 |
52 | True
53 |
54 |
55 | False
56 |
57 |
58 | False
59 |
60 |
61 | 2
62 |
63 |
64 | True
65 |
66 |
67 | 30
68 |
69 |
70 | True
71 |
72 |
73 | False
74 |
75 |
76 | True
77 |
78 |
79 | -1
80 |
81 |
82 | False
83 |
84 |
85 | True
86 |
87 |
88 |
89 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/Program.cs:
--------------------------------------------------------------------------------
1 | using System.ServiceProcess;
2 |
3 | namespace WindowsServiceExample
4 | {
5 | internal static class Program
6 | {
7 | ///
8 | /// The main entry point for the application.
9 | ///
10 | private static void Main()
11 | {
12 | ServiceBase[] servicesToRun;
13 | servicesToRun = new ServiceBase[]
14 | {
15 | new ProxyService()
16 | };
17 | ServiceBase.Run(servicesToRun);
18 | }
19 | }
20 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.InteropServices;
3 |
4 | // General Information about an assembly is controlled through the following
5 | // set of attributes. Change these attribute values to modify the information
6 | // associated with an assembly.
7 | [assembly: AssemblyTitle("WindowsServiceExample")]
8 | [assembly: AssemblyDescription("")]
9 | [assembly: AssemblyConfiguration("")]
10 | [assembly: AssemblyCompany("")]
11 | [assembly: AssemblyProduct("WindowsServiceExample")]
12 | [assembly: AssemblyCopyright("Copyright © 2019")]
13 | [assembly: AssemblyTrademark("")]
14 | [assembly: AssemblyCulture("")]
15 |
16 | // Setting ComVisible to false makes the types in this assembly not visible
17 | // to COM components. If you need to access a type in this assembly from
18 | // COM, set the ComVisible attribute to true on that type.
19 | [assembly: ComVisible(false)]
20 |
21 | // The following GUID is for the ID of the typelib if this project is exposed to COM
22 | [assembly: Guid("63635f50-7d6f-4a93-84c6-04cf9d2754c5")]
23 |
24 | // Version information for an assembly consists of the following four values:
25 | //
26 | // Major Version
27 | // Minor Version
28 | // Build Number
29 | // Revision
30 | //
31 | // You can specify all the values or you can default the Build and Revision Numbers
32 | // by using the '*' as shown below:
33 | // [assembly: AssemblyVersion("1.0.*")]
34 | [assembly: AssemblyVersion("1.0.0.0")]
35 | [assembly: AssemblyFileVersion("1.0.0.0")]
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | 8080
7 |
8 |
9 | True
10 |
11 |
12 | NoCheck
13 |
14 |
15 | 30
16 |
17 |
18 | False
19 |
20 |
21 | True
22 |
23 |
24 | True
25 |
26 |
27 | False
28 |
29 |
30 | False
31 |
32 |
33 | 2
34 |
35 |
36 | True
37 |
38 |
39 | 30
40 |
41 |
42 | True
43 |
44 |
45 | False
46 |
47 |
48 | True
49 |
50 |
51 | -1
52 |
53 |
54 | False
55 |
56 |
57 | True
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/ProxyService.Designer.cs:
--------------------------------------------------------------------------------
1 | namespace WindowsServiceExample
2 | {
3 | partial class ProxyService
4 | {
5 | ///
6 | /// Required designer variable.
7 | ///
8 | private System.ComponentModel.IContainer components = null;
9 |
10 | ///
11 | /// Clean up any resources being used.
12 | ///
13 | /// true if managed resources should be disposed; otherwise, false.
14 | protected override void Dispose(bool disposing)
15 | {
16 | if (disposing && (components != null))
17 | {
18 | components.Dispose();
19 | }
20 | base.Dispose(disposing);
21 | }
22 |
23 | #region Component Designer generated code
24 |
25 | ///
26 | /// Required method for Designer support - do not modify
27 | /// the contents of this method with the code editor.
28 | ///
29 | private void InitializeComponent()
30 | {
31 | this.ProxyServiceEventLog = new System.Diagnostics.EventLog();
32 | ((System.ComponentModel.ISupportInitialize)(this.ProxyServiceEventLog)).BeginInit();
33 | //
34 | // ProxyServiceEventLog
35 | //
36 | this.ProxyServiceEventLog.Log = "Application";
37 | this.ProxyServiceEventLog.Source = "ProxyService";
38 | //
39 | // ProxyService
40 | //
41 | this.ServiceName = "ProxyService";
42 | ((System.ComponentModel.ISupportInitialize)(this.ProxyServiceEventLog)).EndInit();
43 |
44 | }
45 |
46 | #endregion
47 | private System.Diagnostics.EventLog ProxyServiceEventLog;
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/install.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # There are several ways to install a service on windows, this methods uses PowerShell.
3 | #
4 |
5 | # Self-elevate the script if required.
6 | if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
7 | if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
8 | $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
9 | Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
10 | Exit
11 | }
12 | }
13 |
14 | # This is the name of the service and will also show as the display name in services.msc.
15 | [String] $ServiceName = "ProxyService"
16 | # This is the name of the executable of the service.
17 | [String] $ServiceExeName = "WindowsServiceExample.exe"
18 | # Use the directory of the runnign script and the service executable name to create a full path.
19 | [String] $ServiceExePath = [string]($PSScriptRoot) + "\" + $ServiceExeName
20 | # Get the information for the executable file.
21 | [IO.FileInfo] $ExeFileInfo = $ServiceExePath
22 |
23 | # Check if the executable file exists.
24 | if(!$ExeFileInfo.Exists) {
25 | # OH NO the executable was not found.
26 | Write-host "Service executable not found $ServiceExePath"
27 | Write-Host "Please fix and try again."
28 |
29 | }else{
30 | # Lets install the service.
31 | Write-host "Installing service $ServiceExePath"
32 | New-Service -Name $ServiceName -BinaryPathName $ServiceExePath -Description "HTTP proxy service" -StartupType "Automatic"
33 | # Service installed, lets start it.
34 | Start-Service -Name $ServiceName
35 | }
36 |
37 | Read-Host -Prompt "Press Enter to exit"
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.WindowsService/remove.ps1:
--------------------------------------------------------------------------------
1 | # Self-elevate the script if required.
2 | if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
3 | if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) {
4 | $CommandLine = "-File `"" + $MyInvocation.MyCommand.Path + "`" " + $MyInvocation.UnboundArguments
5 | Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList $CommandLine
6 | Exit
7 | }
8 | }
9 |
10 | # This is the name of the service and will also show as the display name in services.msc.
11 | # This must match what the service was installed as.
12 | $ServiceName = "ProxyService"
13 |
14 | # Make sure the service is stopped.
15 | Stop-Service -Name $ServiceName
16 | # Remove the service, this doesnt always work. (Requires PS 6+)
17 | Remove-Service -Name $ServiceName
18 | # Make sure the service gets unregistered even if the last command failed.
19 | sc.exe delete $ServiceName
20 |
21 | Read-Host -Prompt "Press Enter to exit"
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/App.xaml:
--------------------------------------------------------------------------------
1 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | namespace Titanium.Web.Proxy.Examples.Wpf
4 | {
5 | ///
6 | /// Interaction logic for App.xaml
7 | ///
8 | public partial class App : Application
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/Capture.PNG:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/justcoding121/titanium-web-proxy/902504a324425e4e49fc5ba604c2b7fa172e68ce/examples/Titanium.Web.Proxy.Examples.Wpf/Capture.PNG
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/MainWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
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 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/ObservableCollectionEx.cs:
--------------------------------------------------------------------------------
1 | using System.Collections.ObjectModel;
2 | using System.Collections.Specialized;
3 |
4 | namespace Titanium.Web.Proxy.Examples.Wpf
5 | {
6 | public class ObservableCollectionEx : ObservableCollection
7 | {
8 | private bool notificationSuppressed;
9 | private bool suppressNotification;
10 |
11 | public bool SuppressNotification
12 | {
13 | get => suppressNotification;
14 | set
15 | {
16 | suppressNotification = value;
17 | if (suppressNotification == false && notificationSuppressed)
18 | {
19 | OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
20 | notificationSuppressed = false;
21 | }
22 | }
23 | }
24 |
25 | protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
26 | {
27 | if (SuppressNotification)
28 | {
29 | notificationSuppressed = true;
30 | return;
31 | }
32 |
33 | base.OnCollectionChanged(e);
34 | }
35 | }
36 | }
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/Properties/Resources.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Titanium.Web.Proxy.Examples.Wpf.Properties {
12 | using System;
13 |
14 |
15 | ///
16 | /// A strongly-typed resource class, for looking up localized strings, etc.
17 | ///
18 | // This class was auto-generated by the StronglyTypedResourceBuilder
19 | // class via a tool like ResGen or Visual Studio.
20 | // To add or remove a member, edit your .ResX file then rerun ResGen
21 | // with the /str option, or rebuild your VS project.
22 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
23 | [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
24 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
25 | internal class Resources {
26 |
27 | private static global::System.Resources.ResourceManager resourceMan;
28 |
29 | private static global::System.Globalization.CultureInfo resourceCulture;
30 |
31 | [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
32 | internal Resources() {
33 | }
34 |
35 | ///
36 | /// Returns the cached ResourceManager instance used by this class.
37 | ///
38 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
39 | internal static global::System.Resources.ResourceManager ResourceManager {
40 | get {
41 | if (object.ReferenceEquals(resourceMan, null)) {
42 | global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Titanium.Web.Proxy.Examples.Wpf.Properties.Resources", typeof(Resources).Assembly);
43 | resourceMan = temp;
44 | }
45 | return resourceMan;
46 | }
47 | }
48 |
49 | ///
50 | /// Overrides the current thread's CurrentUICulture property for all
51 | /// resource lookups using this strongly typed resource class.
52 | ///
53 | [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
54 | internal static global::System.Globalization.CultureInfo Culture {
55 | get {
56 | return resourceCulture;
57 | }
58 | set {
59 | resourceCulture = value;
60 | }
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/Properties/Settings.Designer.cs:
--------------------------------------------------------------------------------
1 | //------------------------------------------------------------------------------
2 | //
3 | // This code was generated by a tool.
4 | // Runtime Version:4.0.30319.42000
5 | //
6 | // Changes to this file may cause incorrect behavior and will be lost if
7 | // the code is regenerated.
8 | //
9 | //------------------------------------------------------------------------------
10 |
11 | namespace Titanium.Web.Proxy.Examples.Wpf.Properties {
12 |
13 |
14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.1.0.0")]
16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
17 |
18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
19 |
20 | public static Settings Default {
21 | get {
22 | return defaultInstance;
23 | }
24 | }
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/Properties/Settings.settings:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/examples/Titanium.Web.Proxy.Examples.Wpf/Titanium.Web.Proxy.Examples.Wpf.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WinExe
5 | net48;net60-windows
6 | true
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | True
20 | True
21 | Resources.resx
22 |
23 |
24 | True
25 | Settings.settings
26 | True
27 |
28 |
29 | ResXFileCodeGenerator
30 | Resources.Designer.cs
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/omnisharp.json:
--------------------------------------------------------------------------------
1 | {
2 | "fileOptions": {
3 | "excludeSearchPatterns": [
4 | "**/*.sln",
5 | "**/*.Docs.csproj",
6 | "**/tests/",
7 | "**/Titanium.Web.Proxy.Examples.Wpf/",
8 | "**/*.Basic.csproj",
9 | "**/*.Proxy.csproj",
10 | "**/*.Mono.csproj"
11 | ]
12 | }
13 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy.Docs.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29102.190
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Titanium.Web.Proxy", "Titanium.Web.Proxy\Titanium.Web.Proxy.csproj", "{91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Debug|x64 = Debug|x64
12 | Release|Any CPU = Release|Any CPU
13 | Release|x64 = Release|x64
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Debug|x64.ActiveCfg = Debug|Any CPU
19 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Debug|x64.Build.0 = Debug|Any CPU
20 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
21 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Release|Any CPU.Build.0 = Release|Any CPU
22 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Release|x64.ActiveCfg = Release|Any CPU
23 | {91018B6D-A7A9-45BE-9CB3-79CBB8B169A6}.Release|x64.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | EnterpriseLibraryConfigurationToolBinariesPath = .1.505.2\lib\NET35
30 | SolutionGuid = {625C1EB5-44CF-47DE-A85A-B4C8C40ED90A}
31 | EndGlobalSection
32 | EndGlobal
33 |
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Certificates/Cache/CachedCertificate.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Security.Cryptography.X509Certificates;
3 |
4 | namespace Titanium.Web.Proxy.Network;
5 |
6 | ///
7 | /// An object that holds the cached certificate
8 | ///
9 | internal sealed class CachedCertificate
10 | {
11 | public CachedCertificate(X509Certificate2 certificate)
12 | {
13 | Certificate = certificate;
14 | }
15 |
16 | internal X509Certificate2 Certificate { get; }
17 |
18 | ///
19 | /// Last time this certificate was used.
20 | /// Useful in determining its cache lifetime.
21 | ///
22 | internal DateTime LastAccess { get; set; }
23 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Certificates/Cache/ICertificateCache.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography.X509Certificates;
2 |
3 | namespace Titanium.Web.Proxy.Network;
4 |
5 | public interface ICertificateCache
6 | {
7 | ///
8 | /// Loads the root certificate from the storage.
9 | ///
10 | X509Certificate2? LoadRootCertificate(string pathOrName, string password, X509KeyStorageFlags storageFlags);
11 |
12 | ///
13 | /// Saves the root certificate to the storage.
14 | ///
15 | void SaveRootCertificate(string pathOrName, string password, X509Certificate2 certificate);
16 |
17 | ///
18 | /// Loads certificate from the storage. Returns true if certificate does not exist.
19 | ///
20 | X509Certificate2? LoadCertificate(string subjectName, X509KeyStorageFlags storageFlags);
21 |
22 | ///
23 | /// Stores certificate into the storage.
24 | ///
25 | void SaveCertificate(string subjectName, X509Certificate2 certificate);
26 |
27 | ///
28 | /// Clears the storage.
29 | ///
30 | void Clear();
31 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Certificates/Makers/ICertificateMaker.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography.X509Certificates;
2 |
3 | namespace Titanium.Web.Proxy.Network.Certificate;
4 |
5 | ///
6 | /// Abstract interface for different Certificate Maker Engines
7 | ///
8 | internal interface ICertificateMaker
9 | {
10 | X509Certificate2 MakeCertificate(string sSubjectCn, X509Certificate2? signingCert);
11 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Compression/CompressionFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.IO.Compression;
4 |
5 | namespace Titanium.Web.Proxy.Compression
6 | {
7 | ///
8 | /// A factory to generate the compression methods based on the type of compression
9 | ///
10 | internal static class CompressionFactory
11 | {
12 | internal static Stream Create(HttpCompression type, Stream stream, bool leaveOpen = true)
13 | {
14 | return type switch
15 | {
16 | HttpCompression.Gzip => new GZipStream(stream, CompressionMode.Compress, leaveOpen),
17 | HttpCompression.Deflate => new DeflateStream(stream, CompressionMode.Compress, leaveOpen),
18 | HttpCompression.Brotli => new BrotliSharpLib.BrotliStream(stream, CompressionMode.Compress, leaveOpen),
19 | _ => throw new Exception($"Unsupported compression mode: {type}")
20 | };
21 | }
22 | }
23 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Compression/DecompressionFactory.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.IO.Compression;
4 |
5 | namespace Titanium.Web.Proxy.Compression;
6 |
7 | ///
8 | /// A factory to generate the de-compression methods based on the type of compression
9 | ///
10 | internal class DecompressionFactory
11 | {
12 | internal static Stream Create(HttpCompression type, Stream stream, bool leaveOpen = true)
13 | {
14 | return type switch
15 | {
16 | HttpCompression.Gzip => new GZipStream(stream, CompressionMode.Decompress, leaveOpen),
17 | HttpCompression.Deflate => new DeflateStream(stream, CompressionMode.Decompress, leaveOpen),
18 | HttpCompression.Brotli => new BrotliSharpLib.BrotliStream(stream, CompressionMode.Decompress, leaveOpen),
19 | _ => throw new Exception($"Unsupported decompression mode: {type}")
20 | };
21 | }
22 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/BeforeBodyWriteEventArgs.cs:
--------------------------------------------------------------------------------
1 | #if DEBUG
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 |
8 | namespace Titanium.Web.Proxy.EventArguments
9 | {
10 |
11 | public class BeforeBodyWriteEventArgs : ProxyEventArgsBase
12 | {
13 | internal BeforeBodyWriteEventArgs(SessionEventArgs session, byte[] bodyBytes, bool isChunked, bool isLastChunk) : base(session.Server, session.ClientConnection)
14 | {
15 | Session = session;
16 | BodyBytes = bodyBytes;
17 | IsChunked = isChunked;
18 | IsLastChunk = isLastChunk;
19 | }
20 |
21 |
22 | ///
23 | /// The session arguments.
24 | ///
25 | public SessionEventArgs Session { get; }
26 |
27 | ///
28 | /// Indicates whether body is written chunked stream.
29 | /// If this is true, BeforeRequestBodySend or BeforeResponseBodySend will be called until IsLastChunk is false.
30 | ///
31 | public bool IsChunked { get; }
32 |
33 | ///
34 | /// Indicates if this is the last chunk from client or server stream, when request is chunked.
35 | /// Override this property to true if there are more bytes to write.
36 | ///
37 | public bool IsLastChunk { get; set; }
38 |
39 | ///
40 | /// The bytes about to be written. If IsChunked is true, this will be a chunk of the bytes to be written.
41 | /// Override this property with custom bytes if needed, and adjust IsLastChunk accordingly.
42 | ///
43 | public byte[] BodyBytes { get; set; }
44 | }
45 | }
46 | #endif
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/BeforeSslAuthenticateEventArgs.cs:
--------------------------------------------------------------------------------
1 | using System.Threading;
2 | using Titanium.Web.Proxy.Network.Tcp;
3 |
4 | namespace Titanium.Web.Proxy.EventArguments;
5 |
6 | ///
7 | /// This is used in transparent endpoint before authenticating client.
8 | ///
9 | public class BeforeSslAuthenticateEventArgs : ProxyEventArgsBase
10 | {
11 | internal readonly CancellationTokenSource TaskCancellationSource;
12 |
13 | internal BeforeSslAuthenticateEventArgs(ProxyServer server, TcpClientConnection clientConnection,
14 | CancellationTokenSource taskCancellationSource, string sniHostName) : base(server, clientConnection)
15 | {
16 | TaskCancellationSource = taskCancellationSource;
17 | SniHostName = sniHostName;
18 | ForwardHttpsHostName = sniHostName;
19 | }
20 |
21 | ///
22 | /// The server name indication hostname if available.
23 | /// Otherwise the GenericCertificateName property of TransparentEndPoint.
24 | ///
25 | public string SniHostName { get; }
26 |
27 | ///
28 | /// Should we decrypt the SSL request?
29 | /// If true we decrypt with fake certificate.
30 | /// If false we relay the connection to the hostname mentioned in SniHostname.
31 | ///
32 | public bool DecryptSsl { get; set; } = true;
33 |
34 | ///
35 | /// We need to know the server hostname we are forwarding the request to.
36 | /// By default its the SNI hostname indicated in SSL handshake, when SNI is available.
37 | /// When SNI is not available, it will use the GenericCertificateName of TransparentEndPoint.
38 | /// This property is used only when DecryptSsl or when BeforeSslAuthenticateEventArgs.DecryptSsl is false.
39 | /// When DecryptSsl is true, we need to explicitly set the Forwarded host and port by setting
40 | /// e.HttpClient.Request.Url inside BeforeRequest event handler.
41 | ///
42 | public string ForwardHttpsHostName { get; set; }
43 |
44 | ///
45 | /// We need to know the server port we are forwarding the request to.
46 | /// By default its the standard https port, 443.
47 | /// This property is used only when DecryptSsl or when BeforeSslAuthenticateEventArgs.DecryptSsl is false.
48 | /// When DecryptSsl is true, we need to explicitly set the Forwarded host and port by setting
49 | /// e.HttpClient.Request.Url inside BeforeRequest event handler.
50 | ///
51 | public int ForwardHttpsPort { get; set; } = 443;
52 |
53 | ///
54 | /// Terminate the request abruptly by closing client/server connections.
55 | ///
56 | public void TerminateSession()
57 | {
58 | TaskCancellationSource.Cancel();
59 | }
60 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/CertificateSelectionEventArgs.cs:
--------------------------------------------------------------------------------
1 | using System.Security.Cryptography.X509Certificates;
2 |
3 | namespace Titanium.Web.Proxy.EventArguments;
4 |
5 | ///
6 | /// An argument passed on to user for client certificate selection during mutual SSL authentication.
7 | ///
8 | public class CertificateSelectionEventArgs : ProxyEventArgsBase
9 | {
10 | public CertificateSelectionEventArgs(SessionEventArgsBase session, string targetHost,
11 | X509CertificateCollection localCertificates, X509Certificate remoteCertificate, string[] acceptableIssuers) :
12 | base(session.Server, session.ClientConnection)
13 | {
14 | Session = session;
15 | TargetHost = targetHost;
16 | LocalCertificates = localCertificates;
17 | RemoteCertificate = remoteCertificate;
18 | AcceptableIssuers = acceptableIssuers;
19 | }
20 |
21 | ///
22 | /// The session.
23 | ///
24 | public SessionEventArgsBase Session { get; }
25 |
26 | ///
27 | /// The remote hostname to which we are authenticating against.
28 | ///
29 | public string TargetHost { get; }
30 |
31 | ///
32 | /// Local certificates in store with matching issuers requested by TargetHost website.
33 | ///
34 | public X509CertificateCollection LocalCertificates { get; }
35 |
36 | ///
37 | /// Certificate of the remote server.
38 | ///
39 | public X509Certificate RemoteCertificate { get; }
40 |
41 | ///
42 | /// Acceptable issuers as listed by remote server.
43 | ///
44 | public string[] AcceptableIssuers { get; }
45 |
46 | ///
47 | /// Client Certificate we selected. Set this value to override.
48 | ///
49 | public X509Certificate? ClientCertificate { get; set; }
50 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/CertificateValidationEventArgs.cs:
--------------------------------------------------------------------------------
1 | using System.Net.Security;
2 | using System.Security.Cryptography.X509Certificates;
3 |
4 | namespace Titanium.Web.Proxy.EventArguments;
5 |
6 | ///
7 | /// An argument passed on to the user for validating the server certificate
8 | /// during SSL authentication.
9 | ///
10 | public class CertificateValidationEventArgs : ProxyEventArgsBase
11 | {
12 | public CertificateValidationEventArgs(SessionEventArgsBase session, X509Certificate certificate, X509Chain chain,
13 | SslPolicyErrors sslPolicyErrors) : base(session.Server, session.ClientConnection)
14 | {
15 | Session = session;
16 | Certificate = certificate;
17 | Chain = chain;
18 | SslPolicyErrors = sslPolicyErrors;
19 | }
20 |
21 | ///
22 | /// The session.
23 | ///
24 | public SessionEventArgsBase Session { get; }
25 |
26 | ///
27 | /// Server certificate.
28 | ///
29 | public X509Certificate Certificate { get; }
30 |
31 | ///
32 | /// Certificate chain.
33 | ///
34 | public X509Chain Chain { get; }
35 |
36 | ///
37 | /// SSL policy errors.
38 | ///
39 | public SslPolicyErrors SslPolicyErrors { get; }
40 |
41 | ///
42 | /// Is the given server certificate valid?
43 | ///
44 | public bool IsValid { get; set; }
45 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/DataEventArgs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Titanium.Web.Proxy.StreamExtended.Network;
4 |
5 | ///
6 | /// Wraps the data sent/received event argument.
7 | ///
8 | public class DataEventArgs : EventArgs
9 | {
10 | public DataEventArgs(byte[] buffer, int offset, int count)
11 | {
12 | Buffer = buffer;
13 | Offset = offset;
14 | Count = count;
15 | }
16 |
17 | ///
18 | /// The buffer with data.
19 | ///
20 | public byte[] Buffer { get; }
21 |
22 | ///
23 | /// Offset in buffer from which valid data begins.
24 | ///
25 | public int Offset { get; }
26 |
27 | ///
28 | /// Length from offset in buffer with valid data.
29 | ///
30 | public int Count { get; }
31 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/EmptyProxyEventArgs.cs:
--------------------------------------------------------------------------------
1 | using Titanium.Web.Proxy.Network.Tcp;
2 |
3 | namespace Titanium.Web.Proxy.EventArguments;
4 |
5 | public class EmptyProxyEventArgs : ProxyEventArgsBase
6 | {
7 | internal EmptyProxyEventArgs(ProxyServer server, TcpClientConnection clientConnection) : base(server,
8 | clientConnection)
9 | {
10 | }
11 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/MultipartRequestPartSentEventArgs.cs:
--------------------------------------------------------------------------------
1 | using Titanium.Web.Proxy.Http;
2 |
3 | namespace Titanium.Web.Proxy.EventArguments;
4 |
5 | ///
6 | /// Class that wraps the multipart sent request arguments.
7 | ///
8 | public class MultipartRequestPartSentEventArgs : ProxyEventArgsBase
9 | {
10 | internal MultipartRequestPartSentEventArgs(SessionEventArgs session, string boundary, HeaderCollection headers) :
11 | base(session.Server, session.ClientConnection)
12 | {
13 | Session = session;
14 | Boundary = boundary;
15 | Headers = headers;
16 | }
17 |
18 | ///
19 | /// The session arguments.
20 | ///
21 | public SessionEventArgs Session { get; }
22 |
23 | ///
24 | /// Boundary.
25 | ///
26 | public string Boundary { get; }
27 |
28 | ///
29 | /// The header collection.
30 | ///
31 | public HeaderCollection Headers { get; }
32 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/ProxyEventArgsBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Titanium.Web.Proxy.Network.Tcp;
3 |
4 | namespace Titanium.Web.Proxy.EventArguments;
5 |
6 | ///
7 | /// The base event arguments
8 | ///
9 | ///
10 | public abstract class ProxyEventArgsBase : EventArgs
11 | {
12 | private readonly TcpClientConnection clientConnection;
13 | internal readonly ProxyServer Server;
14 |
15 | internal ProxyEventArgsBase(ProxyServer server, TcpClientConnection clientConnection)
16 | {
17 | this.clientConnection = clientConnection;
18 | Server = server;
19 | }
20 |
21 | public object ClientUserData
22 | {
23 | get => clientConnection.ClientUserData;
24 | set => clientConnection.ClientUserData = value;
25 | }
26 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/TransformationMode.cs:
--------------------------------------------------------------------------------
1 | namespace Titanium.Web.Proxy.EventArguments;
2 |
3 | internal enum TransformationMode
4 | {
5 | None,
6 |
7 | ///
8 | /// Removes the chunked encoding
9 | ///
10 | RemoveChunked,
11 |
12 | ///
13 | /// Uncompress the body (this also removes the chunked encoding if exists)
14 | ///
15 | Uncompress
16 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/EventArguments/TunnelConnectEventArgs.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading;
3 | using Titanium.Web.Proxy.Helpers;
4 | using Titanium.Web.Proxy.Http;
5 | using Titanium.Web.Proxy.Models;
6 | using Titanium.Web.Proxy.StreamExtended.Network;
7 |
8 | namespace Titanium.Web.Proxy.EventArguments;
9 |
10 | ///
11 | /// A class that wraps the state when a tunnel connect event happen for Explicit endpoints.
12 | ///
13 | public class TunnelConnectSessionEventArgs : SessionEventArgsBase
14 | {
15 | private bool? isHttpsConnect;
16 |
17 | internal TunnelConnectSessionEventArgs(ProxyServer server, ProxyEndPoint endPoint, ConnectRequest connectRequest,
18 | HttpClientStream clientStream, CancellationTokenSource cancellationTokenSource)
19 | : base(server, endPoint, clientStream, connectRequest, connectRequest, cancellationTokenSource)
20 | {
21 | }
22 |
23 | ///
24 | /// Should we decrypt the Ssl or relay it to server?
25 | /// Default is true.
26 | ///
27 | public bool DecryptSsl { get; set; } = true;
28 |
29 | ///
30 | /// When set to true it denies the connect request with a Forbidden status.
31 | ///
32 | public bool DenyConnect { get; set; }
33 |
34 | ///
35 | /// Is this a connect request to secure HTTP server? Or is it to some other protocol.
36 | ///
37 | public bool IsHttpsConnect
38 | {
39 | get => isHttpsConnect ??
40 | throw new Exception("The value of this property is known in the BeforeTunnelConnectResponse event");
41 |
42 | internal set => isHttpsConnect = value;
43 | }
44 |
45 | ///
46 | /// Fired when decrypted data is sent within this session to server/client.
47 | ///
48 | public event EventHandler? DecryptedDataSent;
49 |
50 | ///
51 | /// Fired when decrypted data is received within this session from client/server.
52 | ///
53 | public event EventHandler? DecryptedDataReceived;
54 |
55 | internal void OnDecryptedDataSent(byte[] buffer, int offset, int count)
56 | {
57 | try
58 | {
59 | DecryptedDataSent?.Invoke(this, new DataEventArgs(buffer, offset, count));
60 | }
61 | catch (Exception ex)
62 | {
63 | OnException(new Exception("Exception thrown in user event", ex));
64 | }
65 | }
66 |
67 | internal void OnDecryptedDataReceived(byte[] buffer, int offset, int count)
68 | {
69 | try
70 | {
71 | DecryptedDataReceived?.Invoke(this, new DataEventArgs(buffer, offset, count));
72 | }
73 | catch (Exception ex)
74 | {
75 | OnException(new Exception("Exception thrown in user event", ex));
76 | }
77 | }
78 |
79 | ~TunnelConnectSessionEventArgs()
80 | {
81 | #if DEBUG
82 | // Finalizer should not be called
83 | System.Diagnostics.Debugger.Break();
84 | #endif
85 |
86 | Dispose(false);
87 | }
88 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Exceptions/BodyNotFoundException.cs:
--------------------------------------------------------------------------------
1 | namespace Titanium.Web.Proxy.Exceptions;
2 |
3 | ///
4 | /// An exception thrown when body is unexpectedly empty.
5 | ///
6 | public class BodyNotFoundException : ProxyException
7 | {
8 | ///
9 | /// Constructor.
10 | ///
11 | ///
12 | internal BodyNotFoundException(string message) : base(message)
13 | {
14 | }
15 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Exceptions/ProxyAuthorizationException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using Titanium.Web.Proxy.EventArguments;
4 | using Titanium.Web.Proxy.Models;
5 |
6 | namespace Titanium.Web.Proxy.Exceptions;
7 |
8 | ///
9 | /// Proxy authorization exception.
10 | ///
11 | public class ProxyAuthorizationException : ProxyException
12 | {
13 | ///
14 | /// Initializes a new instance of the class.
15 | ///
16 | /// Exception message.
17 | /// The instance containing the event data.
18 | /// Inner exception associated to upstream proxy authorization
19 | /// Http's headers associated
20 | internal ProxyAuthorizationException(string message, SessionEventArgsBase session, Exception innerException,
21 | IEnumerable headers) : base(message, innerException)
22 | {
23 | Session = session;
24 | Headers = headers;
25 | }
26 |
27 | ///
28 | /// The current session within which this error happened.
29 | ///
30 | public SessionEventArgsBase Session { get; }
31 |
32 | ///
33 | /// Headers associated with the authorization exception.
34 | ///
35 | public IEnumerable Headers { get; }
36 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Exceptions/ProxyConnectException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Titanium.Web.Proxy.EventArguments;
3 |
4 | namespace Titanium.Web.Proxy.Exceptions;
5 |
6 | ///
7 | /// Proxy Connection exception.
8 | ///
9 | public class ProxyConnectException : ProxyException
10 | {
11 | ///
12 | /// Initializes a new instance of the class.
13 | ///
14 | /// Message for this exception
15 | /// Associated inner exception
16 | ///
17 | /// Instance of associated to the
18 | /// exception
19 | ///
20 | internal ProxyConnectException(string message, Exception innerException, SessionEventArgsBase session) : base(
21 | message, innerException)
22 | {
23 | Session = session;
24 | }
25 |
26 | ///
27 | /// Gets session info associated to the exception.
28 | ///
29 | ///
30 | /// This object properties should not be edited.
31 | ///
32 | public SessionEventArgsBase Session { get; }
33 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Exceptions/ProxyException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Titanium.Web.Proxy.Exceptions;
4 |
5 | ///
6 | /// Base class exception associated with this proxy server.
7 | ///
8 | public abstract class ProxyException : Exception
9 | {
10 | ///
11 | /// Initializes a new instance of the class.
12 | /// - must be invoked by derived classes' constructors
13 | ///
14 | /// Exception message
15 | protected ProxyException(string message) : base(message)
16 | {
17 | }
18 |
19 | ///
20 | /// Initializes a new instance of the class.
21 | /// - must be invoked by derived classes' constructors
22 | ///
23 | /// Exception message
24 | /// Inner exception associated
25 | protected ProxyException(string message, Exception? innerException) : base(message, innerException)
26 | {
27 | }
28 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Exceptions/ProxyHttpException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Titanium.Web.Proxy.EventArguments;
3 |
4 | namespace Titanium.Web.Proxy.Exceptions;
5 |
6 | ///
7 | /// Proxy HTTP exception.
8 | ///
9 | public class ProxyHttpException : ProxyException
10 | {
11 | ///
12 | /// Initializes a new instance of the class.
13 | ///
14 | /// Message for this exception
15 | /// Associated inner exception
16 | /// Instance of associated to the exception
17 | internal ProxyHttpException(string message, Exception? innerException, SessionEventArgs? session) : base(
18 | message, innerException)
19 | {
20 | Session = session;
21 | }
22 |
23 | ///
24 | /// Gets session info associated to the exception.
25 | ///
26 | ///
27 | /// This object properties should not be edited.
28 | ///
29 | public SessionEventArgs? Session { get; }
30 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Exceptions/RetryableServerConnectionException.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Titanium.Web.Proxy.Exceptions;
4 |
5 | ///
6 | /// The server connection was closed upon first write with the new connection from pool.
7 | /// Should retry the request with a new connection.
8 | ///
9 | public class RetryableServerConnectionException : ProxyException
10 | {
11 | internal RetryableServerConnectionException(string message) : base(message)
12 | {
13 | }
14 |
15 | ///
16 | /// Constructor.
17 | ///
18 | ///
19 | ///
20 | internal RetryableServerConnectionException(string message, Exception e) : base(message, e)
21 | {
22 | }
23 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Extensions/FuncExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading.Tasks;
3 | using Titanium.Web.Proxy.EventArguments;
4 |
5 | namespace Titanium.Web.Proxy.Extensions;
6 |
7 | internal static class FuncExtensions
8 | {
9 | internal static async Task InvokeAsync(this AsyncEventHandler callback, object sender, T args,
10 | ExceptionHandler? exceptionFunc)
11 | {
12 | var invocationList = callback.GetInvocationList();
13 |
14 | foreach (var @delegate in invocationList)
15 | await InternalInvokeAsync((AsyncEventHandler)@delegate, sender, args, exceptionFunc);
16 | }
17 |
18 | private static async Task InternalInvokeAsync(AsyncEventHandler callback, object sender, T args,
19 | ExceptionHandler? exceptionFunc)
20 | {
21 | try
22 | {
23 | await callback(sender, args);
24 | }
25 | catch (Exception e)
26 | {
27 | exceptionFunc?.Invoke(new Exception("Exception thrown in user event", e));
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Extensions/HttpHeaderExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Titanium.Web.Proxy.Models;
3 |
4 | namespace Titanium.Web.Proxy.Extensions;
5 |
6 | internal static class HttpHeaderExtensions
7 | {
8 | internal static string GetString(this ByteString str)
9 | {
10 | return GetString(str.Span);
11 | }
12 |
13 | internal static string GetString(this ReadOnlySpan bytes)
14 | {
15 | #if NET6_0_OR_GREATER
16 | return HttpHeader.Encoding.GetString(bytes);
17 | #else
18 | return HttpHeader.Encoding.GetString(bytes.ToArray());
19 | #endif
20 | }
21 |
22 | internal static ByteString GetByteString(this string str)
23 | {
24 | return HttpHeader.Encoding.GetBytes(str);
25 | }
26 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Extensions/StreamExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.IO;
3 | using System.Threading;
4 | using System.Threading.Tasks;
5 | using Titanium.Web.Proxy.StreamExtended.BufferPool;
6 |
7 | namespace Titanium.Web.Proxy.Extensions;
8 |
9 | ///
10 | /// Extensions used for Stream and CustomBinaryReader objects
11 | ///
12 | internal static class StreamExtensions
13 | {
14 | ///
15 | /// Copy streams asynchronously
16 | ///
17 | ///
18 | ///
19 | ///
20 | ///
21 | internal static Task CopyToAsync(this Stream input, Stream output, Action onCopy,
22 | IBufferPool bufferPool)
23 | {
24 | return CopyToAsync(input, output, onCopy, bufferPool, CancellationToken.None);
25 | }
26 |
27 | ///
28 | /// Copy streams asynchronously
29 | ///
30 | ///
31 | ///
32 | ///
33 | ///
34 | ///
35 | internal static async Task CopyToAsync(this Stream input, Stream output, Action? onCopy,
36 | IBufferPool bufferPool, CancellationToken cancellationToken)
37 | {
38 | var buffer = bufferPool.GetBuffer();
39 | try
40 | {
41 | while (!cancellationToken.IsCancellationRequested)
42 | {
43 | // cancellation is not working on Socket ReadAsync
44 | // https://github.com/dotnet/corefx/issues/15033
45 | var num = await input.ReadAsync(buffer, 0, buffer.Length, cancellationToken)
46 | .WithCancellation(cancellationToken);
47 | int bytesRead;
48 | if ((bytesRead = num) != 0 && !cancellationToken.IsCancellationRequested)
49 | {
50 | await output.WriteAsync(buffer, 0, bytesRead, CancellationToken.None);
51 | onCopy?.Invoke(buffer, 0, bytesRead);
52 | }
53 | else
54 | {
55 | break;
56 | }
57 | }
58 | }
59 | finally
60 | {
61 | bufferPool.ReturnBuffer(buffer);
62 | }
63 | }
64 |
65 | internal static async Task WithCancellation(this Task task, CancellationToken cancellationToken)
66 | where T : struct
67 | {
68 | var tcs = new TaskCompletionSource();
69 | using (cancellationToken.Register(s => ((TaskCompletionSource)s).TrySetResult(true), tcs))
70 | {
71 | if (task != await Task.WhenAny(task, tcs.Task)) return default;
72 | }
73 |
74 | return await task;
75 | }
76 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Extensions/StringExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Buffers.Text;
3 | using System.Buffers;
4 | using System.Globalization;
5 | using System.Text;
6 |
7 | namespace Titanium.Web.Proxy.Extensions;
8 |
9 | internal static class StringExtensions
10 | {
11 | internal static bool EqualsIgnoreCase(this string str, string? value)
12 | {
13 | return str.Equals(value, StringComparison.CurrentCultureIgnoreCase);
14 | }
15 |
16 | internal static bool EqualsIgnoreCase(this ReadOnlySpan str, ReadOnlySpan value)
17 | {
18 | return str.Equals(value, StringComparison.CurrentCultureIgnoreCase);
19 | }
20 |
21 | internal static bool ContainsIgnoreCase(this string str, string? value)
22 | {
23 | return CultureInfo.CurrentCulture.CompareInfo.IndexOf(str, value, CompareOptions.IgnoreCase) >= 0;
24 | }
25 |
26 | internal static int IndexOfIgnoreCase(this string str, string? value)
27 | {
28 | return CultureInfo.CurrentCulture.CompareInfo.IndexOf(str, value, CompareOptions.IgnoreCase);
29 | }
30 |
31 | internal static unsafe string ByteArrayToHexString(this ReadOnlySpan data)
32 | {
33 | if (data.Length == 0)
34 | {
35 | return string.Empty;
36 | }
37 |
38 | int length = data.Length * 3;
39 | Span buf = stackalloc byte[length];
40 | var buf2 = buf;
41 | foreach (var b in data)
42 | {
43 | Utf8Formatter.TryFormat(b, buf2, out _, new StandardFormat('X', 2));
44 | buf2[2] = 32; // space
45 | buf2 = buf2.Slice(3);
46 | }
47 |
48 | #if NET6_0_OR_GREATER
49 | return Encoding.UTF8.GetString(buf.Slice(0, length - 1));
50 | #else
51 | fixed (byte* bp = buf)
52 | {
53 | return Encoding.UTF8.GetString(bp, length -1);
54 | }
55 | #endif
56 | }
57 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Extensions/TcpExtensions.cs:
--------------------------------------------------------------------------------
1 | using System.Net.Sockets;
2 |
3 | namespace Titanium.Web.Proxy.Extensions;
4 |
5 | internal static class TcpExtensions
6 | {
7 | ///
8 | /// Check if a TcpClient is good to be used.
9 | /// This only checks if send is working so local socket is still connected.
10 | /// Receive can only be verified by doing a valid read from server without exceptions.
11 | /// So in our case we should retry with new connection from pool if first read after getting the connection fails.
12 | /// https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected(v=vs.110).aspx
13 | ///
14 | ///
15 | ///
16 | internal static bool IsGoodConnection(this Socket socket)
17 | {
18 | if (!socket.Connected) return false;
19 |
20 | // This is how you can determine whether a socket is still connected.
21 | var blockingState = socket.Blocking;
22 | try
23 | {
24 | var tmp = new byte[1];
25 |
26 | socket.Blocking = false;
27 | socket.Send(tmp, 0, 0);
28 | // Connected.
29 | }
30 | catch
31 | {
32 | // Should we let 10035 == WSAEWOULDBLOCK as valid connection?
33 | return false;
34 | }
35 | finally
36 | {
37 | socket.Blocking = blockingState;
38 | }
39 |
40 | return true;
41 | }
42 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Extensions/UriExtensions.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Titanium.Web.Proxy.Models;
3 |
4 | namespace Titanium.Web.Proxy.Extensions;
5 |
6 | internal static class UriExtensions
7 | {
8 | public static string GetOriginalPathAndQuery(this Uri uri)
9 | {
10 | var leftPart = uri.GetLeftPart(UriPartial.Authority);
11 | if (uri.OriginalString.StartsWith(leftPart))
12 | return uri.OriginalString.Substring(leftPart.Length);
13 |
14 | return uri.IsWellFormedOriginalString()
15 | ? uri.PathAndQuery
16 | : uri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
17 | }
18 |
19 | public static ByteString GetScheme(ByteString str)
20 | {
21 | if (str.Length < 3) return ByteString.Empty;
22 |
23 | // regex: "^[a-z]*://"
24 | int i;
25 |
26 | for (i = 0; i < str.Length - 3; i++)
27 | {
28 | var ch = str[i];
29 | if (ch == ':') break;
30 |
31 | if (ch < 'A' || ch > 'z' || ch > 'Z' && ch < 'a') // ASCII letter
32 | return ByteString.Empty;
33 | }
34 |
35 | if (str[i++] != ':') return ByteString.Empty;
36 |
37 | if (str[i++] != '/') return ByteString.Empty;
38 |
39 | if (str[i] != '/') return ByteString.Empty;
40 |
41 | return new ByteString(str.Data.Slice(0, i - 2));
42 | }
43 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Handlers/AsyncEventHandler.cs:
--------------------------------------------------------------------------------
1 | using System.Threading.Tasks;
2 |
3 | namespace Titanium.Web.Proxy.EventArguments;
4 |
5 | ///
6 | /// A generic asynchronous event handler used by the proxy.
7 | ///
8 | /// Event argument type.
9 | /// The proxy server instance.
10 | /// The event arguments.
11 | ///
12 | public delegate Task AsyncEventHandler(object sender, TEventArgs e);
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Handlers/CertificateHandler.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.Security;
3 | using System.Security.Cryptography.X509Certificates;
4 | using Titanium.Web.Proxy.EventArguments;
5 | using Titanium.Web.Proxy.Extensions;
6 |
7 | namespace Titanium.Web.Proxy;
8 |
9 | public partial class ProxyServer
10 | {
11 | ///
12 | /// Call back to override server certificate validation
13 | ///
14 | /// The sender object.
15 | /// The http session.
16 | /// The remote certificate.
17 | /// The certificate chain.
18 | /// Ssl policy errors
19 | /// Return true if valid certificate.
20 | internal bool ValidateServerCertificate(object sender, SessionEventArgsBase sessionArgs,
21 | X509Certificate certificate, X509Chain chain,
22 | SslPolicyErrors sslPolicyErrors)
23 | {
24 | // if user callback is registered then do it
25 | if (ServerCertificateValidationCallback != null)
26 | {
27 | var args = new CertificateValidationEventArgs(sessionArgs, certificate, chain, sslPolicyErrors);
28 |
29 | // why is the sender null?
30 | ServerCertificateValidationCallback.InvokeAsync(this, args, ExceptionFunc).Wait();
31 | return args.IsValid;
32 | }
33 |
34 | if (sslPolicyErrors == SslPolicyErrors.None) return true;
35 |
36 | // By default
37 | // do not allow this client to communicate with unauthenticated servers.
38 | return false;
39 | }
40 |
41 | ///
42 | /// Call back to select client certificate used for mutual authentication
43 | ///
44 | /// The sender.
45 | /// The http session.
46 | /// The remote hostname.
47 | /// Selected local certificates by SslStream.
48 | /// The remote certificate of server.
49 | /// The acceptable issues for client certificate as listed by server.
50 | ///
51 | internal X509Certificate? SelectClientCertificate(object sender, SessionEventArgsBase sessionArgs,
52 | string targetHost,
53 | X509CertificateCollection localCertificates,
54 | X509Certificate remoteCertificate, string[] acceptableIssuers)
55 | {
56 | X509Certificate? clientCertificate = null;
57 |
58 | //fallback to the first client certificate from proxy machine certificate store
59 | if (acceptableIssuers != null && acceptableIssuers.Length > 0 && localCertificates != null &&
60 | localCertificates.Count > 0)
61 | foreach (var certificate in localCertificates)
62 | {
63 | var issuer = certificate.Issuer;
64 | if (Array.IndexOf(acceptableIssuers, issuer) != -1) clientCertificate = certificate;
65 | }
66 |
67 | //fallback to the first client certificate from proxy machine certificate store
68 | if (clientCertificate == null
69 | && localCertificates != null && localCertificates.Count > 0)
70 | clientCertificate = localCertificates[0];
71 |
72 | // If user call back is registered
73 | if (ClientCertificateSelectionCallback != null)
74 | {
75 | var args = new CertificateSelectionEventArgs(sessionArgs, targetHost, localCertificates, remoteCertificate,
76 | acceptableIssuers)
77 | {
78 | ClientCertificate = clientCertificate
79 | };
80 |
81 |
82 | ClientCertificateSelectionCallback.InvokeAsync(this, args, ExceptionFunc).Wait();
83 | return args.ClientCertificate;
84 | }
85 |
86 | return clientCertificate;
87 | }
88 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Handlers/ExceptionHandler.cs:
--------------------------------------------------------------------------------
1 | using System;
2 |
3 | namespace Titanium.Web.Proxy;
4 |
5 | ///
6 | /// A delegate to catch exceptions occuring in proxy.
7 | ///
8 | /// The exception occurred in proxy.
9 | public delegate void ExceptionHandler(Exception exception);
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Handlers/WebSocketHandler.cs:
--------------------------------------------------------------------------------
1 | using System.Threading;
2 | using System.Threading.Tasks;
3 | using Titanium.Web.Proxy.EventArguments;
4 | using Titanium.Web.Proxy.Helpers;
5 | using Titanium.Web.Proxy.Http;
6 | using Titanium.Web.Proxy.Network.Tcp;
7 |
8 | namespace Titanium.Web.Proxy;
9 |
10 | public partial class ProxyServer
11 | {
12 | ///
13 | /// Handle upgrade to websocket
14 | ///
15 | private async Task HandleWebSocketUpgrade(SessionEventArgs args,
16 | HttpClientStream clientStream, TcpServerConnection serverConnection,
17 | CancellationTokenSource cancellationTokenSource, CancellationToken cancellationToken)
18 | {
19 | await serverConnection.Stream.WriteRequestAsync(args.HttpClient.Request, cancellationToken);
20 |
21 | var httpStatus = await serverConnection.Stream.ReadResponseStatus(cancellationToken);
22 |
23 | var response = args.HttpClient.Response;
24 | response.HttpVersion = httpStatus.Version;
25 | response.StatusCode = httpStatus.StatusCode;
26 | response.StatusDescription = httpStatus.Description;
27 |
28 | await HeaderParser.ReadHeaders(serverConnection.Stream, response.Headers,
29 | cancellationToken);
30 |
31 | await clientStream.WriteResponseAsync(response, cancellationToken);
32 |
33 | // If user requested call back then do it
34 | if (!args.HttpClient.Response.Locked) await OnBeforeResponse(args);
35 |
36 | await TcpHelper.SendRaw(clientStream, serverConnection.Stream, BufferPool,
37 | args.OnDataSent, args.OnDataReceived, cancellationTokenSource, ExceptionFunc);
38 | }
39 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Helpers/CompressionUtil.cs:
--------------------------------------------------------------------------------
1 | using Titanium.Web.Proxy.Http;
2 |
3 | namespace Titanium.Web.Proxy.Compression;
4 |
5 | internal static class CompressionUtil
6 | {
7 | public static HttpCompression CompressionNameToEnum(string name)
8 | {
9 | if (KnownHeaders.ContentEncodingGzip.Equals(name))
10 | return HttpCompression.Gzip;
11 |
12 | if (KnownHeaders.ContentEncodingDeflate.Equals(name))
13 | return HttpCompression.Deflate;
14 |
15 | if (KnownHeaders.ContentEncodingBrotli.Equals(name))
16 | return HttpCompression.Brotli;
17 |
18 | return HttpCompression.Unsupported;
19 | }
20 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Helpers/NativeMethods.SystemProxy.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Runtime.InteropServices;
3 |
4 | namespace Titanium.Web.Proxy.Helpers;
5 |
6 | internal partial class NativeMethods
7 | {
8 | // Keeps it from getting garbage collected
9 | internal static ConsoleEventDelegate? Handler;
10 |
11 | [DllImport("wininet.dll")]
12 | internal static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer,
13 | int dwBufferLength);
14 |
15 | [DllImport("kernel32.dll")]
16 | internal static extern IntPtr GetConsoleWindow();
17 |
18 | [DllImport("kernel32.dll", SetLastError = true)]
19 | internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
20 |
21 | ///
22 | ///
23 | ///
24 | [DllImport("user32.dll")]
25 | internal static extern int GetSystemMetrics(int nIndex);
26 |
27 | // Pinvoke
28 | internal delegate bool ConsoleEventDelegate(int eventType);
29 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Helpers/NativeMethods.Tcp.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Net.NetworkInformation;
3 | using System.Runtime.InteropServices;
4 |
5 | namespace Titanium.Web.Proxy.Helpers;
6 |
7 | internal partial class NativeMethods
8 | {
9 | internal const int AfInet = 2;
10 | internal const int AfInet6 = 23;
11 |
12 | ///
13 | ///
14 | ///
15 | [DllImport("iphlpapi.dll", SetLastError = true)]
16 | internal static extern uint GetExtendedTcpTable(IntPtr tcpTable, ref int size, bool sort, int ipVersion,
17 | int tableClass, int reserved);
18 |
19 | internal enum TcpTableType
20 | {
21 | BasicListener,
22 | BasicConnections,
23 | BasicAll,
24 | OwnerPidListener,
25 | OwnerPidConnections,
26 | OwnerPidAll,
27 | OwnerModuleListener,
28 | OwnerModuleConnections,
29 | OwnerModuleAll
30 | }
31 |
32 | ///
33 | ///
34 | ///
35 | [StructLayout(LayoutKind.Sequential)]
36 | internal struct TcpRow
37 | {
38 | public TcpState state;
39 | public uint localAddr;
40 | public uint localPort; // in network byte order (order of bytes - 1,0,3,2)
41 | public uint remoteAddr;
42 | public uint remotePort; // in network byte order (order of bytes - 1,0,3,2)
43 | public int owningPid;
44 | }
45 |
46 | ///
47 | ///
48 | ///
49 | [StructLayout(LayoutKind.Sequential)]
50 | internal unsafe struct Tcp6Row
51 | {
52 | public fixed byte localAddr[16];
53 | public uint localScopeId;
54 | public uint localPort; // in network byte order (order of bytes - 1,0,3,2)
55 | public fixed byte remoteAddr[16];
56 | public uint remoteScopeId;
57 | public uint remotePort; // in network byte order (order of bytes - 1,0,3,2)
58 | public TcpState state;
59 | public int owningPid;
60 | }
61 | }
--------------------------------------------------------------------------------
/src/Titanium.Web.Proxy/Helpers/Net45Compatibility.cs:
--------------------------------------------------------------------------------
1 | #if NET451
2 | using System.Threading.Tasks;
3 |
4 | namespace Titanium.Web.Proxy
5 | {
6 | internal class Net45Compatibility
7 | {
8 | public static byte[] EmptyArray = new byte[0];
9 |
10 | public static Task CompletedTask = Task.FromResult