server.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. package route
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/subtle"
  6. "crypto/tls"
  7. "encoding/json"
  8. "net"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "runtime/debug"
  13. "strings"
  14. "syscall"
  15. "time"
  16. "github.com/metacubex/mihomo/adapter/inbound"
  17. CN "github.com/metacubex/mihomo/common/net"
  18. "github.com/metacubex/mihomo/common/utils"
  19. C "github.com/metacubex/mihomo/constant"
  20. "github.com/metacubex/mihomo/log"
  21. "github.com/metacubex/mihomo/tunnel/statistic"
  22. "github.com/go-chi/chi/v5"
  23. "github.com/go-chi/chi/v5/middleware"
  24. "github.com/go-chi/cors"
  25. "github.com/go-chi/render"
  26. "github.com/gobwas/ws"
  27. "github.com/gobwas/ws/wsutil"
  28. )
  29. var (
  30. serverSecret = ""
  31. serverAddr = ""
  32. uiPath = ""
  33. server *http.Server
  34. )
  35. type Traffic struct {
  36. Up int64 `json:"up"`
  37. Down int64 `json:"down"`
  38. }
  39. type Memory struct {
  40. Inuse uint64 `json:"inuse"`
  41. OSLimit uint64 `json:"oslimit"` // maybe we need it in the future
  42. }
  43. func SetUIPath(path string) {
  44. uiPath = C.Path.Resolve(path)
  45. }
  46. func router(isDebug bool, withAuth bool, dohServer string) *chi.Mux {
  47. r := chi.NewRouter()
  48. corsM := cors.New(cors.Options{
  49. AllowedOrigins: []string{"*"},
  50. AllowedMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
  51. AllowedHeaders: []string{"Content-Type", "Authorization"},
  52. MaxAge: 300,
  53. })
  54. r.Use(setPrivateNetworkAccess)
  55. r.Use(corsM.Handler)
  56. if isDebug {
  57. r.Mount("/debug", func() http.Handler {
  58. r := chi.NewRouter()
  59. r.Put("/gc", func(w http.ResponseWriter, r *http.Request) {
  60. debug.FreeOSMemory()
  61. })
  62. handler := middleware.Profiler
  63. r.Mount("/", handler())
  64. return r
  65. }())
  66. }
  67. r.Group(func(r chi.Router) {
  68. if withAuth {
  69. r.Use(authentication)
  70. }
  71. r.Get("/", hello)
  72. r.Get("/logs", getLogs)
  73. r.Get("/traffic", traffic)
  74. r.Get("/memory", memory)
  75. r.Get("/version", version)
  76. r.Mount("/configs", configRouter())
  77. r.Mount("/proxies", proxyRouter())
  78. r.Mount("/group", GroupRouter())
  79. r.Mount("/rules", ruleRouter())
  80. r.Mount("/connections", connectionRouter())
  81. r.Mount("/providers/proxies", proxyProviderRouter())
  82. r.Mount("/providers/rules", ruleProviderRouter())
  83. r.Mount("/cache", cacheRouter())
  84. r.Mount("/dns", dnsRouter())
  85. r.Mount("/restart", restartRouter())
  86. r.Mount("/upgrade", upgradeRouter())
  87. addExternalRouters(r)
  88. })
  89. if uiPath != "" {
  90. r.Group(func(r chi.Router) {
  91. fs := http.StripPrefix("/ui", http.FileServer(http.Dir(uiPath)))
  92. r.Get("/ui", http.RedirectHandler("/ui/", http.StatusTemporaryRedirect).ServeHTTP)
  93. r.Get("/ui/*", func(w http.ResponseWriter, r *http.Request) {
  94. fs.ServeHTTP(w, r)
  95. })
  96. })
  97. }
  98. if len(dohServer) > 0 && dohServer[0] == '/' {
  99. r.Mount(dohServer, dohRouter())
  100. }
  101. return r
  102. }
  103. func ReStartServer(addr string) {
  104. if addr == "" {
  105. StopServer()
  106. return
  107. }
  108. if server != nil && server.Addr == addr {
  109. return
  110. }
  111. StopServer()
  112. server = &http.Server{
  113. Addr: addr,
  114. Handler: router(false, false, ""),
  115. }
  116. go func() {
  117. if err := server.ListenAndServe(); err != nil {
  118. log.Errorln("External controller listen error: %s", err)
  119. }
  120. }()
  121. }
  122. func StopServer() {
  123. if server == nil {
  124. return
  125. }
  126. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  127. defer cancel()
  128. if err := server.Shutdown(ctx); err != nil {
  129. log.Errorln("Shutdown external controller:", err)
  130. }
  131. server = nil
  132. }
  133. func Start(addr string, tlsAddr string, secret string,
  134. certificate, privateKey string, dohServer string, isDebug bool) {
  135. if serverAddr != "" {
  136. return
  137. }
  138. serverAddr = addr
  139. serverSecret = secret
  140. if len(tlsAddr) > 0 {
  141. go func() {
  142. c, err := CN.ParseCert(certificate, privateKey, C.Path)
  143. if err != nil {
  144. log.Errorln("External controller tls listen error: %s", err)
  145. return
  146. }
  147. l, err := inbound.Listen("tcp", tlsAddr)
  148. if err != nil {
  149. log.Errorln("External controller tls listen error: %s", err)
  150. return
  151. }
  152. serverAddr = l.Addr().String()
  153. log.Infoln("RESTful API tls listening at: %s", serverAddr)
  154. tlsServe := &http.Server{
  155. Handler: router(isDebug, true, dohServer),
  156. TLSConfig: &tls.Config{
  157. Certificates: []tls.Certificate{c},
  158. },
  159. }
  160. if err = tlsServe.ServeTLS(l, "", ""); err != nil {
  161. log.Errorln("External controller tls serve error: %s", err)
  162. }
  163. }()
  164. }
  165. l, err := inbound.Listen("tcp", addr)
  166. if err != nil {
  167. log.Errorln("External controller listen error: %s", err)
  168. return
  169. }
  170. serverAddr = l.Addr().String()
  171. log.Infoln("RESTful API listening at: %s", serverAddr)
  172. if err = http.Serve(l, router(isDebug, true, dohServer)); err != nil {
  173. log.Errorln("External controller serve error: %s", err)
  174. }
  175. }
  176. func StartUnix(addr string, dohServer string, isDebug bool) {
  177. addr = C.Path.Resolve(addr)
  178. dir := filepath.Dir(addr)
  179. if _, err := os.Stat(dir); os.IsNotExist(err) {
  180. if err := os.MkdirAll(dir, 0o755); err != nil {
  181. log.Errorln("External controller unix listen error: %s", err)
  182. return
  183. }
  184. }
  185. // https://devblogs.microsoft.com/commandline/af_unix-comes-to-windows/
  186. //
  187. // Note: As mentioned above in the ‘security’ section, when a socket binds a socket to a valid pathname address,
  188. // a socket file is created within the filesystem. On Linux, the application is expected to unlink
  189. // (see the notes section in the man page for AF_UNIX) before any other socket can be bound to the same address.
  190. // The same applies to Windows unix sockets, except that, DeleteFile (or any other file delete API)
  191. // should be used to delete the socket file prior to calling bind with the same path.
  192. _ = syscall.Unlink(addr)
  193. l, err := inbound.Listen("unix", addr)
  194. if err != nil {
  195. log.Errorln("External controller unix listen error: %s", err)
  196. return
  197. }
  198. serverAddr = l.Addr().String()
  199. log.Infoln("RESTful API unix listening at: %s", serverAddr)
  200. if err = http.Serve(l, router(isDebug, false, dohServer)); err != nil {
  201. log.Errorln("External controller unix serve error: %s", err)
  202. }
  203. }
  204. func setPrivateNetworkAccess(next http.Handler) http.Handler {
  205. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  206. if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
  207. w.Header().Add("Access-Control-Allow-Private-Network", "true")
  208. }
  209. next.ServeHTTP(w, r)
  210. })
  211. }
  212. func safeEuqal(a, b string) bool {
  213. aBuf := utils.ImmutableBytesFromString(a)
  214. bBuf := utils.ImmutableBytesFromString(b)
  215. return subtle.ConstantTimeCompare(aBuf, bBuf) == 1
  216. }
  217. func authentication(next http.Handler) http.Handler {
  218. fn := func(w http.ResponseWriter, r *http.Request) {
  219. if serverSecret == "" {
  220. next.ServeHTTP(w, r)
  221. return
  222. }
  223. // Browser websocket not support custom header
  224. if r.Header.Get("Upgrade") == "websocket" && r.URL.Query().Get("token") != "" {
  225. token := r.URL.Query().Get("token")
  226. if !safeEuqal(token, serverSecret) {
  227. render.Status(r, http.StatusUnauthorized)
  228. render.JSON(w, r, ErrUnauthorized)
  229. return
  230. }
  231. next.ServeHTTP(w, r)
  232. return
  233. }
  234. header := r.Header.Get("Authorization")
  235. bearer, token, found := strings.Cut(header, " ")
  236. hasInvalidHeader := bearer != "Bearer"
  237. hasInvalidSecret := !found || !safeEuqal(token, serverSecret)
  238. if hasInvalidHeader || hasInvalidSecret {
  239. render.Status(r, http.StatusUnauthorized)
  240. render.JSON(w, r, ErrUnauthorized)
  241. return
  242. }
  243. next.ServeHTTP(w, r)
  244. }
  245. return http.HandlerFunc(fn)
  246. }
  247. func hello(w http.ResponseWriter, r *http.Request) {
  248. render.JSON(w, r, render.M{"hello": "mihomo"})
  249. }
  250. func traffic(w http.ResponseWriter, r *http.Request) {
  251. var wsConn net.Conn
  252. if r.Header.Get("Upgrade") == "websocket" {
  253. var err error
  254. wsConn, _, _, err = ws.UpgradeHTTP(r, w)
  255. if err != nil {
  256. return
  257. }
  258. }
  259. if wsConn == nil {
  260. w.Header().Set("Content-Type", "application/json")
  261. render.Status(r, http.StatusOK)
  262. }
  263. tick := time.NewTicker(time.Second)
  264. defer tick.Stop()
  265. t := statistic.DefaultManager
  266. buf := &bytes.Buffer{}
  267. var err error
  268. for range tick.C {
  269. buf.Reset()
  270. up, down := t.Now()
  271. if err := json.NewEncoder(buf).Encode(Traffic{
  272. Up: up,
  273. Down: down,
  274. }); err != nil {
  275. break
  276. }
  277. if wsConn == nil {
  278. _, err = w.Write(buf.Bytes())
  279. w.(http.Flusher).Flush()
  280. } else {
  281. err = wsutil.WriteMessage(wsConn, ws.StateServerSide, ws.OpText, buf.Bytes())
  282. }
  283. if err != nil {
  284. break
  285. }
  286. }
  287. }
  288. func memory(w http.ResponseWriter, r *http.Request) {
  289. var wsConn net.Conn
  290. if r.Header.Get("Upgrade") == "websocket" {
  291. var err error
  292. wsConn, _, _, err = ws.UpgradeHTTP(r, w)
  293. if err != nil {
  294. return
  295. }
  296. }
  297. if wsConn == nil {
  298. w.Header().Set("Content-Type", "application/json")
  299. render.Status(r, http.StatusOK)
  300. }
  301. tick := time.NewTicker(time.Second)
  302. defer tick.Stop()
  303. t := statistic.DefaultManager
  304. buf := &bytes.Buffer{}
  305. var err error
  306. first := true
  307. for range tick.C {
  308. buf.Reset()
  309. inuse := t.Memory()
  310. // make chat.js begin with zero
  311. // this is shit var,but we need output 0 for first time
  312. if first {
  313. inuse = 0
  314. first = false
  315. }
  316. if err := json.NewEncoder(buf).Encode(Memory{
  317. Inuse: inuse,
  318. OSLimit: 0,
  319. }); err != nil {
  320. break
  321. }
  322. if wsConn == nil {
  323. _, err = w.Write(buf.Bytes())
  324. w.(http.Flusher).Flush()
  325. } else {
  326. err = wsutil.WriteMessage(wsConn, ws.StateServerSide, ws.OpText, buf.Bytes())
  327. }
  328. if err != nil {
  329. break
  330. }
  331. }
  332. }
  333. type Log struct {
  334. Type string `json:"type"`
  335. Payload string `json:"payload"`
  336. }
  337. type LogStructuredField struct {
  338. Key string `json:"key"`
  339. Value string `json:"value"`
  340. }
  341. type LogStructured struct {
  342. Time string `json:"time"`
  343. Level string `json:"level"`
  344. Message string `json:"message"`
  345. Fields []LogStructuredField `json:"fields"`
  346. }
  347. func getLogs(w http.ResponseWriter, r *http.Request) {
  348. levelText := r.URL.Query().Get("level")
  349. if levelText == "" {
  350. levelText = "info"
  351. }
  352. formatText := r.URL.Query().Get("format")
  353. isStructured := false
  354. if formatText == "structured" {
  355. isStructured = true
  356. }
  357. level, ok := log.LogLevelMapping[levelText]
  358. if !ok {
  359. render.Status(r, http.StatusBadRequest)
  360. render.JSON(w, r, ErrBadRequest)
  361. return
  362. }
  363. var wsConn net.Conn
  364. if r.Header.Get("Upgrade") == "websocket" {
  365. var err error
  366. wsConn, _, _, err = ws.UpgradeHTTP(r, w)
  367. if err != nil {
  368. return
  369. }
  370. }
  371. if wsConn == nil {
  372. w.Header().Set("Content-Type", "application/json")
  373. render.Status(r, http.StatusOK)
  374. }
  375. ch := make(chan log.Event, 1024)
  376. sub := log.Subscribe()
  377. defer log.UnSubscribe(sub)
  378. buf := &bytes.Buffer{}
  379. go func() {
  380. for logM := range sub {
  381. select {
  382. case ch <- logM:
  383. default:
  384. }
  385. }
  386. close(ch)
  387. }()
  388. for logM := range ch {
  389. if logM.LogLevel < level {
  390. continue
  391. }
  392. buf.Reset()
  393. if !isStructured {
  394. if err := json.NewEncoder(buf).Encode(Log{
  395. Type: logM.Type(),
  396. Payload: logM.Payload,
  397. }); err != nil {
  398. break
  399. }
  400. } else {
  401. newLevel := logM.Type()
  402. if newLevel == "warning" {
  403. newLevel = "warn"
  404. }
  405. if err := json.NewEncoder(buf).Encode(LogStructured{
  406. Time: time.Now().Format(time.TimeOnly),
  407. Level: newLevel,
  408. Message: logM.Payload,
  409. Fields: []LogStructuredField{},
  410. }); err != nil {
  411. break
  412. }
  413. }
  414. var err error
  415. if wsConn == nil {
  416. _, err = w.Write(buf.Bytes())
  417. w.(http.Flusher).Flush()
  418. } else {
  419. err = wsutil.WriteMessage(wsConn, ws.StateServerSide, ws.OpText, buf.Bytes())
  420. }
  421. if err != nil {
  422. break
  423. }
  424. }
  425. }
  426. func version(w http.ResponseWriter, r *http.Request) {
  427. render.JSON(w, r, render.M{"meta": C.Meta, "version": C.Version})
  428. }