serve.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // SiYuan - Build Your Eternal Digital Garden
  2. // Copyright (c) 2020-present, b3log.org
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package server
  17. import (
  18. "fmt"
  19. "net"
  20. "net/http"
  21. "net/http/httputil"
  22. "net/http/pprof"
  23. "net/url"
  24. "os"
  25. "path"
  26. "path/filepath"
  27. "strings"
  28. "time"
  29. "github.com/88250/gulu"
  30. "github.com/gin-contrib/gzip"
  31. "github.com/gin-contrib/sessions"
  32. "github.com/gin-contrib/sessions/cookie"
  33. "github.com/gin-gonic/gin"
  34. "github.com/mssola/user_agent"
  35. "github.com/olahol/melody"
  36. "github.com/siyuan-note/logging"
  37. "github.com/siyuan-note/siyuan/kernel/api"
  38. "github.com/siyuan-note/siyuan/kernel/cmd"
  39. "github.com/siyuan-note/siyuan/kernel/model"
  40. "github.com/siyuan-note/siyuan/kernel/util"
  41. )
  42. var cookieStore = cookie.NewStore([]byte("ATN51UlxVq1Gcvdf"))
  43. func Serve(fastMode bool) {
  44. gin.SetMode(gin.ReleaseMode)
  45. ginServer := gin.New()
  46. ginServer.MaxMultipartMemory = 1024 * 1024 * 32 // 插入较大的资源文件时内存占用较大 https://github.com/siyuan-note/siyuan/issues/5023
  47. ginServer.Use(gin.Recovery())
  48. ginServer.Use(corsMiddleware()) // 后端服务支持 CORS 预检请求验证 https://github.com/siyuan-note/siyuan/pull/5593
  49. ginServer.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{".pdf", ".mp3", ".wav", ".ogg", ".mov", ".weba", ".mkv", ".mp4", ".webm"})))
  50. cookieStore.Options(sessions.Options{
  51. Path: "/",
  52. Secure: util.SSL,
  53. //MaxAge: 60 * 60 * 24 * 7, // 默认是 Session
  54. HttpOnly: true,
  55. })
  56. ginServer.Use(sessions.Sessions("siyuan", cookieStore))
  57. if "dev" == util.Mode {
  58. serveDebug(ginServer)
  59. }
  60. serveAssets(ginServer)
  61. serveAppearance(ginServer)
  62. serveWebSocket(ginServer)
  63. serveExport(ginServer)
  64. serveWidgets(ginServer)
  65. serveEmojis(ginServer)
  66. serveTemplates(ginServer)
  67. api.ServeAPI(ginServer)
  68. var host string
  69. if model.Conf.System.NetworkServe || util.ContainerDocker == util.Container {
  70. host = "0.0.0.0"
  71. } else {
  72. host = "127.0.0.1"
  73. }
  74. ln, err := net.Listen("tcp", host+":"+util.ServerPort)
  75. if nil != err {
  76. if !fastMode {
  77. logging.LogErrorf("boot kernel failed: %s", err)
  78. os.Exit(util.ExitCodeUnavailablePort)
  79. }
  80. }
  81. _, port, err := net.SplitHostPort(ln.Addr().String())
  82. if nil != err {
  83. if !fastMode {
  84. logging.LogErrorf("boot kernel failed: %s", err)
  85. os.Exit(util.ExitCodeUnavailablePort)
  86. }
  87. }
  88. util.ServerPort = port
  89. pid := fmt.Sprintf("%d", os.Getpid())
  90. if !fastMode {
  91. rewritePortJSON(pid, port)
  92. }
  93. logging.LogInfof("kernel [pid=%s] is booting [%s]", pid, "http://"+host+":"+port)
  94. util.HttpServing = true
  95. go func() {
  96. if util.FixedPort != port {
  97. // 启动一个 6806 端口的反向代理服务器,这样浏览器扩展才能直接使用 127.0.0.1:6806,不用配置端口
  98. serverURL, _ := url.Parse("http://" + host + ":" + port)
  99. proxy := httputil.NewSingleHostReverseProxy(serverURL)
  100. logging.LogInfof("kernel reverse proxy server [%s] is booting", util.FixedPort)
  101. if proxyErr := http.ListenAndServe(host+":"+util.FixedPort, proxy); nil != proxyErr {
  102. logging.LogErrorf("boot kernel reverse proxy server failed: %s", serverURL, proxyErr)
  103. }
  104. // 反代服务器启动失败不影响核心服务器启动
  105. }
  106. }()
  107. if err = http.Serve(ln, ginServer); nil != err {
  108. if !fastMode {
  109. logging.LogErrorf("boot kernel failed: %s", err)
  110. os.Exit(util.ExitCodeUnavailablePort)
  111. }
  112. }
  113. }
  114. func rewritePortJSON(pid, port string) {
  115. portJSON := filepath.Join(util.HomeDir, ".config", "siyuan", "port.json")
  116. pidPorts := map[string]string{}
  117. var data []byte
  118. var err error
  119. if gulu.File.IsExist(portJSON) {
  120. data, err = os.ReadFile(portJSON)
  121. if nil != err {
  122. logging.LogWarnf("read port.json failed: %s", err)
  123. } else {
  124. if err = gulu.JSON.UnmarshalJSON(data, &pidPorts); nil != err {
  125. logging.LogWarnf("unmarshal port.json failed: %s", err)
  126. }
  127. }
  128. }
  129. pidPorts[pid] = port
  130. if data, err = gulu.JSON.MarshalIndentJSON(pidPorts, "", " "); nil != err {
  131. logging.LogWarnf("marshal port.json failed: %s", err)
  132. } else {
  133. if err = os.WriteFile(portJSON, data, 0644); nil != err {
  134. logging.LogWarnf("write port.json failed: %s", err)
  135. }
  136. }
  137. }
  138. func serveExport(ginServer *gin.Engine) {
  139. ginServer.Static("/export/", filepath.Join(util.TempDir, "export"))
  140. }
  141. func serveWidgets(ginServer *gin.Engine) {
  142. ginServer.Static("/widgets/", filepath.Join(util.DataDir, "widgets"))
  143. }
  144. func serveEmojis(ginServer *gin.Engine) {
  145. ginServer.Static("/emojis/", filepath.Join(util.DataDir, "emojis"))
  146. }
  147. func serveTemplates(ginServer *gin.Engine) {
  148. ginServer.Static("/templates/", filepath.Join(util.DataDir, "templates"))
  149. }
  150. func serveAppearance(ginServer *gin.Engine) {
  151. siyuan := ginServer.Group("", model.CheckAuth)
  152. siyuan.Handle("GET", "/", func(c *gin.Context) {
  153. userAgentHeader := c.GetHeader("User-Agent")
  154. if strings.Contains(userAgentHeader, "Electron") {
  155. c.Redirect(302, "/stage/build/app/?r="+gulu.Rand.String(7))
  156. return
  157. }
  158. ua := user_agent.New(userAgentHeader)
  159. if ua.Mobile() {
  160. c.Redirect(302, "/stage/build/mobile/?r="+gulu.Rand.String(7))
  161. return
  162. }
  163. c.Redirect(302, "/stage/build/desktop/?r="+gulu.Rand.String(7))
  164. })
  165. appearancePath := util.AppearancePath
  166. if "dev" == util.Mode {
  167. appearancePath = filepath.Join(util.WorkingDir, "appearance")
  168. }
  169. siyuan.GET("/appearance/*filepath", func(c *gin.Context) {
  170. filePath := filepath.Join(appearancePath, strings.TrimPrefix(c.Request.URL.Path, "/appearance/"))
  171. if strings.HasSuffix(c.Request.URL.Path, "/theme.js") {
  172. if !gulu.File.IsExist(filePath) {
  173. // 主题 js 不存在时生成空内容返回
  174. c.Data(200, "application/x-javascript", nil)
  175. return
  176. }
  177. } else if strings.Contains(c.Request.URL.Path, "/langs/") && strings.HasSuffix(c.Request.URL.Path, ".json") {
  178. lang := path.Base(c.Request.URL.Path)
  179. lang = strings.TrimSuffix(lang, ".json")
  180. if "zh_CN" != lang && "en_US" != lang {
  181. // 多语言配置缺失项使用对应英文配置项补齐 https://github.com/siyuan-note/siyuan/issues/5322
  182. enUSFilePath := filepath.Join(appearancePath, "langs", "en_US.json")
  183. enUSData, err := os.ReadFile(enUSFilePath)
  184. if nil != err {
  185. logging.LogFatalf("read en_US.json [%s] failed: %s", enUSFilePath, err)
  186. return
  187. }
  188. enUSMap := map[string]interface{}{}
  189. if err = gulu.JSON.UnmarshalJSON(enUSData, &enUSMap); nil != err {
  190. logging.LogFatalf("unmarshal en_US.json [%s] failed: %s", enUSFilePath, err)
  191. return
  192. }
  193. for {
  194. data, err := os.ReadFile(filePath)
  195. if nil != err {
  196. c.JSON(200, enUSMap)
  197. return
  198. }
  199. langMap := map[string]interface{}{}
  200. if err = gulu.JSON.UnmarshalJSON(data, &langMap); nil != err {
  201. logging.LogErrorf("unmarshal json [%s] failed: %s", filePath, err)
  202. c.JSON(200, enUSMap)
  203. return
  204. }
  205. for enUSDataKey, enUSDataValue := range enUSMap {
  206. if _, ok := langMap[enUSDataKey]; !ok {
  207. langMap[enUSDataKey] = enUSDataValue
  208. }
  209. }
  210. c.JSON(200, langMap)
  211. return
  212. }
  213. }
  214. }
  215. c.File(filePath)
  216. })
  217. siyuan.Static("/stage/", filepath.Join(util.WorkingDir, "stage"))
  218. siyuan.StaticFile("favicon.ico", filepath.Join(util.WorkingDir, "stage", "icon.png"))
  219. siyuan.GET("/check-auth", serveCheckAuth)
  220. }
  221. func serveCheckAuth(c *gin.Context) {
  222. data, err := os.ReadFile(filepath.Join(util.WorkingDir, "stage/auth.html"))
  223. if nil != err {
  224. logging.LogErrorf("load auth page failed: %s", err)
  225. c.Status(500)
  226. return
  227. }
  228. c.Data(http.StatusOK, "text/html; charset=utf-8", data)
  229. }
  230. func serveAssets(ginServer *gin.Engine) {
  231. ginServer.POST("/upload", model.CheckAuth, model.Upload)
  232. ginServer.GET("/assets/*path", model.CheckAuth, func(context *gin.Context) {
  233. requestPath := context.Param("path")
  234. relativePath := path.Join("assets", requestPath)
  235. p, err := model.GetAssetAbsPath(relativePath)
  236. if nil != err {
  237. context.Status(404)
  238. return
  239. }
  240. http.ServeFile(context.Writer, context.Request, p)
  241. return
  242. })
  243. ginServer.GET("/history/*path", model.CheckAuth, func(context *gin.Context) {
  244. p := filepath.Join(util.HistoryDir, context.Param("path"))
  245. http.ServeFile(context.Writer, context.Request, p)
  246. return
  247. })
  248. }
  249. func serveDebug(ginServer *gin.Engine) {
  250. ginServer.GET("/debug/pprof/", gin.WrapF(pprof.Index))
  251. ginServer.GET("/debug/pprof/allocs", gin.WrapF(pprof.Index))
  252. ginServer.GET("/debug/pprof/block", gin.WrapF(pprof.Index))
  253. ginServer.GET("/debug/pprof/goroutine", gin.WrapF(pprof.Index))
  254. ginServer.GET("/debug/pprof/heap", gin.WrapF(pprof.Index))
  255. ginServer.GET("/debug/pprof/mutex", gin.WrapF(pprof.Index))
  256. ginServer.GET("/debug/pprof/threadcreate", gin.WrapF(pprof.Index))
  257. ginServer.GET("/debug/pprof/cmdline", gin.WrapF(pprof.Cmdline))
  258. ginServer.GET("/debug/pprof/profile", gin.WrapF(pprof.Profile))
  259. ginServer.GET("/debug/pprof/symbol", gin.WrapF(pprof.Symbol))
  260. ginServer.GET("/debug/pprof/trace", gin.WrapF(pprof.Trace))
  261. }
  262. func serveWebSocket(ginServer *gin.Engine) {
  263. util.WebSocketServer.Config.MaxMessageSize = 1024 * 1024 * 8
  264. ginServer.GET("/ws", func(c *gin.Context) {
  265. if err := util.WebSocketServer.HandleRequest(c.Writer, c.Request); nil != err {
  266. logging.LogErrorf("handle command failed: %s", err)
  267. }
  268. })
  269. util.WebSocketServer.HandlePong(func(session *melody.Session) {
  270. //logging.LogInfof("pong")
  271. })
  272. util.WebSocketServer.HandleConnect(func(s *melody.Session) {
  273. //logging.LogInfof("ws check auth for [%s]", s.Request.RequestURI)
  274. authOk := true
  275. if "" != model.Conf.AccessAuthCode {
  276. session, err := cookieStore.Get(s.Request, "siyuan")
  277. if nil != err {
  278. authOk = false
  279. logging.LogErrorf("get cookie failed: %s", err)
  280. } else {
  281. val := session.Values["data"]
  282. if nil == val {
  283. authOk = false
  284. } else {
  285. sess := map[string]interface{}{}
  286. err = gulu.JSON.UnmarshalJSON([]byte(val.(string)), &sess)
  287. if nil != err {
  288. authOk = false
  289. logging.LogErrorf("unmarshal cookie failed: %s", err)
  290. } else {
  291. authOk = sess["AccessAuthCode"].(string) == model.Conf.AccessAuthCode
  292. }
  293. }
  294. }
  295. }
  296. if !authOk {
  297. // 用于授权页保持连接,避免非常驻内存内核自动退出 https://github.com/siyuan-note/insider/issues/1099
  298. authOk = strings.Contains(s.Request.RequestURI, "/ws?app=siyuan&id=auth")
  299. }
  300. if !authOk {
  301. s.CloseWithMsg([]byte(" unauthenticated"))
  302. //logging.LogWarnf("closed an unauthenticated session [%s]", util.GetRemoteAddr(s))
  303. return
  304. }
  305. util.AddPushChan(s)
  306. //sessionId, _ := s.Get("id")
  307. //logging.LogInfof("ws [%s] connected", sessionId)
  308. })
  309. util.WebSocketServer.HandleDisconnect(func(s *melody.Session) {
  310. util.RemovePushChan(s)
  311. //sessionId, _ := s.Get("id")
  312. //logging.LogInfof("ws [%s] disconnected", sessionId)
  313. })
  314. util.WebSocketServer.HandleError(func(s *melody.Session, err error) {
  315. //sessionId, _ := s.Get("id")
  316. //logging.LogDebugf("ws [%s] failed: %s", sessionId, err)
  317. })
  318. util.WebSocketServer.HandleClose(func(s *melody.Session, i int, str string) error {
  319. //sessionId, _ := s.Get("id")
  320. //logging.LogDebugf("ws [%s] closed: %v, %v", sessionId, i, str)
  321. return nil
  322. })
  323. util.WebSocketServer.HandleMessage(func(s *melody.Session, msg []byte) {
  324. start := time.Now()
  325. logging.LogTracef("request [%s]", shortReqMsg(msg))
  326. request := map[string]interface{}{}
  327. if err := gulu.JSON.UnmarshalJSON(msg, &request); nil != err {
  328. result := util.NewResult()
  329. result.Code = -1
  330. result.Msg = "Bad Request"
  331. responseData, _ := gulu.JSON.MarshalJSON(result)
  332. s.Write(responseData)
  333. return
  334. }
  335. if _, ok := s.Get("app"); !ok {
  336. result := util.NewResult()
  337. result.Code = -1
  338. result.Msg = "Bad Request"
  339. s.Write(result.Bytes())
  340. return
  341. }
  342. cmdStr := request["cmd"].(string)
  343. cmdId := request["reqId"].(float64)
  344. param := request["param"].(map[string]interface{})
  345. command := cmd.NewCommand(cmdStr, cmdId, param, s)
  346. if nil == command {
  347. result := util.NewResult()
  348. result.Code = -1
  349. result.Msg = "can not find command [" + cmdStr + "]"
  350. s.Write(result.Bytes())
  351. return
  352. }
  353. if util.ReadOnly && !command.IsRead() {
  354. result := util.NewResult()
  355. result.Code = -1
  356. result.Msg = model.Conf.Language(34)
  357. s.Write(result.Bytes())
  358. return
  359. }
  360. end := time.Now()
  361. logging.LogTracef("parse cmd [%s] consumed [%d]ms", command.Name(), end.Sub(start).Milliseconds())
  362. cmd.Exec(command)
  363. })
  364. }
  365. func shortReqMsg(msg []byte) []byte {
  366. s := gulu.Str.FromBytes(msg)
  367. max := 128
  368. if len(s) > max {
  369. count := 0
  370. for i := range s {
  371. count++
  372. if count > max {
  373. return gulu.Str.ToBytes(s[:i] + "...")
  374. }
  375. }
  376. }
  377. return msg
  378. }
  379. func corsMiddleware() gin.HandlerFunc {
  380. return func(c *gin.Context) {
  381. c.Header("Access-Control-Allow-Origin", "*")
  382. c.Header("Access-Control-Allow-Credentials", "true")
  383. c.Header("Access-Control-Allow-Headers", "origin, Content-Length, Content-Type, Authorization")
  384. c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS")
  385. if c.Request.Method == "OPTIONS" {
  386. c.AbortWithStatus(204)
  387. return
  388. }
  389. c.Next()
  390. }
  391. }