serve.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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. // fast 模式下启动失败则直接返回
  81. return
  82. }
  83. _, port, err := net.SplitHostPort(ln.Addr().String())
  84. if nil != err {
  85. if !fastMode {
  86. logging.LogErrorf("boot kernel failed: %s", err)
  87. os.Exit(util.ExitCodeUnavailablePort)
  88. }
  89. }
  90. util.ServerPort = port
  91. pid := fmt.Sprintf("%d", os.Getpid())
  92. if !fastMode {
  93. rewritePortJSON(pid, port)
  94. }
  95. logging.LogInfof("kernel [pid=%s] is booting [%s]", pid, "http://"+util.LocalHost+":"+port)
  96. util.HttpServing = true
  97. go func() {
  98. if util.FixedPort != port {
  99. // 启动一个 6806 端口的反向代理服务器,这样浏览器扩展才能直接使用 127.0.0.1:6806,不用配置端口
  100. serverURL, _ := url.Parse("http://" + host + ":" + port)
  101. proxy := httputil.NewSingleHostReverseProxy(serverURL)
  102. logging.LogInfof("kernel reverse proxy server [%s] is booting", util.FixedPort)
  103. if proxyErr := http.ListenAndServe(host+":"+util.FixedPort, proxy); nil != proxyErr {
  104. logging.LogErrorf("boot kernel reverse proxy server failed: %s", serverURL, proxyErr)
  105. }
  106. // 反代服务器启动失败不影响核心服务器启动
  107. }
  108. }()
  109. if err = http.Serve(ln, ginServer); nil != err {
  110. if !fastMode {
  111. logging.LogErrorf("boot kernel failed: %s", err)
  112. os.Exit(util.ExitCodeUnavailablePort)
  113. }
  114. }
  115. }
  116. func rewritePortJSON(pid, port string) {
  117. portJSON := filepath.Join(util.HomeDir, ".config", "siyuan", "port.json")
  118. pidPorts := map[string]string{}
  119. var data []byte
  120. var err error
  121. if gulu.File.IsExist(portJSON) {
  122. data, err = os.ReadFile(portJSON)
  123. if nil != err {
  124. logging.LogWarnf("read port.json failed: %s", err)
  125. } else {
  126. if err = gulu.JSON.UnmarshalJSON(data, &pidPorts); nil != err {
  127. logging.LogWarnf("unmarshal port.json failed: %s", err)
  128. }
  129. }
  130. }
  131. pidPorts[pid] = port
  132. if data, err = gulu.JSON.MarshalIndentJSON(pidPorts, "", " "); nil != err {
  133. logging.LogWarnf("marshal port.json failed: %s", err)
  134. } else {
  135. if err = os.WriteFile(portJSON, data, 0644); nil != err {
  136. logging.LogWarnf("write port.json failed: %s", err)
  137. }
  138. }
  139. }
  140. func serveExport(ginServer *gin.Engine) {
  141. ginServer.Static("/export/", filepath.Join(util.TempDir, "export"))
  142. }
  143. func serveWidgets(ginServer *gin.Engine) {
  144. ginServer.Static("/widgets/", filepath.Join(util.DataDir, "widgets"))
  145. }
  146. func serveEmojis(ginServer *gin.Engine) {
  147. ginServer.Static("/emojis/", filepath.Join(util.DataDir, "emojis"))
  148. }
  149. func serveTemplates(ginServer *gin.Engine) {
  150. ginServer.Static("/templates/", filepath.Join(util.DataDir, "templates"))
  151. }
  152. func serveAppearance(ginServer *gin.Engine) {
  153. siyuan := ginServer.Group("", model.CheckAuth)
  154. siyuan.Handle("GET", "/", func(c *gin.Context) {
  155. userAgentHeader := c.GetHeader("User-Agent")
  156. if strings.Contains(userAgentHeader, "Electron") {
  157. c.Redirect(302, "/stage/build/app/?r="+gulu.Rand.String(7))
  158. return
  159. }
  160. ua := user_agent.New(userAgentHeader)
  161. if ua.Mobile() {
  162. c.Redirect(302, "/stage/build/mobile/?r="+gulu.Rand.String(7))
  163. return
  164. }
  165. c.Redirect(302, "/stage/build/desktop/?r="+gulu.Rand.String(7))
  166. })
  167. appearancePath := util.AppearancePath
  168. if "dev" == util.Mode {
  169. appearancePath = filepath.Join(util.WorkingDir, "appearance")
  170. }
  171. siyuan.GET("/appearance/*filepath", func(c *gin.Context) {
  172. filePath := filepath.Join(appearancePath, strings.TrimPrefix(c.Request.URL.Path, "/appearance/"))
  173. if strings.HasSuffix(c.Request.URL.Path, "/theme.js") {
  174. if !gulu.File.IsExist(filePath) {
  175. // 主题 js 不存在时生成空内容返回
  176. c.Data(200, "application/x-javascript", nil)
  177. return
  178. }
  179. } else if strings.Contains(c.Request.URL.Path, "/langs/") && strings.HasSuffix(c.Request.URL.Path, ".json") {
  180. lang := path.Base(c.Request.URL.Path)
  181. lang = strings.TrimSuffix(lang, ".json")
  182. if "zh_CN" != lang && "en_US" != lang {
  183. // 多语言配置缺失项使用对应英文配置项补齐 https://github.com/siyuan-note/siyuan/issues/5322
  184. enUSFilePath := filepath.Join(appearancePath, "langs", "en_US.json")
  185. enUSData, err := os.ReadFile(enUSFilePath)
  186. if nil != err {
  187. logging.LogFatalf("read en_US.json [%s] failed: %s", enUSFilePath, err)
  188. return
  189. }
  190. enUSMap := map[string]interface{}{}
  191. if err = gulu.JSON.UnmarshalJSON(enUSData, &enUSMap); nil != err {
  192. logging.LogFatalf("unmarshal en_US.json [%s] failed: %s", enUSFilePath, err)
  193. return
  194. }
  195. for {
  196. data, err := os.ReadFile(filePath)
  197. if nil != err {
  198. c.JSON(200, enUSMap)
  199. return
  200. }
  201. langMap := map[string]interface{}{}
  202. if err = gulu.JSON.UnmarshalJSON(data, &langMap); nil != err {
  203. logging.LogErrorf("unmarshal json [%s] failed: %s", filePath, err)
  204. c.JSON(200, enUSMap)
  205. return
  206. }
  207. for enUSDataKey, enUSDataValue := range enUSMap {
  208. if _, ok := langMap[enUSDataKey]; !ok {
  209. langMap[enUSDataKey] = enUSDataValue
  210. }
  211. }
  212. c.JSON(200, langMap)
  213. return
  214. }
  215. }
  216. }
  217. c.File(filePath)
  218. })
  219. siyuan.Static("/stage/", filepath.Join(util.WorkingDir, "stage"))
  220. siyuan.StaticFile("favicon.ico", filepath.Join(util.WorkingDir, "stage", "icon.png"))
  221. siyuan.GET("/check-auth", serveCheckAuth)
  222. }
  223. func serveCheckAuth(c *gin.Context) {
  224. data, err := os.ReadFile(filepath.Join(util.WorkingDir, "stage/auth.html"))
  225. if nil != err {
  226. logging.LogErrorf("load auth page failed: %s", err)
  227. c.Status(500)
  228. return
  229. }
  230. c.Data(http.StatusOK, "text/html; charset=utf-8", data)
  231. }
  232. func serveAssets(ginServer *gin.Engine) {
  233. ginServer.POST("/upload", model.CheckAuth, model.Upload)
  234. ginServer.GET("/assets/*path", model.CheckAuth, func(context *gin.Context) {
  235. requestPath := context.Param("path")
  236. relativePath := path.Join("assets", requestPath)
  237. p, err := model.GetAssetAbsPath(relativePath)
  238. if nil != err {
  239. context.Status(404)
  240. return
  241. }
  242. http.ServeFile(context.Writer, context.Request, p)
  243. return
  244. })
  245. ginServer.GET("/history/*path", model.CheckAuth, func(context *gin.Context) {
  246. p := filepath.Join(util.HistoryDir, context.Param("path"))
  247. http.ServeFile(context.Writer, context.Request, p)
  248. return
  249. })
  250. }
  251. func serveDebug(ginServer *gin.Engine) {
  252. ginServer.GET("/debug/pprof/", gin.WrapF(pprof.Index))
  253. ginServer.GET("/debug/pprof/allocs", gin.WrapF(pprof.Index))
  254. ginServer.GET("/debug/pprof/block", gin.WrapF(pprof.Index))
  255. ginServer.GET("/debug/pprof/goroutine", gin.WrapF(pprof.Index))
  256. ginServer.GET("/debug/pprof/heap", gin.WrapF(pprof.Index))
  257. ginServer.GET("/debug/pprof/mutex", gin.WrapF(pprof.Index))
  258. ginServer.GET("/debug/pprof/threadcreate", gin.WrapF(pprof.Index))
  259. ginServer.GET("/debug/pprof/cmdline", gin.WrapF(pprof.Cmdline))
  260. ginServer.GET("/debug/pprof/profile", gin.WrapF(pprof.Profile))
  261. ginServer.GET("/debug/pprof/symbol", gin.WrapF(pprof.Symbol))
  262. ginServer.GET("/debug/pprof/trace", gin.WrapF(pprof.Trace))
  263. }
  264. func serveWebSocket(ginServer *gin.Engine) {
  265. util.WebSocketServer.Config.MaxMessageSize = 1024 * 1024 * 8
  266. ginServer.GET("/ws", func(c *gin.Context) {
  267. if err := util.WebSocketServer.HandleRequest(c.Writer, c.Request); nil != err {
  268. logging.LogErrorf("handle command failed: %s", err)
  269. }
  270. })
  271. util.WebSocketServer.HandlePong(func(session *melody.Session) {
  272. //logging.LogInfof("pong")
  273. })
  274. util.WebSocketServer.HandleConnect(func(s *melody.Session) {
  275. //logging.LogInfof("ws check auth for [%s]", s.Request.RequestURI)
  276. authOk := true
  277. if "" != model.Conf.AccessAuthCode {
  278. session, err := cookieStore.Get(s.Request, "siyuan")
  279. if nil != err {
  280. authOk = false
  281. logging.LogErrorf("get cookie failed: %s", err)
  282. } else {
  283. val := session.Values["data"]
  284. if nil == val {
  285. authOk = false
  286. } else {
  287. sess := map[string]interface{}{}
  288. err = gulu.JSON.UnmarshalJSON([]byte(val.(string)), &sess)
  289. if nil != err {
  290. authOk = false
  291. logging.LogErrorf("unmarshal cookie failed: %s", err)
  292. } else {
  293. authOk = sess["AccessAuthCode"].(string) == model.Conf.AccessAuthCode
  294. }
  295. }
  296. }
  297. }
  298. if !authOk {
  299. // 用于授权页保持连接,避免非常驻内存内核自动退出 https://github.com/siyuan-note/insider/issues/1099
  300. authOk = strings.Contains(s.Request.RequestURI, "/ws?app=siyuan&id=auth")
  301. }
  302. if !authOk {
  303. s.CloseWithMsg([]byte(" unauthenticated"))
  304. //logging.LogWarnf("closed an unauthenticated session [%s]", util.GetRemoteAddr(s))
  305. return
  306. }
  307. util.AddPushChan(s)
  308. //sessionId, _ := s.Get("id")
  309. //logging.LogInfof("ws [%s] connected", sessionId)
  310. })
  311. util.WebSocketServer.HandleDisconnect(func(s *melody.Session) {
  312. util.RemovePushChan(s)
  313. //sessionId, _ := s.Get("id")
  314. //logging.LogInfof("ws [%s] disconnected", sessionId)
  315. })
  316. util.WebSocketServer.HandleError(func(s *melody.Session, err error) {
  317. //sessionId, _ := s.Get("id")
  318. //logging.LogDebugf("ws [%s] failed: %s", sessionId, err)
  319. })
  320. util.WebSocketServer.HandleClose(func(s *melody.Session, i int, str string) error {
  321. //sessionId, _ := s.Get("id")
  322. //logging.LogDebugf("ws [%s] closed: %v, %v", sessionId, i, str)
  323. return nil
  324. })
  325. util.WebSocketServer.HandleMessage(func(s *melody.Session, msg []byte) {
  326. start := time.Now()
  327. logging.LogTracef("request [%s]", shortReqMsg(msg))
  328. request := map[string]interface{}{}
  329. if err := gulu.JSON.UnmarshalJSON(msg, &request); nil != err {
  330. result := util.NewResult()
  331. result.Code = -1
  332. result.Msg = "Bad Request"
  333. responseData, _ := gulu.JSON.MarshalJSON(result)
  334. s.Write(responseData)
  335. return
  336. }
  337. if _, ok := s.Get("app"); !ok {
  338. result := util.NewResult()
  339. result.Code = -1
  340. result.Msg = "Bad Request"
  341. s.Write(result.Bytes())
  342. return
  343. }
  344. cmdStr := request["cmd"].(string)
  345. cmdId := request["reqId"].(float64)
  346. param := request["param"].(map[string]interface{})
  347. command := cmd.NewCommand(cmdStr, cmdId, param, s)
  348. if nil == command {
  349. result := util.NewResult()
  350. result.Code = -1
  351. result.Msg = "can not find command [" + cmdStr + "]"
  352. s.Write(result.Bytes())
  353. return
  354. }
  355. if util.ReadOnly && !command.IsRead() {
  356. result := util.NewResult()
  357. result.Code = -1
  358. result.Msg = model.Conf.Language(34)
  359. s.Write(result.Bytes())
  360. return
  361. }
  362. end := time.Now()
  363. logging.LogTracef("parse cmd [%s] consumed [%d]ms", command.Name(), end.Sub(start).Milliseconds())
  364. cmd.Exec(command)
  365. })
  366. }
  367. func shortReqMsg(msg []byte) []byte {
  368. s := gulu.Str.FromBytes(msg)
  369. max := 128
  370. if len(s) > max {
  371. count := 0
  372. for i := range s {
  373. count++
  374. if count > max {
  375. return gulu.Str.ToBytes(s[:i] + "...")
  376. }
  377. }
  378. }
  379. return msg
  380. }
  381. func corsMiddleware() gin.HandlerFunc {
  382. return func(c *gin.Context) {
  383. c.Header("Access-Control-Allow-Origin", "*")
  384. c.Header("Access-Control-Allow-Credentials", "true")
  385. c.Header("Access-Control-Allow-Headers", "origin, Content-Length, Content-Type, Authorization")
  386. c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS")
  387. if c.Request.Method == "OPTIONS" {
  388. c.AbortWithStatus(204)
  389. return
  390. }
  391. c.Next()
  392. }
  393. }