forked from jetty/jetty.project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CompressExtension.java
628 lines (548 loc) · 19 KB
/
CompressExtension.java
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
//
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
//
package org.eclipse.jetty.websocket.common.extensions.compress;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import java.util.zip.ZipException;
import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.IteratingCallback;
import org.eclipse.jetty.util.compression.DeflaterPool;
import org.eclipse.jetty.util.compression.InflaterPool;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;
import org.eclipse.jetty.websocket.api.BatchMode;
import org.eclipse.jetty.websocket.api.WriteCallback;
import org.eclipse.jetty.websocket.api.extensions.Frame;
import org.eclipse.jetty.websocket.common.OpCode;
import org.eclipse.jetty.websocket.common.extensions.AbstractExtension;
import org.eclipse.jetty.websocket.common.frames.DataFrame;
public abstract class CompressExtension extends AbstractExtension
{
protected static final byte[] TAIL_BYTES = new byte[]{0x00, 0x00, (byte)0xFF, (byte)0xFF};
protected static final ByteBuffer TAIL_BYTES_BUF = ByteBuffer.wrap(TAIL_BYTES);
private static final Logger LOG = Log.getLogger(CompressExtension.class);
/**
* Never drop tail bytes 0000FFFF, from any frame type
*/
protected static final int TAIL_DROP_NEVER = 0;
/**
* Always drop tail bytes 0000FFFF, from all frame types
*/
protected static final int TAIL_DROP_ALWAYS = 1;
/**
* Only drop tail bytes 0000FFFF, from fin==true frames
*/
protected static final int TAIL_DROP_FIN_ONLY = 2;
/**
* Always set RSV flag, on all frame types
*/
protected static final int RSV_USE_ALWAYS = 0;
/**
* Only set RSV flag on first frame in multi-frame messages.
* <p>
* Note: this automatically means no-continuation frames have the RSV bit set
*/
protected static final int RSV_USE_ONLY_FIRST = 1;
/**
* Inflater / Decompressed Buffer Size
*/
protected static final int INFLATE_BUFFER_SIZE = 8 * 1024;
/**
* Deflater / Inflater: Maximum Input Buffer Size
*/
protected static final int INPUT_MAX_BUFFER_SIZE = 8 * 1024;
/**
* Inflater : Output Buffer Size
*/
private static final int DECOMPRESS_BUF_SIZE = 8 * 1024;
private final Queue<FrameEntry> entries = new ArrayDeque<>();
private final IteratingCallback flusher = new Flusher();
private DeflaterPool deflaterPool;
private InflaterPool inflaterPool;
private Deflater deflaterImpl;
private Inflater inflaterImpl;
protected ByteAccumulator accumulator;
protected AtomicInteger decompressCount = new AtomicInteger(0);
private int tailDrop = TAIL_DROP_NEVER;
private int rsvUse = RSV_USE_ALWAYS;
protected CompressExtension()
{
tailDrop = getTailDropMode();
rsvUse = getRsvUseMode();
}
public void setInflaterPool(InflaterPool inflaterPool)
{
this.inflaterPool = inflaterPool;
}
public void setDeflaterPool(DeflaterPool deflaterPool)
{
this.deflaterPool = deflaterPool;
}
public Deflater getDeflater()
{
if (deflaterImpl == null)
{
deflaterImpl = deflaterPool.acquire();
}
return deflaterImpl;
}
public Inflater getInflater()
{
if (inflaterImpl == null)
{
inflaterImpl = inflaterPool.acquire();
}
return inflaterImpl;
}
/**
* Indicates use of RSV1 flag for indicating deflation is in use.
*/
@Override
public boolean isRsv1User()
{
return true;
}
/**
* Return the mode of operation for dropping (or keeping) tail bytes in frames generated by compress (outgoing)
*
* @return either {@link #TAIL_DROP_ALWAYS}, {@link #TAIL_DROP_FIN_ONLY}, or {@link #TAIL_DROP_NEVER}
*/
abstract int getTailDropMode();
/**
* Return the mode of operation for RSV flag use in frames generate by compress (outgoing)
*
* @return either {@link #RSV_USE_ALWAYS} or {@link #RSV_USE_ONLY_FIRST}
*/
abstract int getRsvUseMode();
protected void forwardIncoming(Frame frame, ByteAccumulator accumulator)
{
DataFrame newFrame = new DataFrame(frame);
// Unset RSV1 since it's not compressed anymore.
newFrame.setRsv1(false);
ByteBuffer buffer = getBufferPool().acquire(accumulator.getLength(), false);
try
{
BufferUtil.flipToFill(buffer);
accumulator.transferTo(buffer);
newFrame.setPayload(buffer);
nextIncomingFrame(newFrame);
}
finally
{
getBufferPool().release(buffer);
}
}
protected ByteAccumulator newByteAccumulator()
{
int maxSize = Math.max(getPolicy().getMaxTextMessageSize(), getPolicy().getMaxBinaryMessageSize());
if (accumulator == null || accumulator.getMaxSize() != maxSize)
{
accumulator = new ByteAccumulator(maxSize);
}
return accumulator;
}
int copyChunk(Inflater inflater, ByteAccumulator accumulator, ByteBuffer buf) throws DataFormatException
{
int position = 0;
int capacity = buf.capacity();
while (position < capacity)
{
int read = inflater.inflate(buf.array(), position, capacity - position);
if (read <= 0)
{
accumulator.copyChunk(buf, position);
return read;
}
position += read;
}
accumulator.copyChunk(buf, position);
return position;
}
protected void decompress(ByteAccumulator accumulator, ByteBuffer buf) throws DataFormatException
{
if ((buf == null) || (!buf.hasRemaining()))
{
return;
}
Inflater inflater = getInflater();
while (buf.hasRemaining() && inflater.needsInput())
{
if (!supplyInput(inflater, buf))
{
if (LOG.isDebugEnabled())
LOG.debug("Needed input, but no buffer could supply input");
return;
}
while (true)
{
ByteBuffer output = accumulator.newByteBuffer(DECOMPRESS_BUF_SIZE);
int read = copyChunk(inflater, accumulator, output);
if (read <= 0)
{
break;
}
}
}
if (LOG.isDebugEnabled())
LOG.debug("Decompress: exiting {}", toDetail(inflater));
}
@Override
public void outgoingFrame(Frame frame, WriteCallback callback, BatchMode batchMode)
{
// We use a queue and an IteratingCallback to handle concurrency.
// We must compress and write atomically, otherwise the compression
// context on the other end gets confused.
if (flusher.isFailed())
{
notifyCallbackFailure(callback, new ZipException());
return;
}
FrameEntry entry = new FrameEntry(frame, callback, batchMode);
if (LOG.isDebugEnabled())
LOG.debug("Queuing {}", entry);
offerEntry(entry);
flusher.iterate();
}
private void offerEntry(FrameEntry entry)
{
synchronized (this)
{
entries.offer(entry);
}
}
private FrameEntry pollEntry()
{
synchronized (this)
{
return entries.poll();
}
}
protected void notifyCallbackSuccess(WriteCallback callback)
{
try
{
if (callback != null)
callback.writeSuccess();
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while notifying success of callback " + callback, x);
}
}
protected void notifyCallbackFailure(WriteCallback callback, Throwable failure)
{
try
{
if (callback != null)
callback.writeFailed(failure);
}
catch (Throwable x)
{
if (LOG.isDebugEnabled())
LOG.debug("Exception while notifying failure of callback " + callback, x);
}
}
private static boolean supplyInput(Inflater inflater, ByteBuffer buf)
{
if (buf == null || buf.remaining() <= 0)
{
if (LOG.isDebugEnabled())
LOG.debug("No data left left to supply to Inflater");
return false;
}
byte[] input;
int inputOffset;
int len;
if (buf.hasArray())
{
// no need to create a new byte buffer, just return this one.
len = buf.remaining();
input = buf.array();
inputOffset = buf.position() + buf.arrayOffset();
buf.position(buf.position() + len);
}
else
{
// Only create an return byte buffer that is reasonable in size
len = Math.min(INPUT_MAX_BUFFER_SIZE, buf.remaining());
input = new byte[len];
inputOffset = 0;
buf.get(input, 0, len);
}
inflater.setInput(input, inputOffset, len);
if (LOG.isDebugEnabled())
LOG.debug("Supplied {} input bytes: {}", input.length, toDetail(inflater));
return true;
}
private static boolean supplyInput(Deflater deflater, ByteBuffer buf)
{
if (buf == null || buf.remaining() <= 0)
{
if (LOG.isDebugEnabled())
LOG.debug("No data left left to supply to Deflater");
return false;
}
byte[] input;
int inputOffset;
int len;
if (buf.hasArray())
{
// no need to create a new byte buffer, just return this one.
len = buf.remaining();
input = buf.array();
inputOffset = buf.position() + buf.arrayOffset();
buf.position(buf.position() + len);
}
else
{
// Only create an return byte buffer that is reasonable in size
len = Math.min(INPUT_MAX_BUFFER_SIZE, buf.remaining());
input = new byte[len];
inputOffset = 0;
buf.get(input, 0, len);
}
deflater.setInput(input, inputOffset, len);
if (LOG.isDebugEnabled())
LOG.debug("Supplied {} input bytes: {}", input.length, toDetail(deflater));
return true;
}
private static String toDetail(Inflater inflater)
{
return String.format("Inflater[finished=%b,read=%d,written=%d,remaining=%d,in=%d,out=%d]", inflater.finished(), inflater.getBytesRead(),
inflater.getBytesWritten(), inflater.getRemaining(), inflater.getTotalIn(), inflater.getTotalOut());
}
private static String toDetail(Deflater deflater)
{
return String.format("Deflater[finished=%b,read=%d,written=%d,in=%d,out=%d]", deflater.finished(), deflater.getBytesRead(), deflater.getBytesWritten(),
deflater.getTotalIn(), deflater.getTotalOut());
}
public static boolean endsWithTail(ByteBuffer buf)
{
if ((buf == null) || (buf.remaining() < TAIL_BYTES.length))
{
return false;
}
int limit = buf.limit();
for (int i = TAIL_BYTES.length; i > 0; i--)
{
if (buf.get(limit - i) != TAIL_BYTES[TAIL_BYTES.length - i])
{
return false;
}
}
return true;
}
@Override
protected void doStop() throws Exception
{
if (deflaterImpl != null)
{
deflaterPool.release(deflaterImpl);
deflaterImpl = null;
}
if (inflaterImpl != null)
{
inflaterPool.release(inflaterImpl);
inflaterImpl = null;
}
super.doStop();
}
@Override
public String toString()
{
return getClass().getSimpleName();
}
private static class FrameEntry
{
private final Frame frame;
private final WriteCallback callback;
private final BatchMode batchMode;
private FrameEntry(Frame frame, WriteCallback callback, BatchMode batchMode)
{
this.frame = frame;
this.callback = callback;
this.batchMode = batchMode;
}
@Override
public String toString()
{
return frame.toString();
}
}
private class Flusher extends IteratingCallback implements WriteCallback
{
private FrameEntry current;
private boolean finished = true;
@Override
public void failed(Throwable x)
{
notifyCallbackFailure(current.callback, x);
// If something went wrong, very likely the compression context
// will be invalid, so we need to fail this IteratingCallback.
LOG.warn(x);
super.failed(x);
}
@Override
protected Action process() throws Exception
{
if (finished)
{
current = pollEntry();
if (LOG.isDebugEnabled())
LOG.debug("Processing {}", current);
if (current == null)
return Action.IDLE;
deflate(current);
}
else
{
compress(current, false);
}
return Action.SCHEDULED;
}
private void deflate(FrameEntry entry)
{
Frame frame = entry.frame;
BatchMode batchMode = entry.batchMode;
if (OpCode.isControlFrame(frame.getOpCode()))
{
// Do not deflate control frames
nextOutgoingFrame(frame, this, batchMode);
return;
}
compress(entry, true);
}
private void compress(FrameEntry entry, boolean first)
{
// Get a chunk of the payload to avoid to blow
// the heap if the payload is a huge mapped file.
Frame frame = entry.frame;
ByteBuffer data = frame.getPayload();
if (data == null)
data = BufferUtil.EMPTY_BUFFER;
int remaining = data.remaining();
int outputLength = Math.max(256, data.remaining());
if (LOG.isDebugEnabled())
LOG.debug("Compressing {}: {} bytes in {} bytes chunk", entry, remaining, outputLength);
boolean needsCompress = true;
Deflater deflater = getDeflater();
if (deflater.needsInput() && !supplyInput(deflater, data))
{
// no input supplied
needsCompress = false;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] output = new byte[outputLength];
boolean fin = frame.isFin();
// Compress the data
while (needsCompress)
{
int compressed = deflater.deflate(output, 0, outputLength, Deflater.SYNC_FLUSH);
// Append the output for the eventual frame.
if (LOG.isDebugEnabled())
LOG.debug("Wrote {} bytes to output buffer", compressed);
out.write(output, 0, compressed);
if (compressed < outputLength)
{
needsCompress = false;
}
}
ByteBuffer payload = ByteBuffer.wrap(out.toByteArray());
if (payload.remaining() > 0)
{
// Handle tail bytes generated by SYNC_FLUSH.
if (LOG.isDebugEnabled())
LOG.debug("compressed[] bytes = {}", BufferUtil.toDetailString(payload));
if (tailDrop == TAIL_DROP_ALWAYS)
{
if (endsWithTail(payload))
{
payload.limit(payload.limit() - TAIL_BYTES.length);
}
if (LOG.isDebugEnabled())
LOG.debug("payload (TAIL_DROP_ALWAYS) = {}", BufferUtil.toDetailString(payload));
}
else if (tailDrop == TAIL_DROP_FIN_ONLY)
{
if (frame.isFin() && endsWithTail(payload))
{
payload.limit(payload.limit() - TAIL_BYTES.length);
}
if (LOG.isDebugEnabled())
LOG.debug("payload (TAIL_DROP_FIN_ONLY) = {}", BufferUtil.toDetailString(payload));
}
}
else if (fin)
{
// Special case: 7.2.3.6. Generating an Empty Fragment Manually
// https://tools.ietf.org/html/rfc7692#section-7.2.3.6
payload = ByteBuffer.wrap(new byte[]{0x00});
}
if (LOG.isDebugEnabled())
LOG.debug("Compressed {}: input:{} -> payload:{}", entry, outputLength, payload.remaining());
boolean continuation = frame.getType().isContinuation() || !first;
DataFrame chunk = new DataFrame(frame, continuation);
if (rsvUse == RSV_USE_ONLY_FIRST)
{
chunk.setRsv1(!continuation);
}
else
{
// always set
chunk.setRsv1(true);
}
chunk.setPayload(payload);
chunk.setFin(fin);
nextOutgoingFrame(chunk, this, entry.batchMode);
}
@Override
protected void onCompleteSuccess()
{
// This IteratingCallback never completes.
}
@Override
protected void onCompleteFailure(Throwable x)
{
// Fail all the frames in the queue.
FrameEntry entry;
while ((entry = pollEntry()) != null)
{
notifyCallbackFailure(entry.callback, x);
}
}
@Override
public void writeSuccess()
{
if (finished)
notifyCallbackSuccess(current.callback);
succeeded();
}
@Override
public void writeFailed(Throwable x)
{
failed(x);
}
}
}