Debian Codegraph @

modules/caddyhttp/reverseproxy/fastcgi/caddyfile.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 package fastcgi
16
17 import (
18 "encoding/json"
19 "net/http"
20 "slices"
21 "strconv"
22 "strings"
23
24 "github.com/caddyserver/caddy/v2"
25 "github.com/caddyserver/caddy/v2/caddyconfig"
26 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
27 "github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
28 "github.com/caddyserver/caddy/v2/modules/caddyhttp"
29 "github.com/caddyserver/caddy/v2/modules/caddyhttp/fileserver"
30 "github.com/caddyserver/caddy/v2/modules/caddyhttp/reverseproxy"
31 "github.com/caddyserver/caddy/v2/modules/caddyhttp/rewrite"
32 )
33
34 func init() {
35 httpcaddyfile.RegisterDirective("php_fastcgi", parsePHPFastCGI)
36 }
37
38 // UnmarshalCaddyfile deserializes Caddyfile tokens into h.
39 //
40 // transport fastcgi {
41 // root <path>
42 // split <at>
43 // env <key> <value>
44 // resolve_root_symlink
45 // dial_timeout <duration>
46 // read_timeout <duration>
47 // write_timeout <duration>
48 // capture_stderr
49 // }
50 func (t *Transport) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
51 d.Next() // consume transport name
52 for d.NextBlock(0) {
53 switch d.Val() {
54 case "root":
55 if !d.NextArg() {
56 return d.ArgErr()
57 }
58 t.Root = d.Val()
59
60 case "split":
61 t.SplitPath = d.RemainingArgs()
62 if len(t.SplitPath) == 0 {
63 return d.ArgErr()
64 }
65
66 case "env":
67 args := d.RemainingArgs()
68 if len(args) != 2 {
69 return d.ArgErr()
70 }
71 if t.EnvVars == nil {
72 t.EnvVars = make(map[string]string)
73 }
74 t.EnvVars[args[0]] = args[1]
75
76 case "resolve_root_symlink":
77 if d.NextArg() {
78 return d.ArgErr()
79 }
80 t.ResolveRootSymlink = true
81
82 case "dial_timeout":
83 if !d.NextArg() {
84 return d.ArgErr()
85 }
86 dur, err := caddy.ParseDuration(d.Val())
87 if err != nil {
88 return d.Errf("bad timeout value %s: %v", d.Val(), err)
89 }
90 t.DialTimeout = caddy.Duration(dur)
91
92 case "read_timeout":
93 if !d.NextArg() {
94 return d.ArgErr()
95 }
96 dur, err := caddy.ParseDuration(d.Val())
97 if err != nil {
98 return d.Errf("bad timeout value %s: %v", d.Val(), err)
99 }
100 t.ReadTimeout = caddy.Duration(dur)
101
102 case "write_timeout":
103 if !d.NextArg() {
104 return d.ArgErr()
105 }
106 dur, err := caddy.ParseDuration(d.Val())
107 if err != nil {
108 return d.Errf("bad timeout value %s: %v", d.Val(), err)
109 }
110 t.WriteTimeout = caddy.Duration(dur)
111
112 case "capture_stderr":
113 if d.NextArg() {
114 return d.ArgErr()
115 }
116 t.CaptureStderr = true
117
118 default:
119 return d.Errf("unrecognized subdirective %s", d.Val())
120 }
121 }
122 return nil
123 }
124
125 // parsePHPFastCGI parses the php_fastcgi directive, which has the same syntax
126 // as the reverse_proxy directive (in fact, the reverse_proxy's directive
127 // Unmarshaler is invoked by this function) but the resulting proxy is specially
128 // configured for most™️ PHP apps over FastCGI. A line such as this:
129 //
130 // php_fastcgi localhost:7777
131 //
132 // is equivalent to a route consisting of:
133 //
134 // # Add trailing slash for directory requests
135 // # This redirection is automatically disabled if "{http.request.uri.path}/index.php"
136 // # doesn't appear in the try_files list
137 // @canonicalPath {
138 // file {path}/index.php
139 // not path */
140 // }
141 // redir @canonicalPath {path}/ 308
142 //
143 // # If the requested file does not exist, try index files and assume index.php always exists
144 // @indexFiles file {
145 // try_files {path} {path}/index.php index.php
146 // try_policy first_exist_fallback
147 // split_path .php
148 // }
149 // rewrite @indexFiles {http.matchers.file.relative}
150 //
151 // # Proxy PHP files to the FastCGI responder
152 // @phpFiles path *.php
153 // reverse_proxy @phpFiles localhost:7777 {
154 // transport fastcgi {
155 // split .php
156 // }
157 // }
158 //
159 // Thus, this directive produces multiple handlers, each with a different
160 // matcher because multiple consecutive handlers are necessary to support
161 // the common PHP use case. If this "common" config is not compatible
162 // with a user's PHP requirements, they can use a manual approach based
163 // on the example above to configure it precisely as they need.
164 //
165 // If a matcher is specified by the user, for example:
166 //
167 // php_fastcgi /subpath localhost:7777
168 //
169 // then the resulting handlers are wrapped in a subroute that uses the
170 // user's matcher as a prerequisite to enter the subroute. In other
171 // words, the directive's matcher is necessary, but not sufficient.
172 func parsePHPFastCGI(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error) {
173 if !h.Next() {
174 return nil, h.ArgErr()
175 }
176
177 // set up the transport for FastCGI, and specifically PHP
178 fcgiTransport := Transport{}
179
180 // set up the set of file extensions allowed to execute PHP code
181 extensions := []string{".php"}
182
183 // set the default index file for the try_files rewrites
184 indexFile := "index.php"
185
186 // set up for explicitly overriding try_files
187 var tryFiles []string
188
189 // if the user specified a matcher token, use that
190 // matcher in a route that wraps both of our routes;
191 // either way, strip the matcher token and pass
192 // the remaining tokens to the unmarshaler so that
193 // we can gain the rest of the reverse_proxy syntax
194 userMatcherSet, err := h.ExtractMatcherSet()
195 if err != nil {
196 return nil, err
197 }
198
199 // make a new dispenser from the remaining tokens so that we
200 // can reset the dispenser back to this point for the
201 // reverse_proxy unmarshaler to read from it as well
202 dispenser := h.NewFromNextSegment()
203
204 // read the subdirectives that we allow as overrides to
205 // the php_fastcgi shortcut
206 // NOTE: we delete the tokens as we go so that the reverse_proxy
207 // unmarshal doesn't see these subdirectives which it cannot handle
208 for dispenser.Next() {
209 for dispenser.NextBlock(0) {
210 // ignore any sub-subdirectives that might
211 // have the same name somewhere within
212 // the reverse_proxy passthrough tokens
213 if dispenser.Nesting() != 1 {
214 continue
215 }
216
217 // parse the php_fastcgi subdirectives
218 switch dispenser.Val() {
219 case "root":
220 if !dispenser.NextArg() {
221 return nil, dispenser.ArgErr()
222 }
223 fcgiTransport.Root = dispenser.Val()
224 dispenser.DeleteN(2)
225
226 case "split":
227 extensions = dispenser.RemainingArgs()
228 dispenser.DeleteN(len(extensions) + 1)
229 if len(extensions) == 0 {
230 return nil, dispenser.ArgErr()
231 }
232
233 case "env":
234 args := dispenser.RemainingArgs()
235 dispenser.DeleteN(len(args) + 1)
236 if len(args) != 2 {
237 return nil, dispenser.ArgErr()
238 }
239 if fcgiTransport.EnvVars == nil {
240 fcgiTransport.EnvVars = make(map[string]string)
241 }
242 fcgiTransport.EnvVars[args[0]] = args[1]
243
244 case "index":
245 args := dispenser.RemainingArgs()
246 dispenser.DeleteN(len(args) + 1)
247 if len(args) != 1 {
248 return nil, dispenser.ArgErr()
249 }
250 indexFile = args[0]
251
252 case "try_files":
253 args := dispenser.RemainingArgs()
254 dispenser.DeleteN(len(args) + 1)
255 if len(args) < 1 {
256 return nil, dispenser.ArgErr()
257 }
258 tryFiles = args
259
260 case "resolve_root_symlink":
261 args := dispenser.RemainingArgs()
262 dispenser.DeleteN(len(args) + 1)
263 fcgiTransport.ResolveRootSymlink = true
264
265 case "dial_timeout":
266 if !dispenser.NextArg() {
267 return nil, dispenser.ArgErr()
268 }
269 dur, err := caddy.ParseDuration(dispenser.Val())
270 if err != nil {
271 return nil, dispenser.Errf("bad timeout value %s: %v", dispenser.Val(), err)
272 }
273 fcgiTransport.DialTimeout = caddy.Duration(dur)
274 dispenser.DeleteN(2)
275
276 case "read_timeout":
277 if !dispenser.NextArg() {
278 return nil, dispenser.ArgErr()
279 }
280 dur, err := caddy.ParseDuration(dispenser.Val())
281 if err != nil {
282 return nil, dispenser.Errf("bad timeout value %s: %v", dispenser.Val(), err)
283 }
284 fcgiTransport.ReadTimeout = caddy.Duration(dur)
285 dispenser.DeleteN(2)
286
287 case "write_timeout":
288 if !dispenser.NextArg() {
289 return nil, dispenser.ArgErr()
290 }
291 dur, err := caddy.ParseDuration(dispenser.Val())
292 if err != nil {
293 return nil, dispenser.Errf("bad timeout value %s: %v", dispenser.Val(), err)
294 }
295 fcgiTransport.WriteTimeout = caddy.Duration(dur)
296 dispenser.DeleteN(2)
297
298 case "capture_stderr":
299 args := dispenser.RemainingArgs()
300 dispenser.DeleteN(len(args) + 1)
301 fcgiTransport.CaptureStderr = true
302 }
303 }
304 }
305
306 // reset the dispenser after we're done so that the reverse_proxy
307 // unmarshaler can read it from the start
308 dispenser.Reset()
309
310 // set up a route list that we'll append to
311 routes := caddyhttp.RouteList{}
312
313 // set the list of allowed path segments on which to split
314 fcgiTransport.SplitPath = extensions
315
316 // if the index is turned off, we skip the redirect and try_files
317 if indexFile != "off" {
318 var dirRedir bool
319 dirIndex := "{http.request.uri.path}/" + indexFile
320 tryPolicy := "first_exist_fallback"
321
322 // if tryFiles wasn't overridden, use a reasonable default
323 if len(tryFiles) == 0 {
324 tryFiles = []string{"{http.request.uri.path}", dirIndex, indexFile}
325 dirRedir = true
326 } else {
327 if !strings.HasSuffix(tryFiles[len(tryFiles)-1], ".php") {
328 // use first_exist strategy if the last file is not a PHP file
329 tryPolicy = ""
330 }
331
332 dirRedir = slices.Contains(tryFiles, dirIndex)
333 }
334
335 if dirRedir {
336 // route to redirect to canonical path if index PHP file
337 redirMatcherSet := caddy.ModuleMap{
338 "file": h.JSON(fileserver.MatchFile{
339 TryFiles: []string{dirIndex},
340 }),
341 "not": h.JSON(caddyhttp.MatchNot{
342 MatcherSetsRaw: []caddy.ModuleMap{
343 {
344 "path": h.JSON(caddyhttp.MatchPath{"*/"}),
345 },
346 },
347 }),
348 }
349 redirHandler := caddyhttp.StaticResponse{
350 StatusCode: caddyhttp.WeakString(strconv.Itoa(http.StatusPermanentRedirect)),
351 Headers: http.Header{"Location": []string{"{http.request.orig_uri.path}/{http.request.orig_uri.prefixed_query}"}},
352 }
353 redirRoute := caddyhttp.Route{
354 MatcherSetsRaw: []caddy.ModuleMap{redirMatcherSet},
355 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(redirHandler, "handler", "static_response", nil)},
356 }
357
358 routes = append(routes, redirRoute)
359 }
360
361 // route to rewrite to PHP index file
362 rewriteMatcherSet := caddy.ModuleMap{
363 "file": h.JSON(fileserver.MatchFile{
364 TryFiles: tryFiles,
365 TryPolicy: tryPolicy,
366 SplitPath: extensions,
367 }),
368 }
369 rewriteHandler := rewrite.Rewrite{
370 URI: "{http.matchers.file.relative}",
371 }
372 rewriteRoute := caddyhttp.Route{
373 MatcherSetsRaw: []caddy.ModuleMap{rewriteMatcherSet},
374 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(rewriteHandler, "handler", "rewrite", nil)},
375 }
376
377 routes = append(routes, rewriteRoute)
378 }
379
380 // route to actually reverse proxy requests to PHP files;
381 // match only requests that are for PHP files
382 pathList := []string{}
383 for _, ext := range extensions {
384 pathList = append(pathList, "*"+ext)
385 }
386 rpMatcherSet := caddy.ModuleMap{
387 "path": h.JSON(pathList),
388 }
389
390 // create the reverse proxy handler which uses our FastCGI transport
391 rpHandler := &reverseproxy.Handler{
392 TransportRaw: caddyconfig.JSONModuleObject(fcgiTransport, "protocol", "fastcgi", nil),
393 }
394
395 // the rest of the config is specified by the user
396 // using the reverse_proxy directive syntax
397 dispenser.Next() // consume the directive name
398 err = rpHandler.UnmarshalCaddyfile(dispenser)
399 if err != nil {
400 return nil, err
401 }
402 err = rpHandler.FinalizeUnmarshalCaddyfile(h)
403 if err != nil {
404 return nil, err
405 }
406
407 // create the final reverse proxy route which is
408 // conditional on matching PHP files
409 rpRoute := caddyhttp.Route{
410 MatcherSetsRaw: []caddy.ModuleMap{rpMatcherSet},
411 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(rpHandler, "handler", "reverse_proxy", nil)},
412 }
413
414 subroute := caddyhttp.Subroute{
415 Routes: append(routes, rpRoute),
416 }
417
418 // the user's matcher is a prerequisite for ours, so
419 // wrap ours in a subroute and return that
420 if userMatcherSet != nil {
421 return []httpcaddyfile.ConfigValue{
422 {
423 Class: "route",
424 Value: caddyhttp.Route{
425 MatcherSetsRaw: []caddy.ModuleMap{userMatcherSet},
426 HandlersRaw: []json.RawMessage{caddyconfig.JSONModuleObject(subroute, "handler", "subroute", nil)},
427 },
428 },
429 }, nil
430 }
431
432 // otherwise, return the literal subroute instead of
433 // individual routes, to ensure they stay together and
434 // are treated as a single unit, without necessarily
435 // creating an actual subroute in the output
436 return []httpcaddyfile.ConfigValue{
437 {
438 Class: "route",
439 Value: subroute,
440 },
441 }, nil
442 }