-
Notifications
You must be signed in to change notification settings - Fork 180
/
caddy.go
329 lines (273 loc) · 7.18 KB
/
caddy.go
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
/*
* Copyright (c) 2019-2022. Abstrium SAS <team (at) pydio.com>
* This file is part of Pydio Cells.
*
* Pydio Cells is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio Cells is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio Cells. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
package caddy
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"text/template"
caddy "github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
_ "github.com/caddyserver/caddy/v2/modules/standard"
"github.com/pydio/caddyvault"
"github.com/pydio/cells/v4/common/crypto/storage"
"go.uber.org/zap"
"github.com/pydio/cells/v4/common"
"github.com/pydio/cells/v4/common/config"
"github.com/pydio/cells/v4/common/crypto/providers"
"github.com/pydio/cells/v4/common/log"
"github.com/pydio/cells/v4/common/registry"
"github.com/pydio/cells/v4/common/registry/util"
"github.com/pydio/cells/v4/common/runtime"
"github.com/pydio/cells/v4/common/server"
"github.com/pydio/cells/v4/common/server/caddy/mux"
"github.com/pydio/cells/v4/common/utils/uuid"
)
const (
caddytemplate = `
{
auto_https disable_redirects
admin off
{{if .Storage}} storage {{.Storage}}{{end}}
}
{{range .Sites}}
{{$SiteWebRoot := .WebRoot}}
{{$ExternalHost := .ExternalHost}}
{{$Maintenance := .Maintenance}}
{{$MaintenanceConditions := .MaintenanceConditions}}
{{range .Binds}}{{.}} {{end}} {
root * "{{if $SiteWebRoot}}{{$SiteWebRoot}}{{else}}{{$.WebRoot}}{{end}}"
@list_buckets {
path / /probe-bucket-sign*
header Authorization *AWS4-HMAC-SHA256*
}
route /* {
{{if $ExternalHost}}request_header Host {{$ExternalHost}}{{end}}
request_header X-Real-IP {http.request.remote}
request_header X-Forwarded-Proto {http.request.scheme}
{{if $Maintenance}}
# Special redir for maintenance mode
@rmatcher {
{{range $MaintenanceConditions}}{{.}}
{{end}}
not path /maintenance.html
}
request_header X-Maintenance-Redirect "true"
redir @rmatcher /maintenance.html
{{end}}
# Special rewrite for s3 list buckets (always sent on root path)
rewrite @list_buckets /io{path}
# Apply mux
mux
# If mux did not find endpoint, redirect all to root and re-apply mux
rewrite /* /
mux
}
{{if .Log}}
log {
output file "{{.Log}}"
level {{.LogLevel}}
}
{{end}}
{{if .TLS}}tls {{.TLS}}{{end}}
{{if .TLSCert}}tls "{{.TLSCert}}" "{{.TLSKey}}"{{end}}
}
{{if .SSLRedirect}}
{{range $k,$v := .Redirects}}
{{$k}} {
redir {{$v}}
}
{{end}}
{{end}}
{{end}}
`
)
func init() {
server.DefaultURLMux().Register("caddy", &Opener{})
}
var (
providersLoggerInit sync.Once
)
type Opener struct{}
func (o *Opener) OpenURL(ctx context.Context, u *url.URL) (server.Server, error) {
return New(ctx, "")
}
type Server struct {
*server.ListableMux
id string
name string
meta map[string]string
serveDir string
rootCtx context.Context
restartRequired bool
caddyConfig []byte
}
func New(ctx context.Context, dir string) (server.Server, error) {
providersLoggerInit.Do(func() {
ct := log.CaptureCaddyStdErr("pydio.server.caddy")
providers.Logger = log.Logger(ct)
})
srvMUX := server.NewListableMux()
mux.RegisterServerMux(ctx, srvMUX)
caddyStorePath := filepath.Join(runtime.ApplicationWorkingDir(), "caddy")
_ = os.MkdirAll(caddyStorePath, 0755)
if _, e := os.Stat(caddyStorePath); e == nil {
caddy.DefaultStorage.Path = caddyStorePath
caddy.ConfigAutosavePath = filepath.Join(caddyStorePath, "autosave.json")
}
srv := &Server{
id: "caddy-" + uuid.New(),
name: "caddy",
meta: make(map[string]string),
rootCtx: ctx,
serveDir: dir,
ListableMux: srvMUX,
}
return server.NewServer(ctx, srv), nil
}
func (s *Server) RawServe(*server.ServeOptions) (ii []registry.Item, er error) {
aa, err := s.ComputeConfs()
if err != nil {
return nil, err
}
if er := caddy.Load(s.caddyConfig, true); er != nil {
return nil, er
}
for _, a := range aa {
ii = append(ii, util.CreateAddress(a, nil))
}
for _, e := range s.ListableMux.Patterns() {
ii = append(ii, util.CreateEndpoint(e, nil))
}
return
}
func (s *Server) ComputeConfs() ([]string, error) {
// Creating temporary caddy file
sites, err := config.LoadSites()
if err != nil {
return nil, err
}
caddySites, err := SitesToCaddyConfigs(sites)
if err != nil {
return nil, err
}
tmpl, err := template.New("pydiocaddy").Parse(caddytemplate)
if err != nil {
return nil, err
}
type TplData struct {
Sites []SiteConf
WebRoot string
Storage string
}
tplData := TplData{Sites: caddySites}
if s.serveDir != "" {
tplData.WebRoot = s.serveDir
}
k, e := storage.OpenStore(context.Background(), runtime.CertsStoreURL())
if e != nil {
return nil, e
}
// Special treatment for vault : append info to caddy
if vs, ok := k.(*caddyvault.VaultStorage); ok {
tplData.Storage = `vault {
address "` + vs.API + `"
token ` + vs.Token + `
prefix ` + vs.Prefix + `
}`
}
buf := bytes.NewBuffer([]byte{})
if err := tmpl.Execute(buf, tplData); err != nil {
return nil, err
}
b := buf.Bytes()
b = caddyfile.Format(b)
if common.LogLevel == zap.DebugLevel {
fmt.Println(string(b))
}
// Load config directly from memory
adapter := caddyconfig.GetAdapter("caddyfile")
confs, ww, err := adapter.Adapt(b, map[string]interface{}{})
if err != nil {
return nil, err
}
for _, w := range ww {
log.Logger(s.rootCtx).Warn(w.String())
}
s.caddyConfig = confs
var addresses []string
for _, site := range caddySites {
for _, bind := range site.GetBinds() {
//s.addresses = append(s.addresses, bind)
bind = strings.TrimPrefix(bind, "http://")
bind = strings.TrimPrefix(bind, "https://")
host, port, err := net.SplitHostPort(bind)
if err != nil {
continue
}
ip := net.ParseIP(host)
if ip == nil || ip.IsUnspecified() {
addresses = append(addresses, net.JoinHostPort(runtime.DefaultAdvertiseAddress(), port))
} else {
addresses = append(addresses, bind)
}
}
}
return addresses, nil
}
func (s *Server) Type() server.Type {
return server.TypeHttp
}
func (s *Server) Stop() error {
return caddy.Stop()
}
func (s *Server) Endpoints() []string {
return s.ListableMux.Patterns()
}
func (s *Server) ID() string {
return s.id
}
func (s *Server) Name() string {
return s.name
}
func (s *Server) Metadata() map[string]string {
return s.meta // map[string]string{}
}
func (s *Server) SetMetadata(meta map[string]string) {
s.meta = meta
}
func (s *Server) As(i interface{}) bool {
if v, ok := i.(*server.HttpMux); ok {
*v = s.ListableMux
return true
}
if v, ok := i.(*server.PatternsProvider); ok {
*v = s.ListableMux
return true
}
return false
}