proxies.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. package clashapi
  2. import (
  3. "context"
  4. "fmt"
  5. "net/http"
  6. "sort"
  7. "strconv"
  8. "time"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/common/badjson"
  11. "github.com/sagernet/sing-box/common/urltest"
  12. C "github.com/sagernet/sing-box/constant"
  13. "github.com/sagernet/sing-box/outbound"
  14. "github.com/sagernet/sing/common"
  15. F "github.com/sagernet/sing/common/format"
  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. var isGroup bool
  57. switch detour.Type() {
  58. case C.TypeDirect:
  59. clashType = "Direct"
  60. case C.TypeBlock:
  61. clashType = "Reject"
  62. case C.TypeSocks:
  63. clashType = "Socks"
  64. case C.TypeHTTP:
  65. clashType = "Http"
  66. case C.TypeShadowsocks:
  67. clashType = "Shadowsocks"
  68. case C.TypeVMess:
  69. clashType = "Vmess"
  70. case C.TypeSelector:
  71. clashType = "Selector"
  72. isGroup = true
  73. default:
  74. clashType = "Unknown"
  75. }
  76. info.Put("type", clashType)
  77. info.Put("name", detour.Tag())
  78. info.Put("udp", common.Contains(detour.Network(), N.NetworkUDP))
  79. delayHistory := server.urlTestHistory.LoadURLTestHistory(adapter.OutboundTag(detour))
  80. if delayHistory != nil {
  81. info.Put("history", []*urltest.History{delayHistory})
  82. } else {
  83. info.Put("history", []*urltest.History{})
  84. }
  85. if isGroup {
  86. selector := detour.(adapter.OutboundGroup)
  87. info.Put("now", selector.Now())
  88. info.Put("all", selector.All())
  89. }
  90. return &info
  91. }
  92. func getProxies(server *Server, router adapter.Router) func(w http.ResponseWriter, r *http.Request) {
  93. return func(w http.ResponseWriter, r *http.Request) {
  94. var proxyMap badjson.JSONObject
  95. outbounds := common.Filter(router.Outbounds(), func(detour adapter.Outbound) bool {
  96. return detour.Tag() != ""
  97. })
  98. allProxies := make([]string, 0, len(outbounds))
  99. for _, detour := range outbounds {
  100. switch detour.Type() {
  101. case C.TypeDirect, C.TypeBlock, C.TypeDNS:
  102. continue
  103. }
  104. allProxies = append(allProxies, detour.Tag())
  105. }
  106. defaultTag := router.DefaultOutbound(N.NetworkTCP).Tag()
  107. if defaultTag == "" {
  108. defaultTag = allProxies[0]
  109. }
  110. sort.Slice(allProxies, func(i, j int) bool {
  111. return allProxies[i] == defaultTag
  112. })
  113. // fix clash dashboard
  114. proxyMap.Put("GLOBAL", map[string]any{
  115. "type": "Fallback",
  116. "name": "GLOBAL",
  117. "udp": true,
  118. "history": []*urltest.History{},
  119. "all": allProxies,
  120. "now": defaultTag,
  121. })
  122. for i, detour := range outbounds {
  123. var tag string
  124. if detour.Tag() == "" {
  125. tag = F.ToString(i)
  126. } else {
  127. tag = detour.Tag()
  128. }
  129. proxyMap.Put(tag, proxyInfo(server, detour))
  130. }
  131. var responseMap badjson.JSONObject
  132. responseMap.Put("proxies", &proxyMap)
  133. response, err := responseMap.MarshalJSON()
  134. if err != nil {
  135. render.Status(r, http.StatusInternalServerError)
  136. render.JSON(w, r, newError(err.Error()))
  137. return
  138. }
  139. w.Write(response)
  140. }
  141. }
  142. func getProxy(server *Server) func(w http.ResponseWriter, r *http.Request) {
  143. return func(w http.ResponseWriter, r *http.Request) {
  144. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  145. response, err := proxyInfo(server, proxy).MarshalJSON()
  146. if err != nil {
  147. render.Status(r, http.StatusInternalServerError)
  148. render.JSON(w, r, newError(err.Error()))
  149. return
  150. }
  151. w.Write(response)
  152. }
  153. }
  154. type UpdateProxyRequest struct {
  155. Name string `json:"name"`
  156. }
  157. func updateProxy(w http.ResponseWriter, r *http.Request) {
  158. req := UpdateProxyRequest{}
  159. if err := render.DecodeJSON(r.Body, &req); err != nil {
  160. render.Status(r, http.StatusBadRequest)
  161. render.JSON(w, r, ErrBadRequest)
  162. return
  163. }
  164. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  165. selector, ok := proxy.(*outbound.Selector)
  166. if !ok {
  167. render.Status(r, http.StatusBadRequest)
  168. render.JSON(w, r, newError("Must be a Selector"))
  169. return
  170. }
  171. if !selector.SelectOutbound(req.Name) {
  172. render.Status(r, http.StatusBadRequest)
  173. render.JSON(w, r, newError(fmt.Sprintf("Selector update error: not found")))
  174. return
  175. }
  176. render.NoContent(w, r)
  177. }
  178. func getProxyDelay(server *Server) func(w http.ResponseWriter, r *http.Request) {
  179. return func(w http.ResponseWriter, r *http.Request) {
  180. query := r.URL.Query()
  181. url := query.Get("url")
  182. timeout, err := strconv.ParseInt(query.Get("timeout"), 10, 16)
  183. if err != nil {
  184. render.Status(r, http.StatusBadRequest)
  185. render.JSON(w, r, ErrBadRequest)
  186. return
  187. }
  188. proxy := r.Context().Value(CtxKeyProxy).(adapter.Outbound)
  189. ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*time.Duration(timeout))
  190. defer cancel()
  191. delay, err := urltest.URLTest(ctx, url, proxy)
  192. defer func() {
  193. realTag := outbound.RealTag(proxy)
  194. if err != nil {
  195. server.urlTestHistory.DeleteURLTestHistory(realTag)
  196. } else {
  197. server.urlTestHistory.StoreURLTestHistory(realTag, &urltest.History{
  198. Time: time.Now(),
  199. Delay: delay,
  200. })
  201. }
  202. }()
  203. if ctx.Err() != nil {
  204. render.Status(r, http.StatusGatewayTimeout)
  205. render.JSON(w, r, ErrRequestTimeout)
  206. return
  207. }
  208. if err != nil || delay == 0 {
  209. render.Status(r, http.StatusServiceUnavailable)
  210. render.JSON(w, r, newError("An error occurred in the delay test"))
  211. return
  212. }
  213. render.JSON(w, r, render.M{
  214. "delay": delay,
  215. })
  216. }
  217. }