proxies.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package clashapi
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "github.com/sagernet/sing-box/adapter"
  11. "github.com/sagernet/sing-box/common/badjson"
  12. "github.com/sagernet/sing-box/common/urltest"
  13. C "github.com/sagernet/sing-box/constant"
  14. "github.com/sagernet/sing-box/outbound"
  15. "github.com/sagernet/sing/common"
  16. F "github.com/sagernet/sing/common/format"
  17. N "github.com/sagernet/sing/common/network"
  18. "github.com/go-chi/chi/v5"
  19. "github.com/go-chi/render"
  20. )
  21. func proxyRouter(server *Server, router adapter.Router) http.Handler {
  22. r := chi.NewRouter()
  23. r.Get("/", getProxies(server, router))
  24. r.Route("/{name}", func(r chi.Router) {
  25. r.Use(parseProxyName, findProxyByName(router))
  26. r.Get("/", getProxy(server))
  27. r.Get("/delay", getProxyDelay(server))
  28. r.Put("/", updateProxy)
  29. })
  30. return r
  31. }
  32. func parseProxyName(next http.Handler) http.Handler {
  33. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  34. name := getEscapeParam(r, "name")
  35. ctx := context.WithValue(r.Context(), CtxKeyProxyName, name)
  36. next.ServeHTTP(w, r.WithContext(ctx))
  37. })
  38. }
  39. func findProxyByName(router adapter.Router) func(next http.Handler) http.Handler {
  40. return func(next http.Handler) http.Handler {
  41. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  42. name := r.Context().Value(CtxKeyProxyName).(string)
  43. proxy, exist := router.Outbound(name)
  44. if !exist {
  45. render.Status(r, http.StatusNotFound)
  46. render.JSON(w, r, ErrNotFound)
  47. return
  48. }
  49. ctx := context.WithValue(r.Context(), CtxKeyProxy, proxy)
  50. next.ServeHTTP(w, r.WithContext(ctx))
  51. })
  52. }
  53. }
  54. func proxyInfo(server *Server, detour adapter.Outbound) *badjson.JSONObject {
  55. var info badjson.JSONObject
  56. var clashType string
  57. switch detour.Type() {
  58. case C.TypeBlock:
  59. clashType = "Reject"
  60. default:
  61. clashType = C.ProxyDisplayName(detour.Type())
  62. }
  63. info.Put("type", clashType)
  64. info.Put("name", detour.Tag())
  65. info.Put("udp", common.Contains(detour.Network(), N.NetworkUDP))
  66. delayHistory := server.urlTestHistory.LoadURLTestHistory(adapter.OutboundTag(detour))
  67. if delayHistory != nil {
  68. info.Put("history", []*urltest.History{delayHistory})
  69. } else {
  70. info.Put("history", []*urltest.History{})
  71. }
  72. if group, isGroup := detour.(adapter.OutboundGroup); isGroup {
  73. info.Put("now", group.Now())
  74. info.Put("all", group.All())
  75. }
  76. return &info
  77. }
  78. func getProxies(server *Server, router adapter.Router) func(w http.ResponseWriter, r *http.Request) {
  79. return func(w http.ResponseWriter, r *http.Request) {
  80. var proxyMap badjson.JSONObject
  81. outbounds := common.Filter(router.Outbounds(), func(detour adapter.Outbound) bool {
  82. return detour.Tag() != ""
  83. })
  84. allProxies := make([]string, 0, len(outbounds))
  85. for _, detour := range outbounds {
  86. switch detour.Type() {
  87. case C.TypeDirect, C.TypeBlock, C.TypeDNS:
  88. continue
  89. }
  90. allProxies = append(allProxies, detour.Tag())
  91. }
  92. defaultTag := router.DefaultOutbound(N.NetworkTCP).Tag()
  93. if defaultTag == "" {
  94. defaultTag = allProxies[0]
  95. }
  96. sort.SliceStable(allProxies, func(i, j int) bool {
  97. return allProxies[i] == defaultTag
  98. })
  99. // fix clash dashboard
  100. proxyMap.Put("GLOBAL", map[string]any{
  101. "type": "Fallback",
  102. "name": "GLOBAL",
  103. "udp": true,
  104. "history": []*urltest.History{},
  105. "all": allProxies,
  106. "now": defaultTag,
  107. })
  108. for i, detour := range outbounds {
  109. var tag string
  110. if detour.Tag() == "" {
  111. tag = F.ToString(i)
  112. } else {
  113. tag = detour.Tag()
  114. }
  115. proxyMap.Put(tag, proxyInfo(server, detour))
  116. }
  117. var responseMap badjson.JSONObject
  118. responseMap.Put("proxies", &proxyMap)
  119. response, err := responseMap.MarshalJSON()
  120. if err != nil {
  121. render.Status(r, http.StatusInternalServerError)
  122. render.JSON(w, r, newError(err.Error()))
  123. return
  124. }
  125. w.Write(response)
  126. }
  127. }
  128. func getProxy(server *Server) func(w http.ResponseWriter, r *http.Request) {
  129. return func(w http.ResponseWriter, r *http.Request) {
  130. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  131. response, err := proxyInfo(server, proxy).MarshalJSON()
  132. if err != nil {
  133. render.Status(r, http.StatusInternalServerError)
  134. render.JSON(w, r, newError(err.Error()))
  135. return
  136. }
  137. w.Write(response)
  138. }
  139. }
  140. type UpdateProxyRequest struct {
  141. Name string `json:"name"`
  142. }
  143. func updateProxy(w http.ResponseWriter, r *http.Request) {
  144. req := UpdateProxyRequest{}
  145. if err := render.DecodeJSON(r.Body, &req); err != nil {
  146. render.Status(r, http.StatusBadRequest)
  147. render.JSON(w, r, ErrBadRequest)
  148. return
  149. }
  150. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  151. selector, ok := proxy.(*outbound.Selector)
  152. if !ok {
  153. render.Status(r, http.StatusBadRequest)
  154. render.JSON(w, r, newError("Must be a Selector"))
  155. return
  156. }
  157. if !selector.SelectOutbound(req.Name) {
  158. render.Status(r, http.StatusBadRequest)
  159. render.JSON(w, r, newError(fmt.Sprintf("Selector update error: not found")))
  160. return
  161. }
  162. render.NoContent(w, r)
  163. }
  164. func getProxyDelay(server *Server) func(w http.ResponseWriter, r *http.Request) {
  165. return func(w http.ResponseWriter, r *http.Request) {
  166. query := r.URL.Query()
  167. url := query.Get("url")
  168. if strings.HasPrefix(url, "http://") {
  169. url = ""
  170. }
  171. timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
  172. if err != nil {
  173. render.Status(r, http.StatusBadRequest)
  174. render.JSON(w, r, ErrBadRequest)
  175. return
  176. }
  177. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  178. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
  179. defer cancel()
  180. delay, err := urltest.URLTest(ctx, url, proxy)
  181. defer func() {
  182. realTag := outbound.RealTag(proxy)
  183. if err != nil {
  184. server.urlTestHistory.DeleteURLTestHistory(realTag)
  185. } else {
  186. server.urlTestHistory.StoreURLTestHistory(realTag, &urltest.History{
  187. Time: time.Now(),
  188. Delay: delay,
  189. })
  190. }
  191. }()
  192. if ctx.Err() != nil {
  193. render.Status(r, http.StatusGatewayTimeout)
  194. render.JSON(w, r, ErrRequestTimeout)
  195. return
  196. }
  197. if err != nil || delay == 0 {
  198. render.Status(r, http.StatusServiceUnavailable)
  199. render.JSON(w, r, newError("An error occurred in the delay test"))
  200. return
  201. }
  202. render.JSON(w, r, render.M{
  203. "delay": delay,
  204. })
  205. }
  206. }