Debian Codegraph @

caddyconfig/load.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 caddyconfig
16
17 import (
18 "bytes"
19 "encoding/json"
20 "fmt"
21 "io"
22 "mime"
23 "net/http"
24 "strings"
25 "sync"
26
27 "github.com/caddyserver/caddy/v2"
28 )
29
30 func init() {
31 caddy.RegisterModule(adminLoad{})
32 }
33
34 // adminLoad is a module that provides the /load endpoint
35 // for the Caddy admin API. The only reason it's not baked
36 // into the caddy package directly is because of the import
37 // of the caddyconfig package for its GetAdapter function.
38 // If the caddy package depends on the caddyconfig package,
39 // then the caddyconfig package will not be able to import
40 // the caddy package, and it can more easily cause backward
41 // edges in the dependency tree (i.e. import cycle).
42 // Fortunately, the admin API has first-class support for
43 // adding endpoints from modules.
44 type adminLoad struct{}
45
46 // CaddyModule returns the Caddy module information.
47 func (adminLoad) CaddyModule() caddy.ModuleInfo {
48 return caddy.ModuleInfo{
49 ID: "admin.api.load",
50 New: func() caddy.Module { return new(adminLoad) },
51 }
52 }
53
54 // Routes returns a route for the /load endpoint.
55 func (al adminLoad) Routes() []caddy.AdminRoute {
56 return []caddy.AdminRoute{
57 {
58 Pattern: "/load",
59 Handler: caddy.AdminHandlerFunc(al.handleLoad),
60 },
61 {
62 Pattern: "/adapt",
63 Handler: caddy.AdminHandlerFunc(al.handleAdapt),
64 },
65 }
66 }
67
68 // handleLoad replaces the entire current configuration with
69 // a new one provided in the response body. It supports config
70 // adapters through the use of the Content-Type header. A
71 // config that is identical to the currently-running config
72 // will be a no-op unless Cache-Control: must-revalidate is set.
73 func (adminLoad) handleLoad(w http.ResponseWriter, r *http.Request) error {
74 if r.Method != http.MethodPost {
75 return caddy.APIError{
76 HTTPStatus: http.StatusMethodNotAllowed,
77 Err: fmt.Errorf("method not allowed"),
78 }
79 }
80
81 buf := bufPool.Get().(*bytes.Buffer)
82 buf.Reset()
83 defer bufPool.Put(buf)
84
85 _, err := io.Copy(buf, r.Body)
86 if err != nil {
87 return caddy.APIError{
88 HTTPStatus: http.StatusBadRequest,
89 Err: fmt.Errorf("reading request body: %v", err),
90 }
91 }
92 body := buf.Bytes()
93
94 // if the config is formatted other than Caddy's native
95 // JSON, we need to adapt it before loading it
96 if ctHeader := r.Header.Get("Content-Type"); ctHeader != "" {
97 result, warnings, err := adaptByContentType(ctHeader, body)
98 if err != nil {
99 return caddy.APIError{
100 HTTPStatus: http.StatusBadRequest,
101 Err: err,
102 }
103 }
104 if len(warnings) > 0 {
105 respBody, err := json.Marshal(warnings)
106 if err != nil {
107 caddy.Log().Named("admin.api.load").Error(err.Error())
108 }
109 _, _ = w.Write(respBody) //nolint:gosec // false positive: no XSS here
110 }
111 body = result
112 }
113
114 forceReload := r.Header.Get("Cache-Control") == "must-revalidate"
115
116 err = caddy.Load(body, forceReload)
117 if err != nil {
118 return caddy.APIError{
119 HTTPStatus: http.StatusBadRequest,
120 Err: fmt.Errorf("loading config: %v", err),
121 }
122 }
123
124 // If this request changed the config, clear the last
125 // config info we have stored, if it is different from
126 // the original source.
127 caddy.ClearLastConfigIfDifferent(
128 r.Header.Get("Caddy-Config-Source-File"),
129 r.Header.Get("Caddy-Config-Source-Adapter"))
130
131 caddy.Log().Named("admin.api").Info("load complete")
132
133 return nil
134 }
135
136 // handleAdapt adapts the given Caddy config to JSON and responds with the result.
137 func (adminLoad) handleAdapt(w http.ResponseWriter, r *http.Request) error {
138 if r.Method != http.MethodPost {
139 return caddy.APIError{
140 HTTPStatus: http.StatusMethodNotAllowed,
141 Err: fmt.Errorf("method not allowed"),
142 }
143 }
144
145 buf := bufPool.Get().(*bytes.Buffer)
146 buf.Reset()
147 defer bufPool.Put(buf)
148
149 _, err := io.Copy(buf, r.Body)
150 if err != nil {
151 return caddy.APIError{
152 HTTPStatus: http.StatusBadRequest,
153 Err: fmt.Errorf("reading request body: %v", err),
154 }
155 }
156
157 result, warnings, err := adaptByContentType(r.Header.Get("Content-Type"), buf.Bytes())
158 if err != nil {
159 return caddy.APIError{
160 HTTPStatus: http.StatusBadRequest,
161 Err: err,
162 }
163 }
164
165 out := struct {
166 Warnings []Warning `json:"warnings,omitempty"`
167 Result json.RawMessage `json:"result"`
168 }{
169 Warnings: warnings,
170 Result: result,
171 }
172
173 w.Header().Set("Content-Type", "application/json")
174 return json.NewEncoder(w).Encode(out)
175 }
176
177 // adaptByContentType adapts body to Caddy JSON using the adapter specified by contentType.
178 // If contentType is empty or ends with "/json", the input will be returned, as a no-op.
179 func adaptByContentType(contentType string, body []byte) ([]byte, []Warning, error) {
180 // assume JSON as the default
181 if contentType == "" {
182 return body, nil, nil
183 }
184
185 ct, _, err := mime.ParseMediaType(contentType)
186 if err != nil {
187 return nil, nil, caddy.APIError{
188 HTTPStatus: http.StatusBadRequest,
189 Err: fmt.Errorf("invalid Content-Type: %v", err),
190 }
191 }
192
193 // if already JSON, no need to adapt
194 if strings.HasSuffix(ct, "/json") {
195 return body, nil, nil
196 }
197
198 // adapter name should be suffix of MIME type
199 _, adapterName, slashFound := strings.Cut(ct, "/")
200 if !slashFound {
201 return nil, nil, fmt.Errorf("malformed Content-Type")
202 }
203
204 cfgAdapter := GetAdapter(adapterName)
205 if cfgAdapter == nil {
206 return nil, nil, fmt.Errorf("unrecognized config adapter '%s'", adapterName)
207 }
208
209 result, warnings, err := cfgAdapter.Adapt(body, nil)
210 if err != nil {
211 return nil, nil, fmt.Errorf("adapting config using %s adapter: %v", adapterName, err)
212 }
213
214 return result, warnings, nil
215 }
216
217 var bufPool = sync.Pool{
218 New: func() any {
219 return new(bytes.Buffer)
220 },
221 }