proxies.go 6.6 KB

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