├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── .idea
├── .gitignore
├── .name
├── codeStyles
│ ├── Project.xml
│ └── codeStyleConfig.xml
├── compiler.xml
├── gradle.xml
├── jarRepositories.xml
├── jvm-http-proxy-agent.iml
├── kotlinc.xml
├── misc.xml
├── modules.xml
├── modules
│ ├── java-agent.iml
│ ├── java-agent.main.iml
│ └── java-agent.test.iml
└── vcs.xml
├── LICENSE
├── README.md
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── r8-rules.txt
├── settings.gradle
├── src
├── main
│ ├── java
│ │ ├── reactor
│ │ │ └── netty
│ │ │ │ └── tcp
│ │ │ │ └── ProxyProvider.java
│ │ └── tech
│ │ │ └── httptoolkit
│ │ │ └── javaagent
│ │ │ └── advice
│ │ │ ├── OverrideAllProxySelectionAdvice.java
│ │ │ ├── OverrideSslContextFieldAdvice.java
│ │ │ ├── OverrideUrlConnectionProxyAdvice.java
│ │ │ ├── ReturnProxyAddressAdvice.java
│ │ │ ├── ReturnProxyAdvice.java
│ │ │ ├── ReturnProxySelectorAdvice.java
│ │ │ ├── ReturnSslContextAdvice.java
│ │ │ ├── ReturnSslSocketFactoryAdvice.java
│ │ │ ├── SkipMethodAdvice.java
│ │ │ ├── akka
│ │ │ ├── OverrideHttpSettingsAdvice.java
│ │ │ ├── ResetOldGatewaysAdvice.java
│ │ │ ├── ResetOldPoolsAdvice.java
│ │ │ └── ResetPoolSetupAdvice.java
│ │ │ ├── apacheclient
│ │ │ ├── ApacheCustomSslProtocolSocketFactory.java
│ │ │ ├── ApacheOverrideProxyHostFieldAdvice.java
│ │ │ ├── ApacheReturnCustomSslProtocolSocketFactoryAdvice.java
│ │ │ ├── ApacheSetConfigProxyHostAdvice.java
│ │ │ ├── ApacheSetSslSocketFactoryAdvice.java
│ │ │ ├── ApacheV4ReturnProxyRouteAdvice.java
│ │ │ └── ApacheV5ReturnProxyRouteAdvice.java
│ │ │ ├── asynchttpclient
│ │ │ ├── AsyncHttpClientReturnProxySelectorAdvice.java
│ │ │ ├── AsyncHttpClientReturnSslContextAdvice.java
│ │ │ └── AsyncHttpResetSslEngineFactoryAdvice.java
│ │ │ ├── jettyclient
│ │ │ ├── JettyResetDestinationsAdvice.java
│ │ │ ├── JettyReturnProxyConfigurationAdvice.java
│ │ │ ├── JettyReturnSslContextFactoryV10Advice.java
│ │ │ ├── JettyReturnSslContextFactoryV9Advice.java
│ │ │ └── JettyV9StubContextFactory.java
│ │ │ ├── ktor
│ │ │ ├── KtorResetProxyFieldAdvice.java
│ │ │ └── KtorResetTlsClientTrustAdvice.java
│ │ │ ├── reactornetty
│ │ │ ├── ReactorNettyResetAllConfigAdvice.java
│ │ │ ├── ReactorNettyResetHttpClientSecureSslAdvice.java
│ │ │ └── ReactorNettyV09ResetProxyProviderFieldAdvice.java
│ │ │ └── vertxclient
│ │ │ ├── VertxHttpClientReturnProxyConfigurationAdvice.java
│ │ │ └── VertxNetClientOptionsSetTrustOptionsAdvice.java
│ └── kotlin
│ │ └── tech
│ │ └── httptoolkit
│ │ └── javaagent
│ │ ├── AgentConfig.kt
│ │ ├── AgentMain.kt
│ │ ├── AkkaClientTransformers.kt
│ │ ├── ApacheAsyncClientTransformer.kt
│ │ ├── ApacheClientTransformers.kt
│ │ ├── AsyncHttpClientConfigTransformers.kt
│ │ ├── AttachMain.kt
│ │ ├── ConstantProxySelector.kt
│ │ ├── CustomSslContext.kt
│ │ ├── HttpsUrlConnectionTransformer.kt
│ │ ├── JavaClientTransformer.kt
│ │ ├── JettyClientTransformer.kt
│ │ ├── KtorCioTransformers.kt
│ │ ├── OkHttpClientTransformers.kt
│ │ ├── ProxySelectorTransformer.kt
│ │ ├── ReactorNettyTransformers.kt
│ │ ├── SslContextTransformer.kt
│ │ ├── TransformationLogger.kt
│ │ ├── UrlConnectionTransformer.kt
│ │ ├── VertxHttpClientTransformer.kt
│ │ └── VertxNetClientOptionsTransformer.kt
└── test
│ ├── kotlin
│ └── IntegrationTests.kt
│ └── resources
│ ├── cert.jks
│ └── cert.pem
└── test-app
├── build.gradle
└── src
└── main
└── java
└── tech
└── httptoolkit
└── testapp
├── Main.java
└── cases
├── AkkaHostClientCase.java
├── AkkaRequestClientCase.java
├── ApacheHttpAsyncClientV4Case.java
├── ApacheHttpAsyncClientV5Case.java
├── ApacheHttpClientV3Case.java
├── ApacheHttpClientV4Case.java
├── ApacheHttpClientV5Case.java
├── AsyncHttpClientCase.java
├── ClientCase.java
├── HttpUrlConnCase.java
├── JavaHttpClientCase.java
├── JettyClientCase.java
├── KtorCioCase.kt
├── OkHttpV2Case.java
├── OkHttpV4Case.java
├── RestEasyWithApacheHttpClientV4Case.java
├── RetrofitCase.java
├── SpringWebClientCase.java
├── VertxHttpClientCase.java
└── VertxWebClientCase.java
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on: [push, pull_request]
3 | jobs:
4 | build:
5 | name: Build & test
6 | runs-on: ubuntu-latest
7 |
8 | steps:
9 | - uses: actions/checkout@v3
10 |
11 | - name: Set up JRE 8 as libs for R8
12 | uses: actions/setup-java@v3
13 | with:
14 | java-version: 8
15 | distribution: adopt-hotspot
16 |
17 | - name: Set up JDK 14 for build
18 | uses: actions/setup-java@v3
19 | with:
20 | java-version: 14
21 | distribution: adopt-hotspot
22 |
23 | - name: Build & test the agent standalone
24 | run: ./gradlew quickTest
25 |
26 | - name: Build & test the full distributable
27 | run: ./gradlew distTest
28 |
29 | - uses: actions/upload-artifact@v4
30 | with:
31 | name: distributables
32 | path: build/libs/*-dist.jar
33 | if-no-files-found: error
34 |
35 | - name: Publish tagged release
36 | uses: svenstaro/upload-release-action@v2
37 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
38 | with:
39 | repo_token: ${{ secrets.GITHUB_TOKEN }}
40 | file: build/libs/*-dist.jar
41 | file_glob: true
42 | tag: ${{ github.ref }}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 |
25 | build/
26 | .idea/workspace.xml
27 | .idea/tasks.xml
28 | .gradle
29 | local.properties
--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/.idea/.name:
--------------------------------------------------------------------------------
1 | http-proxy-agent
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
17 |
18 |
--------------------------------------------------------------------------------
/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/.idea/jvm-http-proxy-agent.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/modules/java-agent.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/modules/java-agent.main.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
--------------------------------------------------------------------------------
/.idea/modules/java-agent.test.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # jvm-http-proxy-agent
2 |
3 | > _Part of [HTTP Toolkit](https://httptoolkit.com): powerful tools for building, testing & debugging HTTP(S)_
4 |
5 | A JVM agent that automatically forces a proxy for HTTP(S) connections, and trusts a given additional HTTPS certificate authority, for all major JVM HTTP clients.
6 |
7 | This agent lets you intercept all HTTP(S) from any JVM application automatically, with no code changes, so you can inspect, debug & mock this traffic using an HTTPS proxy, such as [HTTP Toolkit](https://httptoolkit.com) or any other HTTPS MitM proxy.
8 |
9 | You can either launch the application with this agent from the start, or it can attach to and take over HTTP(S) from an already running JVM application.
10 |
11 | Traffic can be captured from at least:
12 |
13 | - [x] Java's built-in HttpURLConnection
14 | - [x] Java 11's built-in HttpClient
15 | - [x] Apache HttpClient v3, v4 & v5
16 | - [x] Apache HttpAsyncClient v4 & v5
17 | - [x] OkHttp v2, v3 & v4
18 | - [x] Retrofit
19 | - [x] Jetty-Client v9, v10 & v11
20 | - [x] Async-Http-Client
21 | - [x] Reactor-Netty v0.9 & v1+
22 | - [x] Spring WebClient
23 | - [x] Ktor-Client
24 | - [x] Akka-HTTP v10.1.6+
25 | - [x] Vert.x HttpClient and WebClient
26 |
27 | This will also capture HTTP(S) from any downstream libraries based on each of these clients, and many other untested clients sharing similar implementations, and so should cover a very large percentage of HTTP client usage.
28 |
29 | This agent supports at least Oracle & OpenJDK v8+ when starting the application with the agent, or v11+ for application that the agent will attach to.
30 |
31 | It's likely that this supports many other HTTP client configurations & JVMs too. If you find a case that isn't supported, or isn't supported correctly, please [file an issue](https://github.com/httptoolkit/jvm-http-proxy-agent/issues/new).
32 |
33 | ## Usage
34 |
35 | This agent can either be attached when the process is started, or attached later to a running process.
36 |
37 | In each case, the agent must be configured with the proxy host (e.g. 127.0.0.1), the proxy port (e.g. 8000) and the absolute path to the HTTPS certificate to be trusted.
38 |
39 | ### Attaching at startup
40 |
41 | To attach at startup, pass this JAR using the `javaagent` option, e.g:
42 |
43 | ```
44 | java -javaagent:./agent.jar="127.0.0.1|8000|/path/to/cert.pem" -jar ./application.jar
45 | ```
46 |
47 | ### Attaching to a running process
48 |
49 | To attach to a process, first launch the target process, and then run:
50 |
51 | ```
52 | java -jar ./agent.jar 1234 127.0.0.1 8000 /path/to/cert.pem
53 | ```
54 |
55 | where 1234 is the pid of the target process. This will exit successfully & immediately if attachment succeeds, or with a non-zero exit code if not.
56 |
57 | You can also query the available JVM processes ids, like so:
58 |
59 | ```
60 | > java -jar ./agent.jar list-targets
61 | 589739:./application.jar
62 | 404401:com.intellij.idea.Main
63 | 453889:org.jetbrains.kotlin.daemon.KotlinCompileDaemon --daemon-runFilesPath ...
64 | 413868:org.gradle.launcher.daemon.bootstrap.GradleDaemon 6.7
65 | ```
66 |
67 | When attached from startup all clients will always be intercepted. When attached later, both newly created HTTP clients and already existing instances will be intercepted, but it's possible that in some cases already established connections may not be immediately captured. Typically though these will eventually close and be reconnected, and at that point the connection is always intercepted.
68 |
69 | ### Testing attachment capabilities
70 |
71 | Not all JDKs provide the instrumentation & attachment APIs required to support this process, although all Oracle & OpenJDK v9+ versions should do so.
72 |
73 | To check this, you can test whether the `java` in your $PATH is capable of attaching to and intercepting a target process using the self-test command, like so:
74 |
75 | ```bash
76 | java -Djdk.attach.allowAttachSelf=true -jar ./agent.jar self-test
77 | ```
78 |
79 | ### Contributing
80 |
81 | Contributions are very welcome! Reports of scenarios that aren't currently supported are helpful (please [create an issue](https://github.com/httptoolkit/jvm-http-proxy-agent/issues/new), including any errors, and preferably steps to reproduce the issue) but patches to fix issues are even better.
82 |
83 | Be aware that for all contributors to HTTP Toolkit components, including this, [HTTP Toolkit Pro is totally free](https://github.com/httptoolkit/httptoolkit/#contributing-directly) - just [get in touch](https://httptoolkit.com/contact) after your contribution is accepted with the email you'd like to use to claim your Pro account.
84 |
85 | To contribute a patch:
86 |
87 | * Fork this repo
88 | * Clone your fork: `git clone git@github.com:$YOUR_GITHUB_USERNAME/jvm-http-proxy-agent.git`
89 | * Create a new branch: `git checkout -B my-contribution-branch`
90 | * Check the existing tests pass locally: `./gradlew quickTest`
91 | * N.B. this requires Java 11+ - while some features are supported in older JVM versions, development requires a modern JVM
92 | * For library-specific issues:
93 | * Add/edit a test case in [/test-app/src/main/java/tech/httptoolkit/testapp/cases](https://github.com/httptoolkit/jvm-http-proxy-agent/tree/main/test-app/src/main/java/tech/httptoolkit/testapp/cases) to reproduce your issue
94 | * Add that case to [the list](https://github.com/httptoolkit/jvm-http-proxy-agent/blob/459b931a2eebd486261f296418aa028e4b2fb7e9/test-app/src/main/java/tech/httptoolkit/testapp/Main.java#L17-L36) if you created a new case.
95 | * Check that `./gradlew quickTest` now fails.
96 | * For more general changes:
97 | * Either add a test case (as above) or add a new standalone test in https://github.com/httptoolkit/jvm-http-proxy-agent/blob/main/src/test/kotlin/IntegrationTests.kt
98 | * Make your changes within the [advice classes](https://github.com/httptoolkit/jvm-http-proxy-agent/tree/main/src/main/java/tech/httptoolkit/javaagent/advice) and [injection setup code](https://github.com/httptoolkit/jvm-http-proxy-agent/tree/main/src/main/kotlin/tech/httptoolkit/javaagent) to fix your issue/add your feature.
99 | * Test that `./gradlew quickTest` now passes.
100 | * If you've changed any functionality, consider adding it to the docs here.
101 | * Commit your change, push it, and open a PR here for review.
102 |
103 | If you have any issues, or if you want to discuss a change before working on it (recommended for large/complex changes), please [open an issue](https://github.com/httptoolkit/jvm-http-proxy-agent/issues/new).
104 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | buildscript {
2 | repositories {
3 | mavenCentral()
4 | }
5 | dependencies {
6 | classpath 'net.sf.proguard:proguard-gradle:6.2.2'
7 | }
8 | }
9 |
10 |
11 | plugins {
12 | id 'java'
13 | id 'org.jetbrains.kotlin.jvm' version '1.6.21'
14 | id 'com.github.johnrengelman.shadow' version '7.1.2'
15 | }
16 |
17 | group 'tech.httptoolkit'
18 | version '1.3.8'
19 |
20 | repositories {
21 | mavenCentral()
22 | maven {
23 | url "https://maven.google.com/"
24 | }
25 | }
26 |
27 | configurations {
28 | r8
29 | }
30 |
31 | dependencies {
32 | implementation group: 'net.bytebuddy', name: 'byte-buddy-dep', version: '1.15.4'
33 | // byte buddy contains references to jna classes and without them the r8Jar step fails
34 | compileOnly group: 'net.java.dev.jna', name: 'jna', version: '5.8.0'
35 |
36 | // Dependencies we load only as part of rewriting them, iff the target app includes them:
37 | compileOnly group: 'commons-httpclient', name: 'commons-httpclient', version: '3.1'
38 | compileOnly group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5'
39 | compileOnly group: 'org.apache.httpcomponents.client5', name: 'httpclient5', version: '5.0.3'
40 | compileOnly group: 'org.eclipse.jetty', name: 'jetty-client', version: '11.0.1'
41 | compileOnly group: 'org.asynchttpclient', name: 'async-http-client', version: '2.12.2'
42 | compileOnly group: 'io.projectreactor.netty', name: 'reactor-netty', version: '1.0.4'
43 | compileOnly group: 'io.ktor', name: 'ktor-client-core', version: '1.5.2'
44 | compileOnly group: 'io.ktor', name: 'ktor-client-cio', version: '1.5.2'
45 | compileOnly group: 'com.typesafe.akka', name: 'akka-http-core_2.13', version: '10.2.4'
46 | compileOnly group: 'com.typesafe.akka', name: 'akka-actor_2.13', version: '2.6.13'
47 | compileOnly group: 'io.vertx', name: 'vertx-core', version: '4.2.2'
48 |
49 | // Test deps:
50 | testImplementation group: 'io.kotest', name: 'kotest-runner-junit5-jvm', version: '4.4.0'
51 | testImplementation group: 'io.kotest', name: 'kotest-assertions-core-jvm', version: '4.4.0'
52 | testImplementation "com.github.tomakehurst:wiremock-jre8:2.27.2"
53 |
54 | // Only used during the R8 build task
55 | r8 group: 'com.android.tools', name: 'r8', version: '2.1.75'
56 | }
57 |
58 | compileJava {
59 | sourceCompatibility = '1.8'
60 | targetCompatibility = '1.8'
61 | }
62 |
63 | compileKotlin {
64 | kotlinOptions {
65 | jvmTarget = "1.8"
66 | }
67 | }
68 |
69 | tasks.withType(Jar) {
70 | manifest {
71 | attributes 'Premain-Class': 'tech.httptoolkit.javaagent.HttpProxyAgent'
72 | attributes 'Agent-Class': 'tech.httptoolkit.javaagent.HttpProxyAgent'
73 | attributes 'Main-Class': 'tech.httptoolkit.javaagent.AttachMain'
74 |
75 | attributes 'Can-Redefine-Classes': 'true'
76 | attributes 'Can-Retransform-Classes': 'true'
77 | }
78 | }
79 |
80 | // First, we bundle everything into a workable standalone JAR, with all runtime source included plus
81 | // dependencies plus agent metadata:
82 | shadowJar {
83 | minimize()
84 | exclude '**/*.kotlin_metadata'
85 | exclude '**/*.kotlin_module'
86 | exclude '**/*.kotlin_builtins'
87 | exclude '**/module_info.class'
88 | exclude 'META-INF/maven/**'
89 |
90 | // We have to specifically exclude our reactor stub code here, because we don't want to the type
91 | // stubs that we've manually defined in our own source included here.
92 | exclude 'reactor/'
93 | }
94 |
95 | // As part of bundling the JAR, we relocate all dependencies into our namespace:
96 | import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation
97 | task relocateShadowJar(type: ConfigureShadowRelocation) {
98 | target = tasks.shadowJar
99 | prefix = "tech.httptoolkit.relocated"
100 | }
101 | tasks.shadowJar.dependsOn tasks.relocateShadowJar
102 |
103 | // Then we take this bundled JAR and optimize it. This shrinks it dramatically, but also breaks it, because
104 | // bytebuddy depends on some of our source being unmodified by R8 (frames in advice classes get messed with).
105 | def r8File = new File("$buildDir/libs/$archivesBaseName-r8.jar")
106 | tasks.register('r8Jar', JavaExec) { task ->
107 | def rules = file('r8-rules.txt')
108 | task.dependsOn(tasks.shadowJar)
109 | task.outputs.file(r8File)
110 | task.inputs.files shadowJar.getArchiveFile()
111 |
112 | task.classpath(configurations.r8)
113 | task.main = 'com.android.tools.r8.R8'
114 | task.args = [
115 | '--release',
116 | '--classfile',
117 | '--output', r8File.toString(),
118 | '--pg-conf', rules.toString()
119 | ] + (configurations.compileClasspath.filter { path ->
120 | // Include libs for a few runtime-only deps, so R8 can resolve them during optimization:
121 | path.getName().startsWith("jna-") ||
122 | path.getName().startsWith("jetty-util-") ||
123 | path.getName().startsWith("commons-httpclient-") ||
124 | path.getName().startsWith("async-http-client-")
125 | }.collect {path ->
126 | ['--lib', path.toString()]
127 | }.flatten())
128 |
129 | doFirst {
130 | def java8Home = System.getenv("JAVA_HOME_8_X64")
131 | if (java8Home == null || java8Home.empty) {
132 | throw new GradleException("\$JAVA_HOME_8_X64 must be set to build a minified distributable")
133 | } else {
134 | // AFAICT R8 only supports the Java 8 lib files. We require that to be available, configured by env
135 | task.args += "--lib"
136 | task.args += java8Home
137 | }
138 |
139 | task.args += shadowJar.getArchiveFile().get().asFile.toString()
140 | }
141 | }
142 |
143 | // Then we fix this, by taking the raw advice classes for our own source from the original bundled JAR (i.e. including
144 | // any relocated references) and combining that with the minified & optimized dependencies from R8, to get a single
145 | // bundled and 99% optimized JAR.
146 | task distJar(type: Jar) {
147 | dependsOn(tasks.shadowJar, tasks.r8Jar)
148 | archiveClassifier = 'dist'
149 |
150 | // Pull raw advice classes from the shadow JAR, unminified:
151 | from (zipTree(shadowJar.getArchiveFile())) {
152 | include "tech/httptoolkit/javaagent/advice/**/*"
153 | include "tech/httptoolkit/relocated/net/bytebuddy/agent/builder/**/*"
154 | }
155 |
156 | // Pull other source & bundled dependencies in their minified form, from R8:
157 | from (zipTree(r8Jar.outputs.files[0])) {
158 | exclude "tech/httptoolkit/javaagent/advice/**/*"
159 | exclude "tech/httptoolkit/relocated/net/bytebuddy/agent/builder/**/*"
160 | }
161 | }
162 |
163 | tasks.withType(Test) {
164 | // We need to build both JARs before the integration tests can run
165 | dependsOn('shadowJar')
166 | dependsOn(':test-app:shadowJar')
167 | useJUnitPlatform()
168 | outputs.upToDateWhen {false}
169 |
170 | testLogging {
171 | events "STARTED", "PASSED", "FAILED", "SKIPPED", "STANDARD_OUT", "STANDARD_ERROR"
172 | }
173 | }
174 |
175 | task quickTest(type: Test) {
176 | environment 'TEST_JAR', tasks.shadowJar.getArchiveFile().get().asFile.toString()
177 | }
178 |
179 | task distTest(type: Test) {
180 | environment 'TEST_JAR', tasks.distJar.getArchiveFile().get().asFile.toString()
181 | dependsOn('distJar')
182 | }
183 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | kotlin.code.style=official
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/httptoolkit/jvm-http-proxy-agent/d43d27373aba210c9c4b564d9e22960d64a0766d/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | distributionBase=GRADLE_USER_HOME
2 | distributionPath=wrapper/dists
3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.10-bin.zip
4 | networkTimeout=10000
5 | validateDistributionUrl=true
6 | zipStoreBase=GRADLE_USER_HOME
7 | zipStorePath=wrapper/dists
8 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/bin/sh
2 |
3 | #
4 | # Copyright © 2015-2021 the original authors.
5 | #
6 | # Licensed under the Apache License, Version 2.0 (the "License");
7 | # you may not use this file except in compliance with the License.
8 | # You may obtain a copy of the License at
9 | #
10 | # https://www.apache.org/licenses/LICENSE-2.0
11 | #
12 | # Unless required by applicable law or agreed to in writing, software
13 | # distributed under the License is distributed on an "AS IS" BASIS,
14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 | # See the License for the specific language governing permissions and
16 | # limitations under the License.
17 | #
18 | # SPDX-License-Identifier: Apache-2.0
19 | #
20 |
21 | ##############################################################################
22 | #
23 | # Gradle start up script for POSIX generated by Gradle.
24 | #
25 | # Important for running:
26 | #
27 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
28 | # noncompliant, but you have some other compliant shell such as ksh or
29 | # bash, then to run this script, type that shell name before the whole
30 | # command line, like:
31 | #
32 | # ksh Gradle
33 | #
34 | # Busybox and similar reduced shells will NOT work, because this script
35 | # requires all of these POSIX shell features:
36 | # * functions;
37 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
38 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»;
39 | # * compound commands having a testable exit status, especially «case»;
40 | # * various built-in commands including «command», «set», and «ulimit».
41 | #
42 | # Important for patching:
43 | #
44 | # (2) This script targets any POSIX shell, so it avoids extensions provided
45 | # by Bash, Ksh, etc; in particular arrays are avoided.
46 | #
47 | # The "traditional" practice of packing multiple parameters into a
48 | # space-separated string is a well documented source of bugs and security
49 | # problems, so this is (mostly) avoided, by progressively accumulating
50 | # options in "$@", and eventually passing that to Java.
51 | #
52 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
53 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
54 | # see the in-line comments for details.
55 | #
56 | # There are tweaks for specific operating systems such as AIX, CygWin,
57 | # Darwin, MinGW, and NonStop.
58 | #
59 | # (3) This script is generated from the Groovy template
60 | # https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
61 | # within the Gradle project.
62 | #
63 | # You can find Gradle at https://github.com/gradle/gradle/.
64 | #
65 | ##############################################################################
66 |
67 | # Attempt to set APP_HOME
68 |
69 | # Resolve links: $0 may be a link
70 | app_path=$0
71 |
72 | # Need this for daisy-chained symlinks.
73 | while
74 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
75 | [ -h "$app_path" ]
76 | do
77 | ls=$( ls -ld "$app_path" )
78 | link=${ls#*' -> '}
79 | case $link in #(
80 | /*) app_path=$link ;; #(
81 | *) app_path=$APP_HOME$link ;;
82 | esac
83 | done
84 |
85 | # This is normally unused
86 | # shellcheck disable=SC2034
87 | APP_BASE_NAME=${0##*/}
88 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
89 | APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
90 | ' "$PWD" ) || exit
91 |
92 | # Use the maximum available, or set MAX_FD != -1 to use that value.
93 | MAX_FD=maximum
94 |
95 | warn () {
96 | echo "$*"
97 | } >&2
98 |
99 | die () {
100 | echo
101 | echo "$*"
102 | echo
103 | exit 1
104 | } >&2
105 |
106 | # OS specific support (must be 'true' or 'false').
107 | cygwin=false
108 | msys=false
109 | darwin=false
110 | nonstop=false
111 | case "$( uname )" in #(
112 | CYGWIN* ) cygwin=true ;; #(
113 | Darwin* ) darwin=true ;; #(
114 | MSYS* | MINGW* ) msys=true ;; #(
115 | NONSTOP* ) nonstop=true ;;
116 | esac
117 |
118 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
119 |
120 |
121 | # Determine the Java command to use to start the JVM.
122 | if [ -n "$JAVA_HOME" ] ; then
123 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
124 | # IBM's JDK on AIX uses strange locations for the executables
125 | JAVACMD=$JAVA_HOME/jre/sh/java
126 | else
127 | JAVACMD=$JAVA_HOME/bin/java
128 | fi
129 | if [ ! -x "$JAVACMD" ] ; then
130 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
131 |
132 | Please set the JAVA_HOME variable in your environment to match the
133 | location of your Java installation."
134 | fi
135 | else
136 | JAVACMD=java
137 | if ! command -v java >/dev/null 2>&1
138 | then
139 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
140 |
141 | Please set the JAVA_HOME variable in your environment to match the
142 | location of your Java installation."
143 | fi
144 | fi
145 |
146 | # Increase the maximum file descriptors if we can.
147 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
148 | case $MAX_FD in #(
149 | max*)
150 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
151 | # shellcheck disable=SC2039,SC3045
152 | MAX_FD=$( ulimit -H -n ) ||
153 | warn "Could not query maximum file descriptor limit"
154 | esac
155 | case $MAX_FD in #(
156 | '' | soft) :;; #(
157 | *)
158 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
159 | # shellcheck disable=SC2039,SC3045
160 | ulimit -n "$MAX_FD" ||
161 | warn "Could not set maximum file descriptor limit to $MAX_FD"
162 | esac
163 | fi
164 |
165 | # Collect all arguments for the java command, stacking in reverse order:
166 | # * args from the command line
167 | # * the main class name
168 | # * -classpath
169 | # * -D...appname settings
170 | # * --module-path (only if needed)
171 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
172 |
173 | # For Cygwin or MSYS, switch paths to Windows format before running java
174 | if "$cygwin" || "$msys" ; then
175 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
176 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
177 |
178 | JAVACMD=$( cygpath --unix "$JAVACMD" )
179 |
180 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
181 | for arg do
182 | if
183 | case $arg in #(
184 | -*) false ;; # don't mess with options #(
185 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
186 | [ -e "$t" ] ;; #(
187 | *) false ;;
188 | esac
189 | then
190 | arg=$( cygpath --path --ignore --mixed "$arg" )
191 | fi
192 | # Roll the args list around exactly as many times as the number of
193 | # args, so each arg winds up back in the position where it started, but
194 | # possibly modified.
195 | #
196 | # NB: a `for` loop captures its iteration list before it begins, so
197 | # changing the positional parameters here affects neither the number of
198 | # iterations, nor the values presented in `arg`.
199 | shift # remove old arg
200 | set -- "$@" "$arg" # push replacement arg
201 | done
202 | fi
203 |
204 |
205 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
206 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
207 |
208 | # Collect all arguments for the java command:
209 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
210 | # and any embedded shellness will be escaped.
211 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
212 | # treated as '${Hostname}' itself on the command line.
213 |
214 | set -- \
215 | "-Dorg.gradle.appname=$APP_BASE_NAME" \
216 | -classpath "$CLASSPATH" \
217 | org.gradle.wrapper.GradleWrapperMain \
218 | "$@"
219 |
220 | # Stop when "xargs" is not available.
221 | if ! command -v xargs >/dev/null 2>&1
222 | then
223 | die "xargs is not available"
224 | fi
225 |
226 | # Use "xargs" to parse quoted args.
227 | #
228 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed.
229 | #
230 | # In Bash we could simply go:
231 | #
232 | # readarray ARGS < <( xargs -n1 <<<"$var" ) &&
233 | # set -- "${ARGS[@]}" "$@"
234 | #
235 | # but POSIX shell has neither arrays nor command substitution, so instead we
236 | # post-process each arg (as a line of input to sed) to backslash-escape any
237 | # character that might be a shell metacharacter, then use eval to reverse
238 | # that process (while maintaining the separation between arguments), and wrap
239 | # the whole thing up as a single "set" statement.
240 | #
241 | # This will of course break if any of these variables contains a newline or
242 | # an unmatched quote.
243 | #
244 |
245 | eval "set -- $(
246 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
247 | xargs -n1 |
248 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
249 | tr '\n' ' '
250 | )" '"$@"'
251 |
252 | exec "$JAVACMD" "$@"
253 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @rem
2 | @rem Copyright 2015 the original author or authors.
3 | @rem
4 | @rem Licensed under the Apache License, Version 2.0 (the "License");
5 | @rem you may not use this file except in compliance with the License.
6 | @rem You may obtain a copy of the License at
7 | @rem
8 | @rem https://www.apache.org/licenses/LICENSE-2.0
9 | @rem
10 | @rem Unless required by applicable law or agreed to in writing, software
11 | @rem distributed under the License is distributed on an "AS IS" BASIS,
12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | @rem See the License for the specific language governing permissions and
14 | @rem limitations under the License.
15 | @rem
16 | @rem SPDX-License-Identifier: Apache-2.0
17 | @rem
18 |
19 | @if "%DEBUG%"=="" @echo off
20 | @rem ##########################################################################
21 | @rem
22 | @rem Gradle startup script for Windows
23 | @rem
24 | @rem ##########################################################################
25 |
26 | @rem Set local scope for the variables with windows NT shell
27 | if "%OS%"=="Windows_NT" setlocal
28 |
29 | set DIRNAME=%~dp0
30 | if "%DIRNAME%"=="" set DIRNAME=.
31 | @rem This is normally unused
32 | set APP_BASE_NAME=%~n0
33 | set APP_HOME=%DIRNAME%
34 |
35 | @rem Resolve any "." and ".." in APP_HOME to make it shorter.
36 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
37 |
38 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
39 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
40 |
41 | @rem Find java.exe
42 | if defined JAVA_HOME goto findJavaFromJavaHome
43 |
44 | set JAVA_EXE=java.exe
45 | %JAVA_EXE% -version >NUL 2>&1
46 | if %ERRORLEVEL% equ 0 goto execute
47 |
48 | echo. 1>&2
49 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
50 | echo. 1>&2
51 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
52 | echo location of your Java installation. 1>&2
53 |
54 | goto fail
55 |
56 | :findJavaFromJavaHome
57 | set JAVA_HOME=%JAVA_HOME:"=%
58 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
59 |
60 | if exist "%JAVA_EXE%" goto execute
61 |
62 | echo. 1>&2
63 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
64 | echo. 1>&2
65 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2
66 | echo location of your Java installation. 1>&2
67 |
68 | goto fail
69 |
70 | :execute
71 | @rem Setup the command line
72 |
73 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
74 |
75 |
76 | @rem Execute Gradle
77 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
78 |
79 | :end
80 | @rem End local scope for the variables with windows NT shell
81 | if %ERRORLEVEL% equ 0 goto mainEnd
82 |
83 | :fail
84 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
85 | rem the _cmd.exe /c_ return code!
86 | set EXIT_CODE=%ERRORLEVEL%
87 | if %EXIT_CODE% equ 0 set EXIT_CODE=1
88 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
89 | exit /b %EXIT_CODE%
90 |
91 | :mainEnd
92 | if "%OS%"=="Windows_NT" endlocal
93 |
94 | :omega
95 |
--------------------------------------------------------------------------------
/r8-rules.txt:
--------------------------------------------------------------------------------
1 | -dontobfuscate
2 | -dontoptimize
3 | -allowaccessmodification
4 | -keepattributes SourceFile, LineNumberTable, *Annotation*
5 |
6 | -keep class tech.httptoolkit.relocated.net.bytebuddy.agent.builder.** { *; }
7 |
8 | -keep class tech.httptoolkit.javaagent.** { *; }
9 | -keep class tech.httptoolkit.relocated.net.bytebuddy.asm.** { *; }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | rootProject.name = 'http-proxy-agent'
2 | include 'test-app'
3 |
4 |
--------------------------------------------------------------------------------
/src/main/java/reactor/netty/tcp/ProxyProvider.java:
--------------------------------------------------------------------------------
1 | package reactor.netty.tcp;
2 |
3 | import java.net.InetSocketAddress;
4 |
5 | /**
6 | * A stub with the parts of the interface we need to support v0.9 of Reactor-Netty. We compile against this, but we
7 | * *don't* include this in the resulting JAR, so references instead resolve to the real implementation, when that
8 | * is present. This is required because we can't depend on both v0.9 and v1 in the same module, and this class has
9 | * moved packages between the two.
10 | */
11 | public final class ProxyProvider {
12 |
13 | public static ProxyProvider.TypeSpec builder() {
14 | return new ProxyProvider.Build();
15 | }
16 |
17 | ProxyProvider(ProxyProvider.Build builder) {}
18 |
19 | public enum Proxy {
20 | HTTP
21 | }
22 |
23 | static final class Build implements TypeSpec, AddressSpec, Builder {
24 |
25 | Build() {}
26 |
27 | public final Builder address(InetSocketAddress address) {
28 | return this;
29 | }
30 |
31 | public final AddressSpec type(Proxy type) {
32 | return this;
33 | }
34 |
35 | public ProxyProvider build() {
36 | return new ProxyProvider(this);
37 | }
38 | }
39 |
40 | public interface TypeSpec {
41 | AddressSpec type(Proxy type);
42 | }
43 |
44 | public interface AddressSpec {
45 | Builder address(InetSocketAddress address);
46 | }
47 |
48 | public interface Builder {
49 | ProxyProvider build();
50 | }
51 | }
52 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/OverrideAllProxySelectionAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | import java.net.InetSocketAddress;
6 | import java.net.Proxy;
7 | import java.net.URI;
8 | import java.util.Collections;
9 | import java.util.List;
10 |
11 | public class OverrideAllProxySelectionAdvice {
12 |
13 | @Advice.OnMethodExit
14 | public static void selectProxy(
15 | @Advice.Argument(value = 0) URI uri,
16 | @Advice.Return(readOnly = false) List returnedProxies
17 | ) {
18 | String scheme = uri.getScheme();
19 |
20 | boolean isHttp = scheme.equals("http") || scheme.equals("https");
21 |
22 | // We read from our custom variables, since we can't access HttpProxyAgent from a bootstrapped
23 | // class, and we use namespaced properties to make this extra reliable:
24 | String proxyHost = System.getProperty("tech.httptoolkit.proxyHost");
25 | int proxyPort = Integer.parseInt(System.getProperty("tech.httptoolkit.proxyPort"));
26 |
27 | boolean isRequestToProxy = uri.getHost().equals(proxyHost) && uri.getPort() == proxyPort;
28 |
29 | // For HTTP URIs going elsewhere, we override all proxy selection globally to go via our proxy:
30 | if (isHttp && !isRequestToProxy) {
31 | returnedProxies = Collections.singletonList(
32 | new Proxy(Proxy.Type.HTTP,
33 | new InetSocketAddress(proxyHost, proxyPort)
34 | )
35 | );
36 | }
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/OverrideSslContextFieldAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import javax.net.ssl.SSLContext;
5 | import java.security.NoSuchAlgorithmException;
6 |
7 | public class OverrideSslContextFieldAdvice {
8 |
9 | @Advice.OnMethodEnter
10 | public static void beforeMethod(
11 | @Advice.FieldValue(value = "sslContext", readOnly = false) SSLContext sslContextField
12 | ) throws NoSuchAlgorithmException {
13 | sslContextField = SSLContext.getDefault();
14 | }
15 |
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/OverrideUrlConnectionProxyAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | import java.net.Proxy;
6 | import java.net.ProxySelector;
7 | import java.net.URI;
8 |
9 | public class OverrideUrlConnectionProxyAdvice {
10 |
11 | @Advice.OnMethodEnter
12 | public static void openConnection(
13 | @Advice.FieldValue(value = "protocol") String urlProtocol,
14 | @Advice.Argument(value = 0, readOnly = false) Proxy proxyArgument
15 | ) {
16 | if (urlProtocol.equals("http") || urlProtocol.equals("https")) {
17 | // We can't access HttpProxyAgent here or even thisd class, since we're in the bootstrap loader, but
18 | // we've already stored a proxy on ProxySelector for all URLs, so we can just use that directly:
19 | proxyArgument = ProxySelector.getDefault().select(
20 | URI.create("http://example.com")
21 | ).get(0);
22 | }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/ReturnProxyAddressAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import tech.httptoolkit.javaagent.HttpProxyAgent;
5 |
6 | import java.net.InetSocketAddress;
7 | import java.net.SocketAddress;
8 |
9 | public class ReturnProxyAddressAdvice {
10 | @Advice.OnMethodExit
11 | public static void proxy(@Advice.Return(readOnly = false) SocketAddress returnValue) {
12 | returnValue = new InetSocketAddress(
13 | HttpProxyAgent.getAgentProxyHost(),
14 | HttpProxyAgent.getAgentProxyPort()
15 | );
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/ReturnProxyAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import tech.httptoolkit.javaagent.HttpProxyAgent;
5 |
6 | import java.net.InetSocketAddress;
7 | import java.net.Proxy;
8 |
9 | public class ReturnProxyAdvice {
10 | @Advice.OnMethodExit
11 | public static void proxy(@Advice.Return(readOnly = false) Proxy returnValue) {
12 | returnValue = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
13 | HttpProxyAgent.getAgentProxyHost(),
14 | HttpProxyAgent.getAgentProxyPort()
15 | ));
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/ReturnProxySelectorAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | import java.net.ProxySelector;
6 | import java.util.Optional;
7 |
8 | public class ReturnProxySelectorAdvice {
9 | @Advice.OnMethodExit
10 | public static void proxy(@Advice.Return(readOnly = false) Optional returnValue) {
11 | returnValue = Optional.of(ProxySelector.getDefault());
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/ReturnSslContextAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | import javax.net.ssl.SSLContext;
6 | import java.security.NoSuchAlgorithmException;
7 |
8 | public class ReturnSslContextAdvice {
9 | @Advice.OnMethodExit
10 | public static void sslContext(@Advice.Return(readOnly = false) SSLContext returnValue) {
11 | try {
12 | returnValue = SSLContext.getDefault();
13 | } catch (NoSuchAlgorithmException e) {
14 | throw new RuntimeException(e);
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/ReturnSslSocketFactoryAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | import javax.net.ssl.SSLContext;
6 | import javax.net.ssl.SSLSocketFactory;
7 | import java.security.NoSuchAlgorithmException;
8 |
9 | public class ReturnSslSocketFactoryAdvice {
10 | @Advice.OnMethodExit
11 | public static void sslSocketFactory(@Advice.Return(readOnly = false) SSLSocketFactory returnValue) {
12 | try {
13 | returnValue = SSLContext.getDefault().getSocketFactory();
14 | } catch (NoSuchAlgorithmException e) {
15 | throw new RuntimeException(e);
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/SkipMethodAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | // General purpose advice which skips a given method, returning the default value for its type
6 | // (so usually null) if there is a return value, and silently doing nothing.
7 | public class SkipMethodAdvice {
8 | @Advice.OnMethodEnter(skipOn = Advice.OnNonDefaultValue.class) // => skip if we return true (or similar)
9 | public static boolean skipMethod() {
10 | return true; // Skip the method body entirely
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/akka/OverrideHttpSettingsAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.akka;
2 |
3 | import akka.http.javadsl.ClientTransport;
4 | import akka.http.javadsl.ConnectionContext;
5 | import akka.http.javadsl.settings.ClientConnectionSettings;
6 | import net.bytebuddy.asm.Advice;
7 | import net.bytebuddy.implementation.bytecode.assign.Assigner;
8 | import tech.httptoolkit.javaagent.HttpProxyAgent;
9 |
10 | import java.net.InetSocketAddress;
11 | import java.util.Arrays;
12 |
13 | public class OverrideHttpSettingsAdvice {
14 |
15 | public static final boolean hasHttpsSettingsMethod =
16 | Arrays.stream(ConnectionContext.class.getDeclaredMethods())
17 | .anyMatch(method -> method.getName().equals("httpsClient"));
18 |
19 | public static final ConnectionContext interceptedConnectionContext = hasHttpsSettingsMethod
20 | // For 10.2+:
21 | ? ConnectionContext.httpsClient(HttpProxyAgent.getInterceptedSslContext())
22 | // For everything before then:
23 | : ConnectionContext.https(HttpProxyAgent.getInterceptedSslContext());
24 |
25 | @Advice.OnMethodEnter
26 | public static void beforeOutgoingConnection(
27 | @Advice.Argument(value = 2, readOnly = false, typing = Assigner.Typing.DYNAMIC) ClientConnectionSettings clientSettings,
28 | @Advice.Argument(value = 3, readOnly = false, typing = Assigner.Typing.DYNAMIC) ConnectionContext connectionContext
29 | ) {
30 | // Change all new outgoing connections to use the proxy:
31 | clientSettings = clientSettings.withTransport(
32 | ClientTransport.httpsProxy(new InetSocketAddress(
33 | HttpProxyAgent.getAgentProxyHost(),
34 | HttpProxyAgent.getAgentProxyPort()
35 | ))
36 | );
37 |
38 | // Change all new outgoing connections to trust our certificate:
39 | if (connectionContext.isSecure()) {
40 | connectionContext = OverrideHttpSettingsAdvice.interceptedConnectionContext;
41 | }
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/akka/ResetOldGatewaysAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.akka;
2 |
3 | import akka.http.impl.settings.HostConnectionPoolSetup;
4 | import akka.http.scaladsl.ClientTransport;
5 | import net.bytebuddy.asm.Advice;
6 | import scala.concurrent.Await;
7 | import scala.concurrent.Future;
8 | import scala.concurrent.duration.Duration;
9 |
10 | import java.lang.reflect.Method;
11 | import java.util.Collections;
12 | import java.util.Set;
13 | import java.util.WeakHashMap;
14 | import java.util.concurrent.TimeUnit;
15 | import java.util.concurrent.TimeoutException;
16 |
17 | // This is very similar to ResetOldPoolsAdvice, but applies to older Akka setups, which use many PoolGateway instances,
18 | // one per config, rather than one PoolMaster instance. Otherwise the logic should be identical.
19 | public class ResetOldGatewaysAdvice {
20 |
21 | public static Set resetPoolSetups = Collections.newSetFromMap(
22 | Collections.synchronizedMap(new WeakHashMap<>())
23 | );
24 |
25 | @Advice.OnMethodEnter
26 | public static void beforeDispatchRequest(
27 | @Advice.This Object thisPoolGateway,
28 | @Advice.FieldValue(value = "hcps") HostConnectionPoolSetup poolSetup
29 | ) throws Exception {
30 | // If a pool config has been changed to use our proxy already, then we're perfect
31 | ClientTransport transport = poolSetup.setup().settings().transport();
32 | boolean alreadyIntercepted = transport == ResetPoolSetupAdvice.interceptedProxyTransport;
33 | // If not, it's still OK, as long as we've previously reset the pool to ensure the connection was
34 | // re-established (we hook connection setup too, so all new conns are intercepted, even with old config)
35 | boolean alreadyReset = resetPoolSetups.contains(poolSetup);
36 |
37 | if (alreadyIntercepted || alreadyReset) return;
38 |
39 | // Otherwise this is a request to use a pre-existing connection pool which probably has connections open that
40 | // aren't using our proxy. We shutdown the pool before the request. It'll be restarted automatically when
41 | // the request does go through, but this ensures we re-establish connections (so it definitely gets intercepted)
42 | Method shutdownMethod = thisPoolGateway.getClass().getDeclaredMethod("shutdown");
43 |
44 | Future> shutdownFuture = (Future>) shutdownMethod.invoke(thisPoolGateway);
45 |
46 | // We wait a little, just to ensure the shutdown is definitely started before this request is dispatched.
47 | try {
48 | Await.result(shutdownFuture, Duration.apply(10, TimeUnit.MILLISECONDS));
49 | } catch (TimeoutException ignored) {}
50 |
51 | // Lastly, we remember this pool setup, so that we don't unnecessarily reset it again in future:
52 | resetPoolSetups.add(poolSetup);
53 | }
54 |
55 | }
56 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/akka/ResetOldPoolsAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.akka;
2 |
3 | import akka.http.impl.engine.client.PoolId;
4 | import akka.http.scaladsl.ClientTransport;
5 | import net.bytebuddy.asm.Advice;
6 | import scala.concurrent.Await;
7 | import scala.concurrent.Future;
8 | import scala.concurrent.duration.Duration;
9 |
10 | import java.lang.reflect.Method;
11 | import java.util.Collections;
12 | import java.util.Set;
13 | import java.util.WeakHashMap;
14 | import java.util.concurrent.TimeUnit;
15 | import java.util.concurrent.TimeoutException;
16 |
17 | public class ResetOldPoolsAdvice {
18 |
19 | public static Set resetPoolIds = Collections.newSetFromMap(
20 | Collections.synchronizedMap(new WeakHashMap<>())
21 | );
22 |
23 | @Advice.OnMethodEnter
24 | public static void beforeDispatchRequest(
25 | @Advice.This Object thisPoolMaster,
26 | @Advice.Argument(value = 0) PoolId poolId
27 | ) throws Exception {
28 | // If a pool config has been changed to use our proxy already, then we're perfect
29 | ClientTransport transport = poolId.hcps().setup().settings().transport();
30 | boolean alreadyIntercepted = transport == ResetPoolSetupAdvice.interceptedProxyTransport;
31 | // If not, it's still OK, as long as we've previously reset the pool to ensure the connection was
32 | // re-established (we hook connection setup too, so all new conns are intercepted, even with old config)
33 | boolean alreadyReset = resetPoolIds.contains(poolId);
34 |
35 | if (alreadyIntercepted || alreadyReset) return;
36 |
37 | // Otherwise this is a request to use a pre-existing connection pool which probably has connections open that
38 | // aren't using our proxy. We shutdown the pool before the request. It'll be restarted automatically when
39 | // the request does go through, but this ensures we re-establish connections (so it definitely gets intercepted)
40 | Method shutdownMethod = thisPoolMaster.getClass()
41 | .getDeclaredMethod("shutdown", PoolId.class);
42 |
43 | Future> shutdownFuture = (Future>) shutdownMethod.invoke(thisPoolMaster, poolId);
44 |
45 | // We wait a little, just to ensure the shutdown is definitely started before this request is dispatched.
46 | try {
47 | Await.result(shutdownFuture, Duration.apply(10, TimeUnit.MILLISECONDS));
48 | } catch (TimeoutException ignored) {}
49 |
50 | // Lastly, we remember this pool id, so that we don't unnecessarily reset it again in future:
51 | resetPoolIds.add(poolId);
52 | }
53 |
54 | }
55 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/akka/ResetPoolSetupAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.akka;
2 |
3 | import akka.http.scaladsl.ClientTransport;
4 | import akka.http.scaladsl.settings.ConnectionPoolSettings;
5 | import akka.http.javadsl.ConnectionContext;
6 | import net.bytebuddy.asm.Advice;
7 | import net.bytebuddy.implementation.bytecode.assign.Assigner;
8 | import tech.httptoolkit.javaagent.HttpProxyAgent;
9 |
10 | import java.net.InetSocketAddress;
11 |
12 | public class ResetPoolSetupAdvice {
13 |
14 | // We use this to avoid re-instantiating the proxy endlessly, but also to recognize intercepted
15 | // and pre-existing settings configurations when they're used.
16 | public static ClientTransport interceptedProxyTransport = ClientTransport.httpsProxy(
17 | new InetSocketAddress(
18 | HttpProxyAgent.getAgentProxyHost(),
19 | HttpProxyAgent.getAgentProxyPort()
20 | )
21 | );
22 |
23 | @Advice.OnMethodExit
24 | public static void afterConstructor(
25 | @Advice.FieldValue(value = "settings", readOnly = false, typing = Assigner.Typing.DYNAMIC) ConnectionPoolSettings settings,
26 | @Advice.FieldValue(value = "connectionContext", readOnly = false, typing = Assigner.Typing.DYNAMIC) ConnectionContext connContext
27 | ) {
28 | // Change all new outgoing connections to use the proxy:
29 | settings = settings.withTransport(interceptedProxyTransport);
30 |
31 | // Change all new outgoing connections to trust our certificate:
32 | if (connContext.isSecure()) {
33 | connContext = OverrideHttpSettingsAdvice.interceptedConnectionContext;
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheCustomSslProtocolSocketFactory.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import org.apache.commons.httpclient.params.HttpConnectionParams;
4 | import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
5 | import tech.httptoolkit.javaagent.HttpProxyAgent;
6 |
7 | import javax.net.SocketFactory;
8 | import javax.net.ssl.SSLSocketFactory;
9 | import java.io.IOException;
10 | import java.net.*;
11 |
12 | public class ApacheCustomSslProtocolSocketFactory implements SecureProtocolSocketFactory {
13 |
14 | private final SSLSocketFactory interceptedSocketFactory = HttpProxyAgent
15 | .getInterceptedSslContext()
16 | .getSocketFactory();
17 |
18 | @Override
19 | public Socket createSocket(String host, int port) throws IOException {
20 | return interceptedSocketFactory.createSocket(host, port);
21 | }
22 |
23 | @Override
24 | public Socket createSocket(String host, int port, InetAddress localAddress, int localPort) throws IOException {
25 | return interceptedSocketFactory.createSocket(host, port, localAddress, localPort);
26 | }
27 |
28 | @Override
29 | public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
30 | return interceptedSocketFactory.createSocket(socket, host, port, autoClose);
31 | }
32 |
33 | @Override
34 | public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException {
35 | // Marginally more complicated logic here unfortunately, since timeout isn't natively
36 | // supported. Minimal implementation taken from the existing lib implementations:
37 | if (params == null) {
38 | throw new IllegalArgumentException("Parameters may not be null");
39 | }
40 | int timeout = params.getConnectionTimeout();
41 | Socket socket;
42 |
43 | SocketFactory socketfactory = SSLSocketFactory.getDefault();
44 | if (timeout == 0) {
45 | socket = socketfactory.createSocket(host, port, localAddress, localPort);
46 | } else {
47 | socket = socketfactory.createSocket();
48 | SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
49 | SocketAddress remoteAddr = new InetSocketAddress(host, port);
50 | socket.bind(localAddr);
51 | socket.connect(remoteAddr, timeout);
52 | }
53 |
54 | return socket;
55 | }
56 | }
57 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheOverrideProxyHostFieldAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import org.apache.commons.httpclient.ProxyHost;
5 | import tech.httptoolkit.javaagent.HttpProxyAgent;
6 |
7 | public class ApacheOverrideProxyHostFieldAdvice {
8 |
9 | @Advice.OnMethodExit
10 | public static void resetProxyHost(
11 | @Advice.FieldValue(value = "proxyHost", readOnly = false) ProxyHost proxyHostField
12 | ) {
13 | // After creating/changing HostConfiguration we override the proxy field:
14 | proxyHostField = new ProxyHost(
15 | HttpProxyAgent.getAgentProxyHost(),
16 | HttpProxyAgent.getAgentProxyPort()
17 | );
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheReturnCustomSslProtocolSocketFactoryAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
5 |
6 | public class ApacheReturnCustomSslProtocolSocketFactoryAdvice {
7 |
8 | @Advice.OnMethodExit
9 | public static void getSocketFactory(
10 | @Advice.FieldValue(value = "secure") boolean isSecure,
11 | @Advice.Return(readOnly = false) ProtocolSocketFactory returnValue
12 | ) {
13 | if (isSecure) {
14 | returnValue = new ApacheCustomSslProtocolSocketFactory();
15 | }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheSetConfigProxyHostAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import org.apache.commons.httpclient.HostConfiguration;
5 |
6 | public class ApacheSetConfigProxyHostAdvice {
7 |
8 | @Advice.OnMethodEnter
9 | public static void beforeMakingRequests(
10 | @Advice.FieldValue(value = "hostConfiguration") HostConfiguration hostConfiguration
11 | ) {
12 | // Elsewhere, we hook setProxyHost to reset the proxy to our configured version whenever it's called.
13 | // Then, here we hook various methods to call it before they use the config:
14 | hostConfiguration.setProxyHost(null); // null here is ignored as this method is already hooked
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheSetSslSocketFactoryAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 |
5 | import javax.net.ssl.SSLContext;
6 | import java.lang.reflect.Field;
7 | import java.util.Arrays;
8 |
9 | public class ApacheSetSslSocketFactoryAdvice {
10 |
11 | @Advice.OnMethodEnter
12 | public static void beforeCreateSocket(@Advice.This Object thisFactory) throws Exception {
13 | // Before creating the socket - replace the SSL context so the new socket trusts us.
14 |
15 | boolean intercepted = false;
16 | for (String factoryFieldName : Arrays.asList("socketfactory", "socketFactory")) {
17 | try {
18 | // Detect which field(s) are present on this class
19 | Field field = getDeclaredFieldInClassTree(thisFactory.getClass(), factoryFieldName);
20 |
21 | // Allow ourselves to change the socket factory value
22 | field.setAccessible(true);
23 |
24 | // Overwrite the socket factory with our own:
25 | field.set(thisFactory, SSLContext.getDefault().getSocketFactory());
26 | intercepted = true;
27 | } catch (NoSuchFieldException ignored) { }
28 | }
29 |
30 | if (!intercepted) {
31 | throw new IllegalStateException("Apache HttpClient interception setup failed");
32 | }
33 | }
34 |
35 | public static Field getDeclaredFieldInClassTree(Class> type, String fieldName) throws NoSuchFieldException {
36 | for (Class> clazz = type; clazz != null; clazz = clazz.getSuperclass()) {
37 | try {
38 | return clazz.getDeclaredField(fieldName);
39 | } catch (NoSuchFieldException ignored) { }
40 | }
41 | throw new NoSuchFieldException();
42 | }
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheV4ReturnProxyRouteAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import net.bytebuddy.implementation.bytecode.assign.Assigner;
5 | import org.apache.http.HttpHost;
6 | import org.apache.http.conn.routing.HttpRoute;
7 |
8 | import java.net.*;
9 |
10 | public class ApacheV4ReturnProxyRouteAdvice {
11 | @Advice.OnMethodExit
12 | public static void determineRoute(
13 | // We type this dynamically, because in some cases (notably Gradle) we seemingly can't reach the
14 | // HttpRoute type from ByteBuddy, only at runtime.
15 | @Advice.Return(readOnly = false, typing = Assigner.Typing.DYNAMIC) Object returnValue
16 | ) {
17 | HttpRoute existingValue = (HttpRoute) returnValue;
18 | // We guarantee that the default proxy selector is always our own. This ensures that we can
19 | // always grab the proxy URL without needing to access our injected classes.
20 | Proxy proxy = ProxySelector.getDefault().select(URI.create("https://example.com")).get(0);
21 | InetSocketAddress proxyAddress = (InetSocketAddress) proxy.address();
22 |
23 | returnValue = new HttpRoute(
24 | existingValue.getTargetHost(),
25 | existingValue.getLocalAddress(),
26 | new HttpHost(proxyAddress.getHostString(), proxyAddress.getPort()),
27 | existingValue.isSecure()
28 | );
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/apacheclient/ApacheV5ReturnProxyRouteAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.apacheclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import org.apache.hc.core5.http.HttpHost;
5 | import org.apache.hc.client5.http.HttpRoute;
6 | import tech.httptoolkit.javaagent.HttpProxyAgent;
7 |
8 | public class ApacheV5ReturnProxyRouteAdvice {
9 | @Advice.OnMethodExit
10 | public static void determineRoute(
11 | @Advice.Return(readOnly = false) HttpRoute returnValue
12 | ) {
13 | returnValue = new HttpRoute(
14 | returnValue.getTargetHost(),
15 | returnValue.getLocalAddress(),
16 | new HttpHost(
17 | HttpProxyAgent.getAgentProxyHost(),
18 | HttpProxyAgent.getAgentProxyPort()
19 | ),
20 | returnValue.isSecure()
21 | );
22 | }
23 | }
24 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/asynchttpclient/AsyncHttpClientReturnProxySelectorAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.asynchttpclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import org.asynchttpclient.proxy.ProxyServer;
5 | import org.asynchttpclient.proxy.ProxyServerSelector;
6 | import tech.httptoolkit.javaagent.HttpProxyAgent;
7 |
8 | public class AsyncHttpClientReturnProxySelectorAdvice {
9 |
10 | public static ProxyServerSelector proxyServerSelector = uri -> new ProxyServer.Builder(
11 | HttpProxyAgent.getAgentProxyHost(),
12 | HttpProxyAgent.getAgentProxyPort()
13 | ).build();
14 |
15 | @Advice.OnMethodExit
16 | public static void getProxyServerSelector(@Advice.Return(readOnly = false) ProxyServerSelector returnValue) {
17 | returnValue = proxyServerSelector;
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/asynchttpclient/AsyncHttpClientReturnSslContextAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.asynchttpclient;
2 |
3 | import io.netty.handler.ssl.SslContext;
4 | import io.netty.handler.ssl.SslContextBuilder;
5 | import net.bytebuddy.asm.Advice;
6 | import tech.httptoolkit.javaagent.HttpProxyAgent;
7 |
8 | import javax.net.ssl.SSLException;
9 |
10 | public class AsyncHttpClientReturnSslContextAdvice {
11 | @Advice.OnMethodExit
12 | public static void getSslContext(@Advice.Return(readOnly = false) SslContext returnValue) {
13 | try {
14 | returnValue = SslContextBuilder
15 | .forClient()
16 | .trustManager(HttpProxyAgent.getInterceptedTrustManagerFactory())
17 | .build();
18 | } catch (SSLException e) {
19 | throw new RuntimeException(e);
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/main/java/tech/httptoolkit/javaagent/advice/asynchttpclient/AsyncHttpResetSslEngineFactoryAdvice.java:
--------------------------------------------------------------------------------
1 | package tech.httptoolkit.javaagent.advice.asynchttpclient;
2 |
3 | import net.bytebuddy.asm.Advice;
4 | import org.asynchttpclient.AsyncHttpClientConfig;
5 | import org.asynchttpclient.SslEngineFactory;
6 |
7 | import java.util.Collections;
8 | import java.util.Set;
9 | import java.util.WeakHashMap;
10 |
11 | public class AsyncHttpResetSslEngineFactoryAdvice {
12 |
13 | // Track each ChannelManager with a weak ref, to avoid unnecessary reflection overhead by only
14 | // initializing them once, instead of every request
15 | public static Set