Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 05a16a46fc5abc69d38b700741b35dcfdc66056b (plain) (blame)
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
//
//  ========================================================================
//  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  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.server.handler.gzip;

import static org.eclipse.jetty.http.GzipHttpContent.ETAG_GZIP_QUOTE;

import java.io.File;
import java.io.IOException;
import java.util.Set;
import java.util.zip.Deflater;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.http.GzipHttpContent;
import org.eclipse.jetty.http.HttpField;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpVersion;
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.http.pathmap.PathSpecSet;
import org.eclipse.jetty.server.HttpOutput;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.HandlerWrapper;
import org.eclipse.jetty.util.IncludeExclude;
import org.eclipse.jetty.util.RegexSet;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;


/**
 * A Handler that can dynamically GZIP compress responses.   Unlike 
 * previous and 3rd party GzipFilters, this mechanism works with asynchronously
 * generated responses and does not need to wrap the response or it's output
 * stream.  Instead it uses the efficient {@link org.eclipse.jetty.server.HttpOutput.Interceptor} mechanism.
 * <p>
 * The handler can be applied to the entire server (a gzip.mod is included in
 * the distribution) or it may be applied to individual contexts.
 * </p>
 */
public class GzipHandler extends HandlerWrapper implements GzipFactory
{
    private static final Logger LOG = Log.getLogger(GzipHandler.class);

    public final static String GZIP = "gzip";
    public final static String DEFLATE = "deflate";
    public final static int DEFAULT_MIN_GZIP_SIZE=16;
    private int _minGzipSize=DEFAULT_MIN_GZIP_SIZE;
    private int _compressionLevel=Deflater.DEFAULT_COMPRESSION;
    private boolean _checkGzExists = true;
    
    // non-static, as other GzipHandler instances may have different configurations
    private final ThreadLocal<Deflater> _deflater = new ThreadLocal<Deflater>();

    private final IncludeExclude<String> _agentPatterns=new IncludeExclude<>(RegexSet.class);
    private final IncludeExclude<String> _methods = new IncludeExclude<>();
    private final IncludeExclude<String> _paths = new IncludeExclude<>(PathSpecSet.class);
    private final IncludeExclude<String> _mimeTypes = new IncludeExclude<>();
    
    private HttpField _vary;


    /* ------------------------------------------------------------ */
    /**
     * Instantiates a new gzip handler.
     * The excluded Mime Types are initialized to common known 
     * images, audio, video and other already compressed types.
     * The included methods is initialized to GET.
     * The excluded agent patterns are set to exclude MSIE 6.0
     */
    public GzipHandler()
    {
        _methods.include(HttpMethod.GET.asString());
        for (String type:MimeTypes.getKnownMimeTypes())
        {
            if ("image/svg+xml".equals(type))
                _paths.exclude("*.svgz");
            else if (type.startsWith("image/")||
                type.startsWith("audio/")||
                type.startsWith("video/"))
                _mimeTypes.exclude(type);
        }
        _mimeTypes.exclude("application/compress");
        _mimeTypes.exclude("application/zip");
        _mimeTypes.exclude("application/gzip");
        _mimeTypes.exclude("application/bzip2");
        _mimeTypes.exclude("application/x-rar-compressed");
        LOG.debug("{} mime types {}",this,_mimeTypes);
        
        _agentPatterns.exclude(".*MSIE 6.0.*");
    }

    /* ------------------------------------------------------------ */
    /**
     * @param patterns Regular expressions matching user agents to exclude
     */
    public void addExcludedAgentPatterns(String... patterns)
    {
        _agentPatterns.exclude(patterns);
    }

    /* ------------------------------------------------------------ */
    /**
     * @param methods The methods to exclude in compression
     */
    public void addExcludedMethods(String... methods)
    {
        for (String m : methods)
            _methods.exclude(m);
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the mime types.
     * @param types The mime types to exclude (without charset or other parameters).
     * For backward compatibility the mimetypes may be comma separated strings, but this
     * will not be supported in future versions.
     */
    public void addExcludedMimeTypes(String... types)
    {
        for (String t : types)
            _mimeTypes.exclude(StringUtil.csvSplit(t));
    }

    /* ------------------------------------------------------------ */
    /**
     * @param pathspecs Path specs (as per servlet spec) to exclude. If a 
     * ServletContext is available, the paths are relative to the context path,
     * otherwise they are absolute.
     * For backward compatibility the pathspecs may be comma separated strings, but this
     * will not be supported in future versions.
     */
    public void addExcludedPaths(String... pathspecs)
    {
        for (String p : pathspecs)
            _paths.exclude(StringUtil.csvSplit(p));
    }

    /* ------------------------------------------------------------ */
    /**
     * @param patterns Regular expressions matching user agents to exclude
     */
    public void addIncludedAgentPatterns(String... patterns)
    {
        _agentPatterns.include(patterns);
    }
    
    /* ------------------------------------------------------------ */
    /**
     * @param methods The methods to include in compression
     */
    public void addIncludedMethods(String... methods)
    {
        for (String m : methods)
            _methods.include(m);
    }

    /* ------------------------------------------------------------ */
    /**
     * Add included mime types. Inclusion takes precedence over
     * exclusion.
     * @param types The mime types to include (without charset or other parameters)
     * For backward compatibility the mimetypes may be comma separated strings, but this
     * will not be supported in future versions.
     */
    public void addIncludedMimeTypes(String... types)
    {
        for (String t : types)
            _mimeTypes.include(StringUtil.csvSplit(t));
    }

    /* ------------------------------------------------------------ */
    /**
     * Add path specs to include. Inclusion takes precedence over exclusion.
     * @param pathspecs Path specs (as per servlet spec) to include. If a 
     * ServletContext is available, the paths are relative to the context path,
     * otherwise they are absolute
     * For backward compatibility the pathspecs may be comma separated strings, but this
     * will not be supported in future versions.
     */
    public void addIncludedPaths(String... pathspecs)
    {
        for (String p : pathspecs)
            _paths.include(StringUtil.csvSplit(p));
    }
    
    /* ------------------------------------------------------------ */
    @Override
    protected void doStart() throws Exception
    {
        _vary=(_agentPatterns.size()>0)?GzipHttpOutputInterceptor.VARY_ACCEPT_ENCODING_USER_AGENT:GzipHttpOutputInterceptor.VARY_ACCEPT_ENCODING;
        super.doStart();
    }

    /* ------------------------------------------------------------ */
    public boolean getCheckGzExists()
    {
        return _checkGzExists;
    }

    /* ------------------------------------------------------------ */
    public int getCompressionLevel()
    {
        return _compressionLevel;
    }
    
    /* ------------------------------------------------------------ */
    @Override
    public Deflater getDeflater(Request request, long content_length)
    {
        String ua = request.getHttpFields().get(HttpHeader.USER_AGENT);
        if (ua!=null && !isAgentGzipable(ua))
        {
            LOG.debug("{} excluded user agent {}",this,request);
            return null;
        }
        
        if (content_length>=0 && content_length<_minGzipSize)
        {
            LOG.debug("{} excluded minGzipSize {}",this,request);
            return null;
        }

        // If not HTTP/2, then we must check the accept encoding header
        if (request.getHttpVersion()!=HttpVersion.HTTP_2)
        {
            HttpField accept = request.getHttpFields().getField(HttpHeader.ACCEPT_ENCODING);

            if (accept==null)
            {
                LOG.debug("{} excluded !accept {}",this,request);
                return null;
            }
            boolean gzip = accept.contains("gzip");

            if (!gzip)
            {
                LOG.debug("{} excluded not gzip accept {}",this,request);
                return null;
            }
        }
        
        Deflater df = _deflater.get();
        if (df==null)
            df=new Deflater(_compressionLevel,true);        
        else
            _deflater.set(null);
        
        return df;
    }
    
    /* ------------------------------------------------------------ */
    public String[] getExcludedAgentPatterns()
    {
        Set<String> excluded=_agentPatterns.getExcluded();
        return excluded.toArray(new String[excluded.size()]);
    }

    /* ------------------------------------------------------------ */
    public String[] getExcludedMethods()
    {
        Set<String> excluded=_methods.getExcluded();
        return excluded.toArray(new String[excluded.size()]);
    }

    /* ------------------------------------------------------------ */
    public String[] getExcludedMimeTypes()
    {
        Set<String> excluded=_mimeTypes.getExcluded();
        return excluded.toArray(new String[excluded.size()]);
    }

    /* ------------------------------------------------------------ */
    public String[] getExcludedPaths()
    {
        Set<String> excluded=_paths.getExcluded();
        return excluded.toArray(new String[excluded.size()]);
    }

    /* ------------------------------------------------------------ */
    public String[] getIncludedAgentPatterns()
    {
        Set<String> includes=_agentPatterns.getIncluded();
        return includes.toArray(new String[includes.size()]);
    }
    
    /* ------------------------------------------------------------ */
    public String[] getIncludedMethods()
    {
        Set<String> includes=_methods.getIncluded();
        return includes.toArray(new String[includes.size()]);
    }

    /* ------------------------------------------------------------ */
    public String[] getIncludedMimeTypes()
    {
        Set<String> includes=_mimeTypes.getIncluded();
        return includes.toArray(new String[includes.size()]);
    }

    /* ------------------------------------------------------------ */
    public String[] getIncludedPaths()
    {
        Set<String> includes=_paths.getIncluded();
        return includes.toArray(new String[includes.size()]);
    }

    /* ------------------------------------------------------------ */
    @Deprecated
    public String[] getMethods()
    {
        return getIncludedMethods();
    }

    /* ------------------------------------------------------------ */
    /**
     * Get the minimum reponse size.
     *
     * @return minimum reponse size
     */
    public int getMinGzipSize()
    {
        return _minGzipSize;
    }

    /* ------------------------------------------------------------ */
    /**
     * @see org.eclipse.jetty.server.handler.HandlerWrapper#handle(java.lang.String, org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
    {
        ServletContext context = baseRequest.getServletContext();
        String path = context==null?baseRequest.getRequestURI():URIUtil.addPaths(baseRequest.getServletPath(),baseRequest.getPathInfo());
        LOG.debug("{} handle {} in {}",this,baseRequest,context);
        
        HttpOutput out = baseRequest.getResponse().getHttpOutput();   
        // Are we already being gzipped?
        HttpOutput.Interceptor interceptor = out.getInterceptor();
        while (interceptor!=null)
        {
            if (interceptor instanceof GzipHttpOutputInterceptor)
            {
                LOG.debug("{} already intercepting {}",this,request);
                _handler.handle(target,baseRequest, request, response);
                return;
            }
            interceptor=interceptor.getNextInterceptor();
        }
        
        // If not a supported method - no Vary because no matter what client, this URI is always excluded
        if (!_methods.matches(baseRequest.getMethod()))
        {
            LOG.debug("{} excluded by method {}",this,request);
            _handler.handle(target,baseRequest, request, response);
            return;
        }
        
        // If not a supported URI- no Vary because no matter what client, this URI is always excluded
        // Use pathInfo because this is be
        if (!isPathGzipable(path))
        {
            LOG.debug("{} excluded by path {}",this,request);
            _handler.handle(target,baseRequest, request, response);
            return;
        }

        // Exclude non compressible mime-types known from URI extension. - no Vary because no matter what client, this URI is always excluded
        String mimeType = context==null?null:context.getMimeType(path);
        if (mimeType!=null)
        {
            mimeType = MimeTypes.getContentTypeWithoutCharset(mimeType);
            if (!isMimeTypeGzipable(mimeType))
            {
                LOG.debug("{} excluded by path suffix mime type {}",this,request);
                // handle normally without setting vary header
                _handler.handle(target,baseRequest, request, response);
                return;
            }
        }
        
        if (_checkGzExists && context!=null)
        {
            String realpath=request.getServletContext().getRealPath(path);
            if (realpath!=null)
            {
                File gz=new File(realpath+".gz");
                if (gz.exists())
                {
                    LOG.debug("{} gzip exists {}",this,request);
                    // allow default servlet to handle
                    _handler.handle(target,baseRequest, request, response);
                    return;
                }
            }
        }
        
        // Special handling for etags
        String etag = baseRequest.getHttpFields().get(HttpHeader.IF_NONE_MATCH); 
        if (etag!=null)
        {
            int i=etag.indexOf(ETAG_GZIP_QUOTE);
            if (i>0)
            {
                while (i>=0)
                {
                    etag=etag.substring(0,i)+etag.substring(i+GzipHttpContent.ETAG_GZIP.length());
                    i=etag.indexOf(ETAG_GZIP_QUOTE,i);
                }
                baseRequest.getHttpFields().put(new HttpField(HttpHeader.IF_NONE_MATCH,etag));
            }
        }

        // install interceptor and handle
        out.setInterceptor(new GzipHttpOutputInterceptor(this,_vary,baseRequest.getHttpChannel(),out.getInterceptor()));
        if (_handler!=null)
            _handler.handle(target,baseRequest, request, response);
    }

    /* ------------------------------------------------------------ */
    /**
     * Checks to see if the userAgent is excluded
     *
     * @param ua the user agent
     * @return boolean true if excluded
     */
    protected boolean isAgentGzipable(String ua)
    {
        if (ua == null)
            return false;
        
        return _agentPatterns.matches(ua);
    }

    /* ------------------------------------------------------------ */
    @Override
    public boolean isMimeTypeGzipable(String mimetype)
    {
        return _mimeTypes.matches(mimetype);
    }

    /* ------------------------------------------------------------ */
    /**
     * Checks to see if the path is included or not excluded 
     *
     * @param requestURI
     *            the request uri
     * @return boolean true if gzipable
     */
    protected boolean isPathGzipable(String requestURI)
    {
        if (requestURI == null)
            return true;
        
        return _paths.matches(requestURI);
    }

    /* ------------------------------------------------------------ */
    @Override
    public void recycle(Deflater deflater)
    {
        deflater.reset();
        if (_deflater.get()==null)
            _deflater.set(deflater);
    }

    /* ------------------------------------------------------------ */
    /**
     * @param checkGzExists If true, check if a static gz file exists for
     * the resource that the DefaultServlet may serve as precompressed.
     */
    public void setCheckGzExists(boolean checkGzExists)
    {
        _checkGzExists = checkGzExists;
    }
    
    /* ------------------------------------------------------------ */
    /**
     * @param compressionLevel  The compression level to use to initialize {@link Deflater#setLevel(int)}
     */
    public void setCompressionLevel(int compressionLevel)
    {
        _compressionLevel = compressionLevel;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param patterns Regular expressions matching user agents to exclude
     */
    public void setExcludedAgentPatterns(String... patterns)
    {
        _agentPatterns.getExcluded().clear();
        addExcludedAgentPatterns(patterns);
    }

    /* ------------------------------------------------------------ */
    /**
     * @param method to exclude
     */
    public void setExcludedMethods(String... method)
    {
        _methods.getExcluded().clear();
        _methods.exclude(method);
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the mime types.
     * @param types The mime types to exclude (without charset or other parameters)
     */
    public void setExcludedMimeTypes(String... types)
    {
        _mimeTypes.getExcluded().clear();
        _mimeTypes.exclude(types);
    }

    /* ------------------------------------------------------------ */
    /**
     * @param pathspecs Path specs (as per servlet spec) to exclude. If a 
     * ServletContext is available, the paths are relative to the context path,
     * otherwise they are absolute.
     */
    public void setExcludedPaths(String... pathspecs)
    {
        _paths.getExcluded().clear();
        _paths.exclude(pathspecs);
    }

    /* ------------------------------------------------------------ */
    /**
     * @param patterns Regular expressions matching user agents to include
     */
    public void setIncludedAgentPatterns(String... patterns)
    {
        _agentPatterns.getIncluded().clear();
        addIncludedAgentPatterns(patterns);
    }
    
    /* ------------------------------------------------------------ */
    /**
     * @param methods The methods to include in compression
     */
    public void setIncludedMethods(String... methods)
    {
        _methods.getIncluded().clear();
        _methods.include(methods);
    }
    
    /* ------------------------------------------------------------ */
    /**
     * Set included mime types. Inclusion takes precedence over
     * exclusion.
     * @param types The mime types to include (without charset or other parameters)
     */
    public void setIncludedMimeTypes(String... types)
    {
        _mimeTypes.getIncluded().clear();
        _mimeTypes.include(types);
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the path specs to include. Inclusion takes precedence over exclusion.
     * @param pathspecs Path specs (as per servlet spec) to include. If a 
     * ServletContext is available, the paths are relative to the context path,
     * otherwise they are absolute
     */
    public void setIncludedPaths(String... pathspecs)
    {
        _paths.getIncluded().clear();
        _paths.include(pathspecs);
    }

    /* ------------------------------------------------------------ */
    /**
     * Set the minimum response size to trigger dynamic compresssion
     *
     * @param minGzipSize minimum response size in bytes
     */
    public void setMinGzipSize(int minGzipSize)
    {
        _minGzipSize = minGzipSize;
    }
}

Back to the top