-
Notifications
You must be signed in to change notification settings - Fork 1k
/
WebSocketDeflateExtension.kt
228 lines (179 loc) · 8 KB
/
WebSocketDeflateExtension.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
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.websocket
import io.ktor.util.*
import io.ktor.websocket.internals.*
import java.util.*
import java.util.zip.*
private const val SERVER_MAX_WINDOW_BITS: String = "server_max_window_bits"
private const val CLIENT_NO_CONTEXT_TAKEOVER = "client_no_context_takeover"
private const val SERVER_NO_CONTEXT_TAKEOVER = "server_no_context_takeover"
private const val CLIENT_MAX_WINDOW_BITS = "client_max_window_bits"
private const val PERMESSAGE_DEFLATE = "permessage-deflate"
private const val MAX_WINDOW_BITS: Int = 15
private const val MIN_WINDOW_BITS: Int = 8
/**
* Compress and decompress WebSocket frames to reduce amount of transferred bytes.
*
* Usage
* ```kotlin
* install(WebSockets) {
* extensions {
* install(WebSocketDeflateExtension)
* }
* }
* ```
*
* Implements WebSocket deflate extension from [RFC-7692](https://tools.ietf.org/html/rfc7692).
* This implementation is using window size = 15 due to limitations of [Deflater] implementation.
*/
public class WebSocketDeflateExtension internal constructor(
private val config: Config
) : WebSocketExtension<WebSocketDeflateExtension.Config> {
override val factory: WebSocketExtensionFactory<Config, out WebSocketExtension<Config>> = WebSocketDeflateExtension
override val protocols: List<WebSocketExtensionHeader> = config.build()
private val inflater = Inflater(true)
private val deflater = Deflater(config.compressionLevel, true)
internal var outgoingNoContextTakeover: Boolean = false
internal var incomingNoContextTakeover: Boolean = false
override fun clientNegotiation(negotiatedProtocols: List<WebSocketExtensionHeader>): Boolean {
val protocol = negotiatedProtocols.find { it.name == PERMESSAGE_DEFLATE } ?: return false
incomingNoContextTakeover = config.serverNoContextTakeOver
outgoingNoContextTakeover = config.clientNoContextTakeOver
for ((key, value) in protocol.parseParameters()) {
when (key) {
SERVER_MAX_WINDOW_BITS -> {
// This value is a hint for a client and can be ignored.
}
CLIENT_MAX_WINDOW_BITS -> {
if (value.isBlank()) continue
check(value.toInt() == MAX_WINDOW_BITS) { "Only $MAX_WINDOW_BITS window size is supported." }
}
SERVER_NO_CONTEXT_TAKEOVER -> {
check(value.isBlank()) {
"WebSocket $PERMESSAGE_DEFLATE extension parameter $SERVER_NO_CONTEXT_TAKEOVER shouldn't " +
"have a value. Current: $value"
}
incomingNoContextTakeover = true
}
CLIENT_NO_CONTEXT_TAKEOVER -> {
check(value.isBlank()) {
"WebSocket $PERMESSAGE_DEFLATE extension parameter $CLIENT_NO_CONTEXT_TAKEOVER shouldn't " +
"have a value. Current: $value"
}
outgoingNoContextTakeover = true
}
}
}
return true
}
override fun serverNegotiation(requestedProtocols: List<WebSocketExtensionHeader>): List<WebSocketExtensionHeader> {
val protocol = requestedProtocols.find { it.name == PERMESSAGE_DEFLATE } ?: return emptyList()
val parameters = mutableListOf<String>()
for ((key, value) in protocol.parseParameters()) {
when (key.lowercase(Locale.getDefault())) {
SERVER_MAX_WINDOW_BITS -> {
check(value.toInt() == MAX_WINDOW_BITS) { "Only $MAX_WINDOW_BITS window size is supported" }
}
CLIENT_MAX_WINDOW_BITS -> {
// This value is a hint for a server and can be ignored.
}
SERVER_NO_CONTEXT_TAKEOVER -> {
check(value.isBlank())
outgoingNoContextTakeover = true
parameters.add(SERVER_NO_CONTEXT_TAKEOVER)
}
CLIENT_NO_CONTEXT_TAKEOVER -> {
check(value.isBlank())
incomingNoContextTakeover = true
parameters.add(CLIENT_NO_CONTEXT_TAKEOVER)
}
else -> error("Unsupported extension parameter: ($key, $value)")
}
}
return listOf(WebSocketExtensionHeader(PERMESSAGE_DEFLATE, parameters))
}
override fun processOutgoingFrame(frame: Frame): Frame {
if (frame !is Frame.Text && frame !is Frame.Binary) return frame
if (!config.compressCondition(frame)) return frame
val deflated = deflater.deflateFully(frame.data)
if (outgoingNoContextTakeover) {
deflater.reset()
}
return Frame.byType(frame.fin, frame.frameType, deflated, rsv1, frame.rsv2, frame.rsv3)
}
override fun processIncomingFrame(frame: Frame): Frame {
if (!frame.rsv1 || (frame !is Frame.Text && frame !is Frame.Binary)) return frame
val inflated = inflater.inflateFully(frame.data)
if (incomingNoContextTakeover) {
inflater.reset()
}
return Frame.byType(frame.fin, frame.frameType, inflated, !rsv1, frame.rsv2, frame.rsv3)
}
/**
* WebSocket deflate extension configuration.
*/
public class Config {
/**
* Specify if the client drops the deflater state (reset the window) after each frame.
*/
public var clientNoContextTakeOver: Boolean = false
/**
* Specify if the server drops the deflater state (reset the window) after each frame.
*/
public var serverNoContextTakeOver: Boolean = false
/**
* Compression level that is used for outgoing frames in the [Deflate] instance.
*/
public var compressionLevel: Int = Deflater.DEFAULT_COMPRESSION
internal var manualConfig: (MutableList<WebSocketExtensionHeader>) -> Unit = {}
internal var compressCondition: (Frame) -> Boolean = { true }
/**
* Configure which protocols should send the client.
*/
public fun configureProtocols(block: (protocols: MutableList<WebSocketExtensionHeader>) -> Unit) {
val old = manualConfig
manualConfig = {
old(it)
block(it)
}
}
/**
* Indicates if the outgoing frame should be compressed.
*
* Compress the frame only if all conditions passed.
*/
public fun compressIf(block: (frame: Frame) -> Boolean) {
val old = compressCondition
compressCondition = { block(it) && old(it) }
}
/**
* Specify the minimum size of frame for compression.
*/
public fun compressIfBiggerThan(bytes: Int) {
compressIf { frame -> frame.data.size > bytes }
}
internal fun build(): List<WebSocketExtensionHeader> {
val result = mutableListOf<WebSocketExtensionHeader>()
val parameters = mutableListOf<String>()
if (clientNoContextTakeOver) {
parameters += CLIENT_NO_CONTEXT_TAKEOVER
}
if (serverNoContextTakeOver) {
parameters += SERVER_NO_CONTEXT_TAKEOVER
}
result += WebSocketExtensionHeader(PERMESSAGE_DEFLATE, parameters)
manualConfig(result)
return result
}
}
public companion object : WebSocketExtensionFactory<Config, WebSocketDeflateExtension> {
override val key: AttributeKey<WebSocketDeflateExtension> = AttributeKey("WebsocketDeflateExtension")
override val rsv1: Boolean = true
override val rsv2: Boolean = false
override val rsv3: Boolean = false
override fun install(config: Config.() -> Unit): WebSocketDeflateExtension =
WebSocketDeflateExtension(Config().apply(config))
}
}