Debian Codegraph @

modules/caddyhttp/reverseproxy/fastcgi/client.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Forked Jan. 2015 from http://bitbucket.org/PinIdea/fcgi_client
16 // (which is forked from https://code.google.com/p/go-fastcgi-client/).
17 // This fork contains several fixes and improvements by Matt Holt and
18 // other contributors to the Caddy project.
19
20 // Copyright 2012 Junqing Tan <[email protected]> and The Go Authors
21 // Use of this source code is governed by a BSD-style
22 // Part of source code is from Go fcgi package
23
24 package fastcgi
25
26 import (
27 "bufio"
28 "bytes"
29 "io"
30 "mime/multipart"
31 "net"
32 "net/http"
33 "net/http/httputil"
34 "net/textproto"
35 "net/url"
36 "os"
37 "path/filepath"
38 "strconv"
39 "strings"
40 "time"
41
42 "go.uber.org/zap"
43 "go.uber.org/zap/zapcore"
44
45 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
46 )
47
48 // FCGIListenSockFileno describes listen socket file number.
49 const FCGIListenSockFileno uint8 = 0
50
51 // FCGIHeaderLen describes header length.
52 const FCGIHeaderLen uint8 = 8
53
54 // Version1 describes the version.
55 const Version1 uint8 = 1
56
57 // FCGINullRequestID describes the null request ID.
58 const FCGINullRequestID uint8 = 0
59
60 // FCGIKeepConn describes keep connection mode.
61 const FCGIKeepConn uint8 = 1
62
63 const (
64 // BeginRequest is the begin request flag.
65 BeginRequest uint8 = iota + 1
66 // AbortRequest is the abort request flag.
67 AbortRequest
68 // EndRequest is the end request flag.
69 EndRequest
70 // Params is the parameters flag.
71 Params
72 // Stdin is the standard input flag.
73 Stdin
74 // Stdout is the standard output flag.
75 Stdout
76 // Stderr is the standard error flag.
77 Stderr
78 // Data is the data flag.
79 Data
80 // GetValues is the get values flag.
81 GetValues
82 // GetValuesResult is the get values result flag.
83 GetValuesResult
84 // UnknownType is the unknown type flag.
85 UnknownType
86 // MaxType is the maximum type flag.
87 MaxType = UnknownType
88 )
89
90 const (
91 // Responder is the responder flag.
92 Responder uint8 = iota + 1
93 // Authorizer is the authorizer flag.
94 Authorizer
95 // Filter is the filter flag.
96 Filter
97 )
98
99 const (
100 // RequestComplete is the completed request flag.
101 RequestComplete uint8 = iota
102 // CantMultiplexConns is the multiplexed connections flag.
103 CantMultiplexConns
104 // Overloaded is the overloaded flag.
105 Overloaded
106 // UnknownRole is the unknown role flag.
107 UnknownRole
108 )
109
110 const (
111 // MaxConns is the maximum connections flag.
112 MaxConns string = "MAX_CONNS"
113 // MaxRequests is the maximum requests flag.
114 MaxRequests string = "MAX_REQS"
115 // MultiplexConns is the multiplex connections flag.
116 MultiplexConns string = "MPXS_CONNS"
117 )
118
119 const (
120 maxWrite = 65500 // 65530 may work, but for compatibility
121 maxPad = 255
122 )
123
124 // for padding so we don't have to allocate all the time
125 // not synchronized because we don't care what the contents are
126 var pad [maxPad]byte
127
128 // client implements a FastCGI client, which is a standard for
129 // interfacing external applications with Web servers.
130 type client struct {
131 rwc net.Conn
132 // keepAlive bool // TODO: implement
133 reqID uint16
134 stderr bool
135 logger *zap.Logger
136 }
137
138 // Do makes the request and returns an io.Reader that translates the data read
139 // from the FastCGI responder out of FastCGI packets before returning it.
140 func (c *client) Do(p map[string]string, req io.Reader) (r io.Reader, err error) {
141 // check for CONTENT_LENGTH, since the lack of it or wrong value will cause the backend to hang
142 if clStr, ok := p["CONTENT_LENGTH"]; !ok {
143 return nil, caddyhttp.Error(http.StatusLengthRequired, nil)
144 } else if _, err := strconv.ParseUint(clStr, 10, 64); err != nil {
145 // stdlib won't return a negative Content-Length, but we check just in case,
146 // the most likely cause is from a missing content length, which is -1
147 return nil, caddyhttp.Error(http.StatusLengthRequired, err)
148 }
149
150 writer := &streamWriter{c: c}
151 writer.buf = bufPool.Get().(*bytes.Buffer)
152 writer.buf.Reset()
153 defer bufPool.Put(writer.buf)
154
155 err = writer.writeBeginRequest(uint16(Responder), 0)
156 if err != nil {
157 return r, err
158 }
159
160 writer.recType = Params
161 err = writer.writePairs(p)
162 if err != nil {
163 return r, err
164 }
165
166 writer.recType = Stdin
167 if req != nil {
168 _, err = io.Copy(writer, req)
169 if err != nil {
170 return nil, err
171 }
172 }
173 err = writer.FlushStream()
174 if err != nil {
175 return nil, err
176 }
177
178 r = &streamReader{c: c}
179 return r, err
180 }
181
182 // clientCloser is an io.ReadCloser. It wraps an io.Reader with a Closer
183 // that closes the client connection.
184 type clientCloser struct {
185 rwc net.Conn
186 r *streamReader
187 io.Reader
188
189 status int
190 logger *zap.Logger
191 }
192
193 func (f clientCloser) Close() error {
194 stderr := f.r.stderr.Bytes()
195 if len(stderr) == 0 {
196 return f.rwc.Close()
197 }
198
199 logLevel := zapcore.WarnLevel
200 if f.status >= 400 {
201 logLevel = zapcore.ErrorLevel
202 }
203
204 if c := f.logger.Check(logLevel, "stderr"); c != nil {
205 c.Write(zap.ByteString("body", stderr))
206 }
207
208 return f.rwc.Close()
209 }
210
211 // Request returns an HTTP response with header and body
212 // from the FastCGI responder.
213 func (c *client) Request(p map[string]string, req io.Reader) (resp *http.Response, err error) {
214 r, err := c.Do(p, req)
215 if err != nil {
216 return resp, err
217 }
218
219 rb := bufio.NewReader(r)
220 tp := textproto.NewReader(rb)
221 resp = new(http.Response)
222
223 // Parse the response headers.
224 mimeHeader, err := tp.ReadMIMEHeader()
225 if err != nil && err != io.EOF {
226 return resp, err
227 }
228 resp.Header = http.Header(mimeHeader)
229
230 if resp.Header.Get("Status") != "" {
231 statusNumber, statusInfo, statusIsCut := strings.Cut(resp.Header.Get("Status"), " ")
232 resp.StatusCode, err = strconv.Atoi(statusNumber)
233 if err != nil {
234 return resp, err
235 }
236 if statusIsCut {
237 resp.Status = statusInfo
238 }
239 } else {
240 resp.StatusCode = http.StatusOK
241 }
242
243 // TODO: fixTransferEncoding ?
244 resp.TransferEncoding = resp.Header["Transfer-Encoding"]
245 resp.ContentLength, _ = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
246
247 // wrap the response body in our closer
248 closer := clientCloser{
249 rwc: c.rwc,
250 r: r.(*streamReader),
251 Reader: rb,
252 status: resp.StatusCode,
253 logger: noopLogger,
254 }
255 if chunked(resp.TransferEncoding) {
256 closer.Reader = httputil.NewChunkedReader(rb)
257 }
258 if c.stderr {
259 closer.logger = c.logger
260 }
261 resp.Body = closer
262
263 return resp, err
264 }
265
266 // Get issues a GET request to the fcgi responder.
267 func (c *client) Get(p map[string]string, body io.Reader, l int64) (resp *http.Response, err error) {
268 p["REQUEST_METHOD"] = "GET"
269 p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10)
270
271 return c.Request(p, body)
272 }
273
274 // Head issues a HEAD request to the fcgi responder.
275 func (c *client) Head(p map[string]string) (resp *http.Response, err error) {
276 p["REQUEST_METHOD"] = "HEAD"
277 p["CONTENT_LENGTH"] = "0"
278
279 return c.Request(p, nil)
280 }
281
282 // Options issues an OPTIONS request to the fcgi responder.
283 func (c *client) Options(p map[string]string) (resp *http.Response, err error) {
284 p["REQUEST_METHOD"] = "OPTIONS"
285 p["CONTENT_LENGTH"] = "0"
286
287 return c.Request(p, nil)
288 }
289
290 // Post issues a POST request to the fcgi responder. with request body
291 // in the format that bodyType specified
292 func (c *client) Post(p map[string]string, method string, bodyType string, body io.Reader, l int64) (resp *http.Response, err error) {
293 if p == nil {
294 p = make(map[string]string)
295 }
296
297 p["REQUEST_METHOD"] = strings.ToUpper(method)
298
299 if len(p["REQUEST_METHOD"]) == 0 || p["REQUEST_METHOD"] == "GET" {
300 p["REQUEST_METHOD"] = "POST"
301 }
302
303 p["CONTENT_LENGTH"] = strconv.FormatInt(l, 10)
304 if len(bodyType) > 0 {
305 p["CONTENT_TYPE"] = bodyType
306 } else {
307 p["CONTENT_TYPE"] = "application/x-www-form-urlencoded"
308 }
309
310 return c.Request(p, body)
311 }
312
313 // PostForm issues a POST to the fcgi responder, with form
314 // as a string key to a list values (url.Values)
315 func (c *client) PostForm(p map[string]string, data url.Values) (resp *http.Response, err error) {
316 body := bytes.NewReader([]byte(data.Encode()))
317 return c.Post(p, "POST", "application/x-www-form-urlencoded", body, int64(body.Len()))
318 }
319
320 // PostFile issues a POST to the fcgi responder in multipart(RFC 2046) standard,
321 // with form as a string key to a list values (url.Values),
322 // and/or with file as a string key to a list file path.
323 func (c *client) PostFile(p map[string]string, data url.Values, file map[string]string) (resp *http.Response, err error) {
324 buf := &bytes.Buffer{}
325 writer := multipart.NewWriter(buf)
326 bodyType := writer.FormDataContentType()
327
328 for key, val := range data {
329 for _, v0 := range val {
330 err = writer.WriteField(key, v0)
331 if err != nil {
332 return resp, err
333 }
334 }
335 }
336
337 for key, val := range file {
338 fd, e := os.Open(val)
339 if e != nil {
340 return nil, e
341 }
342 defer fd.Close()
343
344 part, e := writer.CreateFormFile(key, filepath.Base(val))
345 if e != nil {
346 return nil, e
347 }
348 _, err = io.Copy(part, fd)
349 if err != nil {
350 return resp, err
351 }
352 }
353
354 err = writer.Close()
355 if err != nil {
356 return resp, err
357 }
358
359 return c.Post(p, "POST", bodyType, buf, int64(buf.Len()))
360 }
361
362 // SetReadTimeout sets the read timeout for future calls that read from the
363 // fcgi responder. A zero value for t means no timeout will be set.
364 func (c *client) SetReadTimeout(t time.Duration) error {
365 if t != 0 {
366 return c.rwc.SetReadDeadline(time.Now().Add(t))
367 }
368 return nil
369 }
370
371 // SetWriteTimeout sets the write timeout for future calls that send data to
372 // the fcgi responder. A zero value for t means no timeout will be set.
373 func (c *client) SetWriteTimeout(t time.Duration) error {
374 if t != 0 {
375 return c.rwc.SetWriteDeadline(time.Now().Add(t))
376 }
377 return nil
378 }
379
380 // Checks whether chunked is part of the encodings stack
381 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }