-
Notifications
You must be signed in to change notification settings - Fork 9.1k
/
Main.kt
302 lines (255 loc) · 9.55 KB
/
Main.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
* Copyright (C) 2014 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3.curl
import java.io.IOException
import java.security.cert.X509Certificate
import java.util.Properties
import java.util.concurrent.TimeUnit.SECONDS
import java.util.logging.ConsoleHandler
import java.util.logging.Level
import java.util.logging.LogRecord
import java.util.logging.Logger
import java.util.logging.SimpleFormatter
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSocketFactory
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager
import kotlin.system.exitProcess
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.curl.Main.Companion.NAME
import okhttp3.internal.format
import okhttp3.internal.http.StatusLine
import okhttp3.internal.http2.Http2
import okhttp3.internal.platform.Platform
import okhttp3.logging.HttpLoggingInterceptor
import okhttp3.logging.LoggingEventListener
import okio.sink
import picocli.CommandLine
import picocli.CommandLine.Command
import picocli.CommandLine.IVersionProvider
import picocli.CommandLine.Option
import picocli.CommandLine.Parameters
@Command(name = NAME, description = ["A curl for the next-generation web."],
mixinStandardHelpOptions = true, versionProvider = Main.VersionProvider::class)
class Main : Runnable {
@Option(names = ["-X", "--request"], description = ["Specify request command to use"])
var method: String? = null
@Option(names = ["-d", "--data"], description = ["HTTP POST data"])
var data: String? = null
@Option(names = ["-H", "--header"], description = ["Custom header to pass to server"])
var headers: MutableList<String>? = null
@Option(names = ["-A", "--user-agent"], description = ["User-Agent to send to server"])
var userAgent = NAME + "/" + versionString()
@Option(names = ["--connect-timeout"],
description = ["Maximum time allowed for connection (seconds)"])
var connectTimeout = DEFAULT_TIMEOUT
@Option(names = ["--read-timeout"],
description = ["Maximum time allowed for reading data (seconds)"])
var readTimeout = DEFAULT_TIMEOUT
@Option(names = ["--call-timeout"],
description = ["Maximum time allowed for the entire call (seconds)"])
var callTimeout = DEFAULT_TIMEOUT
@Option(names = ["-L", "--location"], description = ["Follow redirects"])
var followRedirects: Boolean = false
@Option(names = ["-k", "--insecure"], description = ["Allow connections to SSL sites without certs"])
var allowInsecure: Boolean = false
@Option(names = ["-i", "--include"], description = ["Include protocol headers in the output"])
var showHeaders: Boolean = false
@Option(names = ["--frames"], description = ["Log HTTP/2 frames to STDERR"])
var showHttp2Frames: Boolean = false
@Option(names = ["-e", "--referer"], description = ["Referer URL"])
var referer: String? = null
@Option(names = ["-v", "--verbose"], description = ["Makes $NAME verbose during the operation"])
var verbose: Boolean = false
@Option(names = ["--ssldebug"], description = ["Output SSL Debug"])
var sslDebug: Boolean = false
@Option(names = ["--completionScript"], hidden = true)
var completionScript: Boolean = false
@Parameters(paramLabel = "url", description = ["Remote resource URL"])
var url: String? = null
private lateinit var client: OkHttpClient
override fun run() {
if (completionScript) {
println(picocli.AutoComplete.bash("okcurl", CommandLine(Main())))
return
}
if (showHttp2Frames) {
enableHttp2FrameLogging()
}
if (sslDebug) {
enableSslDebugging()
}
client = createClient()
val request = createRequest()
try {
val response = client.newCall(request).execute()
if (showHeaders) {
println(StatusLine.get(response))
val headers = response.headers
for ((name, value) in headers) {
println("$name: $value")
}
println()
}
// Stream the response to the System.out as it is returned from the server.
val out = System.out.sink()
val source = response.body!!.source()
while (!source.exhausted()) {
out.write(source.buffer, source.buffer.size)
out.flush()
}
response.body!!.close()
} catch (e: IOException) {
e.printStackTrace()
} finally {
close()
}
}
private fun createClient(): OkHttpClient {
val builder = OkHttpClient.Builder()
builder.followSslRedirects(followRedirects)
if (connectTimeout != DEFAULT_TIMEOUT) {
builder.connectTimeout(connectTimeout.toLong(), SECONDS)
}
if (readTimeout != DEFAULT_TIMEOUT) {
builder.readTimeout(readTimeout.toLong(), SECONDS)
}
if (callTimeout != DEFAULT_TIMEOUT) {
builder.callTimeout(callTimeout.toLong(), SECONDS)
}
if (allowInsecure) {
val trustManager = createInsecureTrustManager()
val sslSocketFactory = createInsecureSslSocketFactory(trustManager)
builder.sslSocketFactory(sslSocketFactory, trustManager)
builder.hostnameVerifier(createInsecureHostnameVerifier())
}
if (verbose) {
val logger = HttpLoggingInterceptor.Logger(::println)
builder.eventListenerFactory(LoggingEventListener.Factory(logger))
}
return builder.build()
}
public fun createRequest(): Request {
val request = Request.Builder()
val requestMethod = method ?: if (data != null) "POST" else "GET"
request.url(url!!)
data?.let {
request.method(requestMethod, it.toRequestBody(mediaType()))
}
for (header in headers.orEmpty()) {
val parts = header.split(':', limit = 2)
request.header(parts[0], parts[1])
}
referer?.let {
request.header("Referer", it)
}
request.header("User-Agent", userAgent)
return request.build()
}
private fun mediaType(): MediaType? {
val mimeType = headers?.let {
for (header in it) {
val parts = header.split(':', limit = 2)
if ("Content-Type".equals(parts[0], ignoreCase = true)) {
it.remove(header)
return@let parts[1].trim()
}
}
return@let null
} ?: "application/x-www-form-urlencoded"
return mimeType.toMediaTypeOrNull()
}
private fun close() {
client.connectionPool.evictAll() // Close any persistent connections.
client.dispatcher.executorService.shutdownNow()
}
class VersionProvider : IVersionProvider {
override fun getVersion(): Array<String> {
return arrayOf(
"$NAME ${versionString()}",
"Protocols: ${Protocol.values().joinToString(", ")}",
"Platform: ${Platform.get()::class.java.simpleName}"
)
}
}
companion object {
internal const val NAME = "okcurl"
internal const val DEFAULT_TIMEOUT = -1
private var frameLogger: Logger? = null
private var sslLogger: Logger? = null
@JvmStatic
fun main(args: Array<String>) {
if (System.getProperty("javax.net.debug") == null) {
System.setProperty("javax.net.debug", "")
}
exitProcess(CommandLine(Main()).execute(*args))
}
private fun versionString(): String? {
val prop = Properties()
Main::class.java.getResourceAsStream("/okcurl-version.properties").use {
prop.load(it)
}
return prop.getProperty("version", "dev")
}
private fun createInsecureTrustManager(): X509TrustManager = object : X509TrustManager {
override fun checkClientTrusted(chain: Array<X509Certificate>, authType: String) {}
override fun checkServerTrusted(chain: Array<X509Certificate>, authType: String) {}
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
}
private fun createInsecureSslSocketFactory(trustManager: TrustManager): SSLSocketFactory =
Platform.get().newSSLContext().apply {
init(null, arrayOf(trustManager), null)
}.socketFactory
private fun createInsecureHostnameVerifier(): HostnameVerifier =
HostnameVerifier { _, _ -> true }
private fun enableHttp2FrameLogging() {
frameLogger = Logger.getLogger(Http2::class.java.name).apply {
level = Level.FINE
addHandler(ConsoleHandler().apply {
level = Level.FINE
formatter = object : SimpleFormatter() {
override fun format(record: LogRecord): String {
return format("%s%n", record.message)
}
}
})
}
}
private fun enableSslDebugging() {
sslLogger = Logger.getLogger("javax.net.ssl").apply {
level = Level.FINE
addHandler(ConsoleHandler().apply {
level = Level.FINE
formatter = object : SimpleFormatter() {
override fun format(record: LogRecord): String {
val parameters = record.parameters
if (parameters != null) {
return format("%s%n%s%n", record.message, record.parameters.first())
} else {
return format("%s%n", record.message)
}
}
}
})
}
}
}
}