Debian Codegraph @

lib/compresshttp/compress.go

raw symbols SCIP
1 //
2 // Copyright (c) SAS Institute Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 package compresshttp
18
19 import (
20 "compress/gzip"
21 "errors"
22 "io"
23 "io/ioutil"
24 "net/http"
25 "strings"
26 "sync/atomic"
27
28 "github.com/golang/snappy"
29 )
30
31 const (
32 acceptEncoding = "Accept-Encoding"
33 contentEncoding = "Content-Encoding"
34 contentLength = "Content-Length"
35 EncodingIdentity = "identity"
36 EncodingGzip = "gzip"
37 EncodingSnappy = "x-snappy-framed"
38
39 AcceptedEncodings = EncodingSnappy + ", " + EncodingGzip
40 )
41
42 // higher is better
43 var prefs = map[string]int{
44 EncodingGzip: 1,
45 EncodingSnappy: 2,
46 }
47
48 var ErrUnacceptableEncoding = errors.New("unknown Content-Encoding")
49
50 func selectEncoding(acceptEncoding string) string {
51 var pref int
52 var best string
53 for _, encoding := range strings.Split(acceptEncoding, ",") {
54 encoding = strings.TrimSpace(strings.Split(encoding, ";")[0])
55 if p2 := prefs[encoding]; p2 > pref {
56 pref = p2
57 best = encoding
58 }
59 }
60 return best
61 }
62
63 func setupCompression(encoding string, w io.Writer) (io.WriteCloser, error) {
64 switch encoding {
65 case EncodingIdentity, "":
66 return nopCloseWriter{Writer: w}, nil
67 case EncodingGzip:
68 return gzip.NewWriterLevel(w, gzip.BestSpeed)
69 case EncodingSnappy:
70 return snappy.NewBufferedWriter(w), nil
71 default:
72 return nil, ErrUnacceptableEncoding
73 }
74 }
75
76 func compress(encoding string, r io.Reader, w io.Writer) (err error) {
77 compr, err := setupCompression(encoding, w)
78 if err == nil {
79 _, err = io.Copy(compr, r)
80 }
81 if err == nil {
82 err = compr.Close()
83 }
84 return
85 }
86
87 func decompress(encoding string, r io.Reader) (io.Reader, error) {
88 switch encoding {
89 case EncodingIdentity, "":
90 return ioutil.NopCloser(r), nil
91 case EncodingGzip:
92 return gzip.NewReader(r)
93 case EncodingSnappy:
94 return snappy.NewReader(r), nil
95 default:
96 return nil, ErrUnacceptableEncoding
97 }
98 }
99
100 func CompressRequest(request *http.Request, acceptEncoding string) error {
101 encoding := selectEncoding(acceptEncoding)
102 if encoding == "" {
103 return nil
104 }
105 plain := &readBlocker{Reader: request.Body}
106 pr, pw := io.Pipe()
107 go func() {
108 err := compress(encoding, plain, pw)
109 _ = plain.Close()
110 _ = pw.CloseWithError(err)
111 }()
112 // Ensure reads inside the goroutine fail after the request terminates.
113 // Otherwise there could be reads happening in parallel from multiple,
114 // different requests, if those requests are reading from the same
115 // underlying file. That could cause file pointers to move unexpectedly,
116 // and it's easier to prevent here than to make sure every use case is
117 // thread-safe.
118 request.Body = alsoClose{ReadCloser: pr, also: plain}
119 request.ContentLength = -1
120 request.Header.Set(contentEncoding, encoding)
121 return nil
122 }
123
124 // Wrap a reader and block all reads once Close() is called
125 type readBlocker struct {
126 io.Reader
127 closed uint32
128 }
129
130 func (r *readBlocker) Read(d []byte) (int, error) {
131 if atomic.LoadUint32(&r.closed) != 0 {
132 return 0, errors.New("stream is closed")
133 }
134 return r.Reader.Read(d)
135 }
136
137 func (r *readBlocker) Close() error {
138 if c, ok := r.Reader.(io.Closer); ok {
139 if err := c.Close(); err != nil {
140 return err
141 }
142 }
143 atomic.StoreUint32(&r.closed, 1)
144 return nil
145 }
146
147 type alsoClose struct {
148 io.ReadCloser
149 also io.Closer
150 }
151
152 func (a alsoClose) Close() error {
153 a.also.Close()
154 return a.ReadCloser.Close()
155 }
156
157 func DecompressRequest(request *http.Request) error {
158 r, err := decompress(request.Header.Get(contentEncoding), request.Body)
159 if err == nil {
160 request.Body = ioutil.NopCloser(r)
161 request.ContentLength = -1
162 }
163 return err
164 }
165
166 func CompressResponse(r io.Reader, acceptEncoding string, writer http.ResponseWriter, status int) error {
167 encoding := selectEncoding(acceptEncoding)
168 if encoding != "" {
169 writer.Header().Set(contentEncoding, encoding)
170 writer.Header().Del(contentLength)
171 } else {
172 writer.Header().Del(contentEncoding)
173 }
174 writer.WriteHeader(status)
175 return compress(encoding, r, writer)
176 }
177
178 func DecompressResponse(response *http.Response) error {
179 r, err := decompress(response.Header.Get(contentEncoding), response.Body)
180 if err == nil {
181 response.Body = readAndClose{r: r, c: response.Body}
182 response.ContentLength = -1
183 }
184 return err
185 }
186
187 type readAndClose struct {
188 r io.Reader
189 c io.Closer
190 }
191
192 func (rc readAndClose) Read(d []byte) (int, error) {
193 return rc.r.Read(d)
194 }
195
196 func (rc readAndClose) Close() error {
197 return rc.c.Close()
198 }
199
200 type nopCloseWriter struct {
201 io.Writer
202 }
203
204 func (nopCloseWriter) Close() error {
205 return nil
206 }