2022-07-19 14:16:49 +00:00
|
|
|
package clashapi
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2022-09-10 06:09:47 +00:00
|
|
|
"strings"
|
2022-07-19 14:16:49 +00:00
|
|
|
|
|
|
|
"github.com/sagernet/sing-box/log"
|
|
|
|
|
|
|
|
"github.com/go-chi/chi/v5"
|
|
|
|
"github.com/go-chi/render"
|
|
|
|
)
|
|
|
|
|
2022-09-10 06:09:47 +00:00
|
|
|
func configRouter(server *Server, logFactory log.Factory, logger log.Logger) http.Handler {
|
2022-07-19 14:16:49 +00:00
|
|
|
r := chi.NewRouter()
|
2022-09-10 06:09:47 +00:00
|
|
|
r.Get("/", getConfigs(server, logFactory))
|
2022-07-19 14:16:49 +00:00
|
|
|
r.Put("/", updateConfigs)
|
2022-09-10 06:09:47 +00:00
|
|
|
r.Patch("/", patchConfigs(server, logger))
|
2022-07-19 14:16:49 +00:00
|
|
|
return r
|
|
|
|
}
|
|
|
|
|
|
|
|
type configSchema struct {
|
2022-07-21 13:03:41 +00:00
|
|
|
Port int `json:"port"`
|
|
|
|
SocksPort int `json:"socks-port"`
|
|
|
|
RedirPort int `json:"redir-port"`
|
|
|
|
TProxyPort int `json:"tproxy-port"`
|
|
|
|
MixedPort int `json:"mixed-port"`
|
|
|
|
AllowLan bool `json:"allow-lan"`
|
|
|
|
BindAddress string `json:"bind-address"`
|
|
|
|
Mode string `json:"mode"`
|
|
|
|
LogLevel string `json:"log-level"`
|
|
|
|
IPv6 bool `json:"ipv6"`
|
|
|
|
Tun map[string]any `json:"tun"`
|
2022-07-19 14:16:49 +00:00
|
|
|
}
|
|
|
|
|
2022-09-10 06:09:47 +00:00
|
|
|
func getConfigs(server *Server, logFactory log.Factory) func(w http.ResponseWriter, r *http.Request) {
|
2022-07-19 14:16:49 +00:00
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2022-07-21 13:03:41 +00:00
|
|
|
logLevel := logFactory.Level()
|
|
|
|
if logLevel == log.LevelTrace {
|
|
|
|
logLevel = log.LevelDebug
|
2022-09-08 10:04:06 +00:00
|
|
|
} else if logLevel < log.LevelError {
|
2022-07-21 13:03:41 +00:00
|
|
|
logLevel = log.LevelError
|
|
|
|
}
|
2022-07-19 14:16:49 +00:00
|
|
|
render.JSON(w, r, &configSchema{
|
2022-09-10 06:09:47 +00:00
|
|
|
Mode: server.mode,
|
2022-07-21 13:03:41 +00:00
|
|
|
BindAddress: "*",
|
|
|
|
LogLevel: log.FormatLevel(logLevel),
|
2022-07-19 14:16:49 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-10 06:09:47 +00:00
|
|
|
func patchConfigs(server *Server, logger log.Logger) func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
var newConfig configSchema
|
|
|
|
err := render.DecodeJSON(r.Body, &newConfig)
|
|
|
|
if err != nil {
|
|
|
|
render.Status(r, http.StatusBadRequest)
|
|
|
|
render.JSON(w, r, ErrBadRequest)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
if newConfig.Mode != "" {
|
|
|
|
mode := strings.ToLower(newConfig.Mode)
|
|
|
|
if server.mode != mode {
|
|
|
|
server.mode = mode
|
|
|
|
logger.Info("updated mode: ", mode)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
render.NoContent(w, r)
|
|
|
|
}
|
2022-07-19 14:16:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func updateConfigs(w http.ResponseWriter, r *http.Request) {
|
|
|
|
render.NoContent(w, r)
|
|
|
|
}
|