sing-box/experimental/clashapi/server.go

425 lines
11 KiB
Go
Raw Normal View History

2022-07-19 14:16:49 +00:00
package clashapi
import (
"bytes"
"context"
2022-07-20 01:41:44 +00:00
"errors"
2022-07-19 14:16:49 +00:00
"net"
"net/http"
2022-07-22 05:51:08 +00:00
"os"
"runtime"
2022-07-19 14:16:49 +00:00
"strings"
"syscall"
2022-07-19 14:16:49 +00:00
"time"
2024-08-23 05:38:38 +00:00
"github.com/sagernet/cors"
2022-07-19 14:16:49 +00:00
"github.com/sagernet/sing-box/adapter"
2022-07-28 08:36:31 +00:00
"github.com/sagernet/sing-box/common/urltest"
2022-07-19 14:16:49 +00:00
C "github.com/sagernet/sing-box/constant"
2022-09-26 11:37:06 +00:00
"github.com/sagernet/sing-box/experimental"
2022-07-22 01:29:13 +00:00
"github.com/sagernet/sing-box/experimental/clashapi/trafficontrol"
2022-07-19 14:16:49 +00:00
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
2022-08-22 10:53:47 +00:00
"github.com/sagernet/sing/common"
2022-07-19 14:16:49 +00:00
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/json"
2022-07-19 14:16:49 +00:00
N "github.com/sagernet/sing/common/network"
2023-07-02 08:45:30 +00:00
"github.com/sagernet/sing/service"
2023-04-21 09:29:00 +00:00
"github.com/sagernet/sing/service/filemanager"
2023-11-09 08:59:44 +00:00
"github.com/sagernet/ws"
"github.com/sagernet/ws/wsutil"
2022-07-19 14:16:49 +00:00
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
)
2022-09-26 11:37:06 +00:00
func init() {
2022-10-01 01:56:09 +00:00
experimental.RegisterClashServerConstructor(NewServer)
2022-09-26 11:37:06 +00:00
}
2022-07-19 23:12:40 +00:00
var _ adapter.ClashServer = (*Server)(nil)
2022-07-19 14:16:49 +00:00
type Server struct {
ctx context.Context
router adapter.Router
outboundManager adapter.OutboundManager
logger log.Logger
httpServer *http.Server
trafficManager *trafficontrol.Manager
urlTestHistory *urltest.HistoryStorage
mode string
modeList []string
modeUpdateHook chan<- struct{}
externalController bool
externalUI string
externalUIDownloadURL string
externalUIDownloadDetour string
2022-07-19 14:16:49 +00:00
}
func NewServer(ctx context.Context, logFactory log.ObservableFactory, options option.ClashAPIOptions) (adapter.ClashServer, error) {
2022-07-22 01:29:13 +00:00
trafficManager := trafficontrol.NewManager()
2022-07-19 14:16:49 +00:00
chiRouter := chi.NewRouter()
s := &Server{
ctx: ctx,
router: service.FromContext[adapter.Router](ctx),
outboundManager: service.FromContext[adapter.OutboundManager](ctx),
logger: logFactory.NewLogger("clash-api"),
2022-08-02 10:47:23 +00:00
httpServer: &http.Server{
2022-07-21 13:03:41 +00:00
Addr: options.ExternalController,
Handler: chiRouter,
},
trafficManager: trafficManager,
modeList: options.ModeList,
externalController: options.ExternalController != "",
externalUIDownloadURL: options.ExternalUIDownloadURL,
externalUIDownloadDetour: options.ExternalUIDownloadDetour,
2022-09-10 06:09:47 +00:00
}
s.urlTestHistory = service.PtrFromContext[urltest.HistoryStorage](ctx)
if s.urlTestHistory == nil {
s.urlTestHistory = urltest.NewHistoryStorage()
2023-07-02 08:45:30 +00:00
}
defaultMode := "Rule"
if options.DefaultMode != "" {
defaultMode = options.DefaultMode
}
if !common.Contains(s.modeList, defaultMode) {
s.modeList = append([]string{defaultMode}, s.modeList...)
2022-07-21 13:03:41 +00:00
}
s.mode = defaultMode
2023-11-28 04:00:28 +00:00
//goland:noinspection GoDeprecation
//nolint:staticcheck
if options.StoreMode || options.StoreSelected || options.StoreFakeIP || options.CacheFile != "" || options.CacheID != "" {
return nil, E.New("cache_file and related fields in Clash API is deprecated in sing-box 1.8.0, use experimental.cache_file instead.")
2022-09-10 06:40:16 +00:00
}
2024-08-23 05:38:38 +00:00
allowedOrigins := options.AccessControlAllowOrigin
if len(allowedOrigins) == 0 {
allowedOrigins = []string{"*"}
}
2022-07-19 14:16:49 +00:00
cors := cors.New(cors.Options{
2024-08-23 05:38:38 +00:00
AllowedOrigins: allowedOrigins,
AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
AllowedHeaders: []string{"Content-Type", "Authorization"},
AllowPrivateNetwork: options.AccessControlAllowPrivateNetwork,
MaxAge: 300,
2022-07-19 14:16:49 +00:00
})
chiRouter.Use(cors.Handler)
chiRouter.Group(func(r chi.Router) {
r.Use(authentication(options.Secret))
2022-09-13 09:29:57 +00:00
r.Get("/", hello(options.ExternalUI != ""))
2022-07-19 14:16:49 +00:00
r.Get("/logs", getLogs(logFactory))
r.Get("/traffic", traffic(trafficManager))
r.Get("/version", version)
r.Mount("/configs", configRouter(s, logFactory))
r.Mount("/proxies", proxyRouter(s, s.router))
r.Mount("/rules", ruleRouter(s.router))
r.Mount("/connections", connectionRouter(s.router, trafficManager))
2022-07-22 01:29:13 +00:00
r.Mount("/providers/proxies", proxyProviderRouter())
2022-07-19 14:16:49 +00:00
r.Mount("/providers/rules", ruleProviderRouter())
r.Mount("/script", scriptRouter())
r.Mount("/profile", profileRouter())
2023-11-28 04:00:28 +00:00
r.Mount("/cache", cacheRouter(ctx))
r.Mount("/dns", dnsRouter(s.router))
2023-04-11 08:43:45 +00:00
s.setupMetaAPI(r)
2022-07-19 14:16:49 +00:00
})
2022-07-19 23:36:06 +00:00
if options.ExternalUI != "" {
s.externalUI = filemanager.BasePath(ctx, os.ExpandEnv(options.ExternalUI))
2022-07-19 23:36:06 +00:00
chiRouter.Group(func(r chi.Router) {
fs := http.StripPrefix("/ui", http.FileServer(http.Dir(s.externalUI)))
2022-07-19 23:36:06 +00:00
r.Get("/ui", http.RedirectHandler("/ui/", http.StatusTemporaryRedirect).ServeHTTP)
r.Get("/ui/*", func(w http.ResponseWriter, r *http.Request) {
fs.ServeHTTP(w, r)
})
})
}
return s, nil
2022-07-19 14:16:49 +00:00
}
2024-11-10 08:46:59 +00:00
func (s *Server) Name() string {
return "clash server"
2023-03-18 12:26:58 +00:00
}
2024-11-10 08:46:59 +00:00
func (s *Server) Start(stage adapter.StartStage) error {
switch stage {
case adapter.StartStateStart:
cacheFile := service.FromContext[adapter.CacheFile](s.ctx)
if cacheFile != nil {
mode := cacheFile.LoadMode()
if common.Any(s.modeList, func(it string) bool {
return strings.EqualFold(it, mode)
}) {
s.mode = mode
}
2022-07-19 14:16:49 +00:00
}
2024-11-10 08:46:59 +00:00
case adapter.StartStateStarted:
if s.externalController {
s.checkAndDownloadExternalUI()
var (
listener net.Listener
err error
)
for i := 0; i < 3; i++ {
listener, err = net.Listen("tcp", s.httpServer.Addr)
if runtime.GOOS == "android" && errors.Is(err, syscall.EADDRINUSE) {
time.Sleep(100 * time.Millisecond)
continue
}
break
}
if err != nil {
return E.Cause(err, "external controller listen error")
}
2024-11-10 08:46:59 +00:00
s.logger.Info("restful api listening at ", listener.Addr())
go func() {
err = s.httpServer.Serve(listener)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
s.logger.Error("external controller serve error: ", err)
}
}()
}
}
2024-11-10 08:46:59 +00:00
2022-07-19 14:16:49 +00:00
return nil
}
func (s *Server) Close() error {
2022-08-22 08:33:33 +00:00
return common.Close(
common.PtrOrNil(s.httpServer),
s.trafficManager,
s.urlTestHistory,
2022-08-22 08:33:33 +00:00
)
2022-07-19 14:16:49 +00:00
}
2022-09-10 06:40:16 +00:00
func (s *Server) Mode() string {
return s.mode
}
func (s *Server) ModeList() []string {
return s.modeList
}
func (s *Server) SetModeUpdateHook(hook chan<- struct{}) {
s.modeUpdateHook = hook
}
func (s *Server) SetMode(newMode string) {
if !common.Contains(s.modeList, newMode) {
newMode = common.Find(s.modeList, func(it string) bool {
return strings.EqualFold(it, newMode)
})
}
if !common.Contains(s.modeList, newMode) {
return
}
if newMode == s.mode {
return
}
s.mode = newMode
if s.modeUpdateHook != nil {
select {
case s.modeUpdateHook <- struct{}{}:
default:
}
}
s.router.ClearDNSCache()
2023-11-28 04:00:28 +00:00
cacheFile := service.FromContext[adapter.CacheFile](s.ctx)
if cacheFile != nil {
err := cacheFile.StoreMode(newMode)
if err != nil {
s.logger.Error(E.Cause(err, "save mode"))
}
}
s.logger.Info("updated mode: ", newMode)
}
2022-09-15 07:22:08 +00:00
func (s *Server) HistoryStorage() *urltest.HistoryStorage {
return s.urlTestHistory
}
2023-07-16 06:08:45 +00:00
func (s *Server) TrafficManager() *trafficontrol.Manager {
return s.trafficManager
}
2024-11-10 08:46:59 +00:00
func (s *Server) RoutedConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) net.Conn {
return trafficontrol.NewTCPTracker(conn, s.trafficManager, metadata, s.outboundManager, matchedRule, matchOutbound)
2022-07-19 14:16:49 +00:00
}
2024-11-10 08:46:59 +00:00
func (s *Server) RoutedPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext, matchedRule adapter.Rule, matchOutbound adapter.Outbound) N.PacketConn {
return trafficontrol.NewUDPTracker(conn, s.trafficManager, metadata, s.outboundManager, matchedRule, matchOutbound)
2022-07-19 14:16:49 +00:00
}
func authentication(serverSecret string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
if serverSecret == "" {
next.ServeHTTP(w, r)
return
}
// Browser websocket not support custom header
2023-11-09 08:59:44 +00:00
if r.Header.Get("Upgrade") == "websocket" && r.URL.Query().Get("token") != "" {
2022-07-19 14:16:49 +00:00
token := r.URL.Query().Get("token")
if token != serverSecret {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, ErrUnauthorized)
return
}
next.ServeHTTP(w, r)
return
}
header := r.Header.Get("Authorization")
bearer, token, found := strings.Cut(header, " ")
hasInvalidHeader := bearer != "Bearer"
hasInvalidSecret := !found || token != serverSecret
if hasInvalidHeader || hasInvalidSecret {
render.Status(r, http.StatusUnauthorized)
render.JSON(w, r, ErrUnauthorized)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}
2022-09-13 09:29:57 +00:00
func hello(redirect bool) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
2024-08-23 05:38:27 +00:00
contentType := r.Header.Get("Content-Type")
if !redirect || contentType == "application/json" {
2022-09-13 09:29:57 +00:00
render.JSON(w, r, render.M{"hello": "clash"})
2024-08-23 05:38:27 +00:00
} else {
http.Redirect(w, r, "/ui/", http.StatusTemporaryRedirect)
2022-09-13 09:29:57 +00:00
}
}
2022-07-19 14:16:49 +00:00
}
type Traffic struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
}
2022-07-22 01:29:13 +00:00
func traffic(trafficManager *trafficontrol.Manager) func(w http.ResponseWriter, r *http.Request) {
2022-07-19 14:16:49 +00:00
return func(w http.ResponseWriter, r *http.Request) {
2023-11-09 08:59:44 +00:00
var conn net.Conn
if r.Header.Get("Upgrade") == "websocket" {
2022-07-19 14:16:49 +00:00
var err error
2023-11-09 08:59:44 +00:00
conn, _, _, err = ws.UpgradeHTTP(r, w)
2022-07-19 14:16:49 +00:00
if err != nil {
return
}
2023-11-09 08:59:44 +00:00
defer conn.Close()
2022-07-19 14:16:49 +00:00
}
2023-11-09 08:59:44 +00:00
if conn == nil {
2022-07-19 14:16:49 +00:00
w.Header().Set("Content-Type", "application/json")
render.Status(r, http.StatusOK)
}
tick := time.NewTicker(time.Second)
defer tick.Stop()
buf := &bytes.Buffer{}
var err error
for range tick.C {
buf.Reset()
up, down := trafficManager.Now()
if err := json.NewEncoder(buf).Encode(Traffic{
Up: up,
Down: down,
}); err != nil {
break
}
2023-11-09 08:59:44 +00:00
if conn == nil {
2022-07-19 14:16:49 +00:00
_, err = w.Write(buf.Bytes())
w.(http.Flusher).Flush()
} else {
2023-11-09 08:59:44 +00:00
err = wsutil.WriteServerText(conn, buf.Bytes())
2022-07-19 14:16:49 +00:00
}
if err != nil {
break
}
}
}
}
type Log struct {
Type string `json:"type"`
Payload string `json:"payload"`
}
func getLogs(logFactory log.ObservableFactory) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
levelText := r.URL.Query().Get("level")
if levelText == "" {
levelText = "info"
}
level, ok := log.ParseLevel(levelText)
if ok != nil {
render.Status(r, http.StatusBadRequest)
render.JSON(w, r, ErrBadRequest)
return
}
2022-07-20 01:41:44 +00:00
subscription, done, err := logFactory.Subscribe()
if err != nil {
render.Status(r, http.StatusNoContent)
return
}
defer logFactory.UnSubscribe(subscription)
2023-11-09 08:59:44 +00:00
var conn net.Conn
if r.Header.Get("Upgrade") == "websocket" {
conn, _, _, err = ws.UpgradeHTTP(r, w)
2022-07-19 14:16:49 +00:00
if err != nil {
return
}
2023-11-09 08:59:44 +00:00
defer conn.Close()
2022-07-19 14:16:49 +00:00
}
2023-11-09 08:59:44 +00:00
if conn == nil {
2022-07-19 14:16:49 +00:00
w.Header().Set("Content-Type", "application/json")
render.Status(r, http.StatusOK)
}
buf := &bytes.Buffer{}
var logEntry log.Entry
for {
select {
case <-done:
return
case logEntry = <-subscription:
}
if logEntry.Level > level {
continue
}
buf.Reset()
err = json.NewEncoder(buf).Encode(Log{
Type: log.FormatLevel(logEntry.Level),
Payload: logEntry.Message,
})
if err != nil {
break
}
2023-11-09 08:59:44 +00:00
if conn == nil {
2022-07-19 14:16:49 +00:00
_, err = w.Write(buf.Bytes())
w.(http.Flusher).Flush()
} else {
2023-11-09 08:59:44 +00:00
err = wsutil.WriteServerText(conn, buf.Bytes())
2022-07-19 14:16:49 +00:00
}
if err != nil {
break
}
}
}
}
func version(w http.ResponseWriter, r *http.Request) {
2023-04-11 08:43:45 +00:00
render.JSON(w, r, render.M{"version": "sing-box " + C.Version, "premium": true, "meta": true})
2022-07-19 14:16:49 +00:00
}