proxies.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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/outbound"
  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, router))
  23. r.Route("/{name}", func(r chi.Router) {
  24. r.Use(parseProxyName, findProxyByName(router))
  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(router adapter.Router) 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 := router.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, router adapter.Router) 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(router.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. var defaultTag string
  92. if defaultOutbound, err := router.DefaultOutbound(N.NetworkTCP); err == nil {
  93. defaultTag = defaultOutbound.Tag()
  94. } else {
  95. defaultTag = allProxies[0]
  96. }
  97. sort.SliceStable(allProxies, func(i, j int) bool {
  98. return allProxies[i] == defaultTag
  99. })
  100. // fix clash dashboard
  101. proxyMap.Put("GLOBAL", map[string]any{
  102. "type": "Fallback",
  103. "name": "GLOBAL",
  104. "udp": true,
  105. "history": []*urltest.History{},
  106. "all": allProxies,
  107. "now": defaultTag,
  108. })
  109. for i, detour := range outbounds {
  110. var tag string
  111. if detour.Tag() == "" {
  112. tag = F.ToString(i)
  113. } else {
  114. tag = detour.Tag()
  115. }
  116. proxyMap.Put(tag, proxyInfo(server, detour))
  117. }
  118. var responseMap badjson.JSONObject
  119. responseMap.Put("proxies", &proxyMap)
  120. response, err := responseMap.MarshalJSON()
  121. if err != nil {
  122. render.Status(r, http.StatusInternalServerError)
  123. render.JSON(w, r, newError(err.Error()))
  124. return
  125. }
  126. w.Write(response)
  127. }
  128. }
  129. func getProxy(server *Server) func(w http.ResponseWriter, r *http.Request) {
  130. return func(w http.ResponseWriter, r *http.Request) {
  131. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  132. response, err := proxyInfo(server, proxy).MarshalJSON()
  133. if err != nil {
  134. render.Status(r, http.StatusInternalServerError)
  135. render.JSON(w, r, newError(err.Error()))
  136. return
  137. }
  138. w.Write(response)
  139. }
  140. }
  141. type UpdateProxyRequest struct {
  142. Name string `json:"name"`
  143. }
  144. func updateProxy(w http.ResponseWriter, r *http.Request) {
  145. req := UpdateProxyRequest{}
  146. if err := render.DecodeJSON(r.Body, &req); err != nil {
  147. render.Status(r, http.StatusBadRequest)
  148. render.JSON(w, r, ErrBadRequest)
  149. return
  150. }
  151. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  152. selector, ok := proxy.(*outbound.Selector)
  153. if !ok {
  154. render.Status(r, http.StatusBadRequest)
  155. render.JSON(w, r, newError("Must be a Selector"))
  156. return
  157. }
  158. if !selector.SelectOutbound(req.Name) {
  159. render.Status(r, http.StatusBadRequest)
  160. render.JSON(w, r, newError("Selector update error: not found"))
  161. return
  162. }
  163. render.NoContent(w, r)
  164. }
  165. func getProxyDelay(server *Server) func(w http.ResponseWriter, r *http.Request) {
  166. return func(w http.ResponseWriter, r *http.Request) {
  167. query := r.URL.Query()
  168. url := query.Get("url")
  169. if strings.HasPrefix(url, "http://") {
  170. url = ""
  171. }
  172. timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
  173. if err != nil {
  174. render.Status(r, http.StatusBadRequest)
  175. render.JSON(w, r, ErrBadRequest)
  176. return
  177. }
  178. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  179. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
  180. defer cancel()
  181. delay, err := urltest.URLTest(ctx, url, proxy)
  182. defer func() {
  183. realTag := outbound.RealTag(proxy)
  184. if err != nil {
  185. server.urlTestHistory.DeleteURLTestHistory(realTag)
  186. } else {
  187. server.urlTestHistory.StoreURLTestHistory(realTag, &urltest.History{
  188. Time: time.Now(),
  189. Delay: delay,
  190. })
  191. }
  192. }()
  193. if ctx.Err() != nil {
  194. render.Status(r, http.StatusGatewayTimeout)
  195. render.JSON(w, r, ErrRequestTimeout)
  196. return
  197. }
  198. if err != nil || delay == 0 {
  199. render.Status(r, http.StatusServiceUnavailable)
  200. render.JSON(w, r, newError("An error occurred in the delay test"))
  201. return
  202. }
  203. render.JSON(w, r, render.M{
  204. "delay": delay,
  205. })
  206. }
  207. }