proxies.go 6.0 KB

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