2019-07-01 06:07:58 +08:00
|
|
|
// Copyright 2015 Matthew Holt and The Caddy Authors
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
|
|
// you may not use this file except in compliance with the License.
|
|
|
|
// You may obtain a copy of the License at
|
|
|
|
//
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
//
|
|
|
|
// Unless required by applicable law or agreed to in writing, software
|
|
|
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
|
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
// See the License for the specific language governing permissions and
|
|
|
|
// limitations under the License.
|
|
|
|
|
2019-06-15 01:58:28 +08:00
|
|
|
package caddy
|
2019-03-27 02:00:54 +08:00
|
|
|
|
|
|
|
import (
|
2019-03-27 09:42:52 +08:00
|
|
|
"bytes"
|
2019-03-27 02:00:54 +08:00
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2019-10-31 05:12:42 +08:00
|
|
|
"errors"
|
2019-03-27 02:00:54 +08:00
|
|
|
"fmt"
|
|
|
|
"io"
|
2019-08-23 04:52:39 +08:00
|
|
|
"io/ioutil"
|
2019-03-27 02:00:54 +08:00
|
|
|
"log"
|
2019-09-03 02:21:41 +08:00
|
|
|
"mime"
|
2019-03-27 02:00:54 +08:00
|
|
|
"net"
|
|
|
|
"net/http"
|
2019-03-27 09:42:52 +08:00
|
|
|
"net/http/pprof"
|
2019-07-21 00:48:46 +08:00
|
|
|
"os"
|
2019-03-27 02:00:54 +08:00
|
|
|
"strings"
|
|
|
|
"sync"
|
2019-03-27 09:42:52 +08:00
|
|
|
"time"
|
2019-06-06 01:10:19 +08:00
|
|
|
|
2019-08-24 00:57:51 +08:00
|
|
|
"github.com/caddyserver/caddy/v2/caddyconfig"
|
2019-07-21 00:48:46 +08:00
|
|
|
"github.com/mholt/certmagic"
|
2019-06-06 01:10:19 +08:00
|
|
|
"github.com/rs/cors"
|
2019-10-29 04:39:37 +08:00
|
|
|
"go.uber.org/zap"
|
2019-03-27 02:00:54 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
cfgEndptSrv *http.Server
|
|
|
|
cfgEndptSrvMu sync.Mutex
|
|
|
|
)
|
|
|
|
|
2019-10-31 05:12:42 +08:00
|
|
|
var ErrAdminInterfaceNotConfigured = errors.New("no admin configuration has been set")
|
|
|
|
|
2019-06-29 05:39:41 +08:00
|
|
|
// AdminConfig configures the admin endpoint.
|
|
|
|
type AdminConfig struct {
|
|
|
|
Listen string `json:"listen,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// DefaultAdminConfig is the default configuration
|
|
|
|
// for the administration endpoint.
|
|
|
|
var DefaultAdminConfig = &AdminConfig{
|
2019-07-05 23:59:13 +08:00
|
|
|
Listen: DefaultAdminListen,
|
2019-06-29 05:39:41 +08:00
|
|
|
}
|
|
|
|
|
2019-10-29 04:39:37 +08:00
|
|
|
// TODO: holy smokes, the admin endpoint might not have to live in caddy's core.
|
|
|
|
|
2019-06-29 05:39:41 +08:00
|
|
|
// StartAdmin starts Caddy's administration endpoint,
|
|
|
|
// bootstrapping it with an optional configuration
|
|
|
|
// in the format of JSON bytes. It opens a listener
|
|
|
|
// resource. When no longer needed, StopAdmin should
|
|
|
|
// be called.
|
2019-10-31 05:12:42 +08:00
|
|
|
// If no configuration is given, a default listener is
|
|
|
|
// started. If a configuration is given that does NOT
|
|
|
|
// specifically configure the admin interface,
|
|
|
|
// `ErrAdminInterfaceNotConfigured` is returned and no
|
|
|
|
// listener is initialized.
|
2019-06-29 05:39:41 +08:00
|
|
|
func StartAdmin(initialConfigJSON []byte) error {
|
2019-03-27 02:00:54 +08:00
|
|
|
cfgEndptSrvMu.Lock()
|
|
|
|
defer cfgEndptSrvMu.Unlock()
|
|
|
|
|
2019-10-31 05:12:42 +08:00
|
|
|
if cfgEndptSrv != nil {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
err := cfgEndptSrv.Shutdown(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("shutting down old admin endpoint: %v", err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-29 05:39:41 +08:00
|
|
|
adminConfig := DefaultAdminConfig
|
|
|
|
if len(initialConfigJSON) > 0 {
|
|
|
|
var config *Config
|
|
|
|
err := json.Unmarshal(initialConfigJSON, &config)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unmarshaling bootstrap config: %v", err)
|
|
|
|
}
|
2019-10-31 05:12:42 +08:00
|
|
|
if config != nil {
|
|
|
|
if config.Admin == nil {
|
|
|
|
return ErrAdminInterfaceNotConfigured
|
2019-06-29 05:39:41 +08:00
|
|
|
}
|
2019-10-31 05:12:42 +08:00
|
|
|
adminConfig = config.Admin
|
2019-06-29 05:39:41 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-09-14 01:24:07 +08:00
|
|
|
// extract a singular listener address
|
|
|
|
netw, listenAddrs, err := ParseNetworkAddress(adminConfig.Listen)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("parsing admin listener address: %v", err)
|
|
|
|
}
|
|
|
|
if len(listenAddrs) != 1 {
|
2019-10-10 09:10:00 +08:00
|
|
|
return fmt.Errorf("admin endpoint must have exactly one address; cannot listen on %v", listenAddrs)
|
2019-09-14 01:24:07 +08:00
|
|
|
}
|
|
|
|
ln, err := net.Listen(netw, listenAddrs[0])
|
2019-03-27 02:00:54 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
mux := http.NewServeMux()
|
|
|
|
mux.HandleFunc("/load", handleLoadConfig)
|
2019-07-21 00:48:46 +08:00
|
|
|
mux.HandleFunc("/stop", handleStop)
|
2019-03-27 02:00:54 +08:00
|
|
|
|
2019-03-28 02:36:30 +08:00
|
|
|
///// BEGIN PPROF STUFF (TODO: Temporary) /////
|
2019-03-27 09:42:52 +08:00
|
|
|
mux.HandleFunc("/debug/pprof/", pprof.Index)
|
|
|
|
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
|
|
|
|
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
|
|
|
|
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
|
|
|
|
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
|
|
|
|
///// END PPROF STUFF //////
|
|
|
|
|
2019-08-22 00:46:35 +08:00
|
|
|
for _, m := range GetModules("admin.routers") {
|
|
|
|
adminrtr := m.New().(AdminRouter)
|
|
|
|
for _, route := range adminrtr.Routes() {
|
2019-08-10 02:05:47 +08:00
|
|
|
mux.Handle(route.Pattern, route)
|
|
|
|
}
|
2019-03-27 02:00:54 +08:00
|
|
|
}
|
|
|
|
|
2019-10-29 04:39:37 +08:00
|
|
|
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// TODO: improve/organize this logging
|
|
|
|
Log().Named("admin.request").Info("",
|
|
|
|
zap.String("method", r.Method),
|
|
|
|
zap.String("uri", r.RequestURI),
|
|
|
|
zap.String("remote", r.RemoteAddr),
|
|
|
|
)
|
|
|
|
cors.Default().Handler(mux).ServeHTTP(w, r)
|
|
|
|
})
|
2019-06-06 01:10:19 +08:00
|
|
|
|
2019-03-27 02:00:54 +08:00
|
|
|
cfgEndptSrv = &http.Server{
|
2019-06-06 01:10:19 +08:00
|
|
|
Handler: handler,
|
2019-03-27 09:42:52 +08:00
|
|
|
ReadTimeout: 5 * time.Second,
|
|
|
|
ReadHeaderTimeout: 5 * time.Second,
|
|
|
|
IdleTimeout: 5 * time.Second,
|
2019-10-10 09:10:00 +08:00
|
|
|
MaxHeaderBytes: 1024 * 64,
|
2019-03-27 02:00:54 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
go cfgEndptSrv.Serve(ln)
|
|
|
|
|
2019-10-31 05:12:42 +08:00
|
|
|
Log().Named("admin").Info("Caddy 2 admin endpoint started.", zap.String("listenAddress", adminConfig.Listen))
|
2019-06-29 05:39:41 +08:00
|
|
|
|
2019-03-27 02:00:54 +08:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-03-27 05:45:51 +08:00
|
|
|
// StopAdmin stops the API endpoint.
|
|
|
|
func StopAdmin() error {
|
2019-03-27 02:00:54 +08:00
|
|
|
cfgEndptSrvMu.Lock()
|
|
|
|
defer cfgEndptSrvMu.Unlock()
|
|
|
|
|
|
|
|
if cfgEndptSrv == nil {
|
|
|
|
return fmt.Errorf("no server")
|
|
|
|
}
|
|
|
|
|
|
|
|
err := cfgEndptSrv.Shutdown(context.Background()) // TODO
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("shutting down server: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
cfgEndptSrv = nil
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-08-22 00:46:35 +08:00
|
|
|
// AdminRouter is a type which can return routes for the admin API.
|
|
|
|
type AdminRouter interface {
|
|
|
|
Routes() []AdminRoute
|
|
|
|
}
|
|
|
|
|
2019-03-27 05:45:51 +08:00
|
|
|
// AdminRoute represents a route for the admin endpoint.
|
|
|
|
type AdminRoute struct {
|
|
|
|
http.Handler
|
|
|
|
Pattern string
|
|
|
|
}
|
|
|
|
|
2019-03-27 02:00:54 +08:00
|
|
|
func handleLoadConfig(w http.ResponseWriter, r *http.Request) {
|
2019-07-21 00:48:46 +08:00
|
|
|
if r.Method != http.MethodPost {
|
2019-03-27 02:00:54 +08:00
|
|
|
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-08-23 04:52:39 +08:00
|
|
|
// if the config is formatted other than Caddy's native
|
|
|
|
// JSON, we need to adapt it before loading it
|
2019-09-03 02:21:41 +08:00
|
|
|
if ctHeader := r.Header.Get("Content-Type"); ctHeader != "" {
|
|
|
|
ct, _, err := mime.ParseMediaType(ctHeader)
|
2019-08-23 04:52:39 +08:00
|
|
|
if err != nil {
|
2019-09-03 02:21:41 +08:00
|
|
|
http.Error(w, "Invalid Content-Type: "+err.Error(), http.StatusBadRequest)
|
2019-08-23 04:52:39 +08:00
|
|
|
return
|
|
|
|
}
|
2019-09-03 02:21:41 +08:00
|
|
|
if !strings.HasSuffix(ct, "/json") {
|
|
|
|
slashIdx := strings.Index(ct, "/")
|
|
|
|
if slashIdx < 0 {
|
|
|
|
http.Error(w, "Malformed Content-Type", http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
adapterName := ct[slashIdx+1:]
|
|
|
|
cfgAdapter := caddyconfig.GetAdapter(adapterName)
|
|
|
|
if cfgAdapter == nil {
|
|
|
|
http.Error(w, "Unrecognized config adapter: "+adapterName, http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(http.MaxBytesReader(w, r.Body, 1024*1024))
|
2019-08-23 04:52:39 +08:00
|
|
|
if err != nil {
|
2019-09-03 02:21:41 +08:00
|
|
|
http.Error(w, "Error reading request body: "+err.Error(), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
result, warnings, err := cfgAdapter.Adapt(body, nil)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("[ADMIN][ERROR] adapting config from %s: %v", adapterName, err)
|
|
|
|
http.Error(w, fmt.Sprintf("Adapting config from %s: %v", adapterName, err), http.StatusBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if len(warnings) > 0 {
|
|
|
|
respBody, err := json.Marshal(warnings)
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("[ADMIN][ERROR] marshaling warnings: %v", err)
|
|
|
|
}
|
|
|
|
w.Write(respBody)
|
2019-08-23 04:52:39 +08:00
|
|
|
}
|
2019-10-10 09:10:00 +08:00
|
|
|
// replace original request body with adapted JSON
|
|
|
|
r.Body.Close()
|
|
|
|
r.Body = ioutil.NopCloser(bytes.NewReader(result))
|
2019-08-23 04:52:39 +08:00
|
|
|
}
|
2019-03-27 02:00:54 +08:00
|
|
|
}
|
|
|
|
|
2019-10-10 09:10:00 +08:00
|
|
|
// pass this off to the /config/ endpoint
|
|
|
|
r.URL.Path = "/" + rawConfigKey + "/"
|
|
|
|
handleConfig(w, r)
|
2019-03-27 02:00:54 +08:00
|
|
|
}
|
|
|
|
|
2019-07-21 00:48:46 +08:00
|
|
|
func handleStop(w http.ResponseWriter, r *http.Request) {
|
|
|
|
if r.Method != http.MethodPost {
|
|
|
|
http.Error(w, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
log.Println("[ADMIN] Initiating shutdown")
|
|
|
|
if err := stopAndCleanup(); err != nil {
|
|
|
|
log.Printf("[ADMIN][ERROR] stopping: %v \n", err)
|
|
|
|
}
|
|
|
|
log.Println("[ADMIN] Exiting")
|
|
|
|
os.Exit(0)
|
|
|
|
}
|
|
|
|
|
|
|
|
func stopAndCleanup() error {
|
|
|
|
if err := Stop(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
certmagic.CleanUpOwnLocks()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2019-03-27 05:45:51 +08:00
|
|
|
// Load loads and starts a configuration.
|
2019-03-27 02:00:54 +08:00
|
|
|
func Load(r io.Reader) error {
|
2019-03-27 09:42:52 +08:00
|
|
|
buf := bufPool.Get().(*bytes.Buffer)
|
|
|
|
buf.Reset()
|
|
|
|
defer bufPool.Put(buf)
|
|
|
|
|
|
|
|
_, err := io.Copy(buf, io.LimitReader(r, 1024*1024))
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
var cfg *Config
|
2019-03-27 09:42:52 +08:00
|
|
|
err = json.Unmarshal(buf.Bytes(), &cfg)
|
2019-03-27 02:00:54 +08:00
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("decoding config: %v", err)
|
|
|
|
}
|
2019-03-27 09:42:52 +08:00
|
|
|
|
2019-04-26 03:54:48 +08:00
|
|
|
err = Run(cfg)
|
2019-03-27 05:45:51 +08:00
|
|
|
if err != nil {
|
2019-04-26 03:54:48 +08:00
|
|
|
return fmt.Errorf("running: %v", err)
|
2019-03-27 02:00:54 +08:00
|
|
|
}
|
2019-03-27 09:42:52 +08:00
|
|
|
|
2019-03-27 02:00:54 +08:00
|
|
|
return nil
|
|
|
|
}
|
2019-03-27 09:42:52 +08:00
|
|
|
|
2019-07-05 23:59:13 +08:00
|
|
|
// DefaultAdminListen is the address for the admin
|
|
|
|
// listener, if none is specified at startup.
|
|
|
|
var DefaultAdminListen = "localhost:2019"
|
|
|
|
|
2019-03-27 09:42:52 +08:00
|
|
|
var bufPool = sync.Pool{
|
|
|
|
New: func() interface{} {
|
|
|
|
return new(bytes.Buffer)
|
|
|
|
},
|
|
|
|
}
|