serve.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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. "net/http"
  19. "net/http/pprof"
  20. "os"
  21. "path"
  22. "path/filepath"
  23. "strings"
  24. "time"
  25. "github.com/88250/gulu"
  26. "github.com/88250/melody"
  27. "github.com/gin-contrib/cors"
  28. "github.com/gin-contrib/gzip"
  29. "github.com/gin-contrib/sessions"
  30. "github.com/gin-contrib/sessions/cookie"
  31. "github.com/gin-gonic/gin"
  32. "github.com/mssola/user_agent"
  33. "github.com/siyuan-note/siyuan/kernel/api"
  34. "github.com/siyuan-note/siyuan/kernel/cmd"
  35. "github.com/siyuan-note/siyuan/kernel/model"
  36. "github.com/siyuan-note/siyuan/kernel/util"
  37. )
  38. var cookieStore = cookie.NewStore([]byte("ATN51UlxVq1Gcvdf"))
  39. func Serve(fastMode bool) {
  40. gin.SetMode(gin.ReleaseMode)
  41. ginServer := gin.New()
  42. ginServer.MaxMultipartMemory = 1024 * 1024 * 32 // 32MB
  43. ginServer.Use(gin.Recovery())
  44. ginServer.Use(cors.Default())
  45. ginServer.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedExtensions([]string{".pdf", ".mp3", ".wav", ".ogg", ".mov", ".weba", ".mkv", ".mp4", ".webm"})))
  46. cookieStore.Options(sessions.Options{
  47. Path: "/",
  48. Secure: util.SSL,
  49. //MaxAge: 60 * 60 * 24 * 7, // 默认是 Session
  50. HttpOnly: true,
  51. })
  52. ginServer.Use(sessions.Sessions("siyuan", cookieStore))
  53. if "dev" == util.Mode {
  54. serveDebug(ginServer)
  55. }
  56. serveAssets(ginServer)
  57. serveAppearance(ginServer)
  58. serveWebSocket(ginServer)
  59. serveExport(ginServer)
  60. serveWidgets(ginServer)
  61. serveEmojis(ginServer)
  62. api.ServeAPI(ginServer)
  63. var addr string
  64. if model.Conf.System.NetworkServe || "docker" == util.Container {
  65. addr = "0.0.0.0:" + util.ServerPort
  66. } else {
  67. addr = "127.0.0.1:" + util.ServerPort
  68. }
  69. util.LogInfof("kernel is booting [%s]", "http://"+addr)
  70. util.HttpServing = true
  71. if err := ginServer.Run(addr); nil != err {
  72. if !fastMode {
  73. util.LogErrorf("boot kernel failed: %s", err)
  74. os.Exit(util.ExitCodeUnavailablePort)
  75. }
  76. }
  77. }
  78. func serveExport(ginServer *gin.Engine) {
  79. ginServer.Static("/export/", filepath.Join(util.TempDir, "export"))
  80. }
  81. func serveWidgets(ginServer *gin.Engine) {
  82. ginServer.Static("/widgets/", filepath.Join(util.DataDir, "widgets"))
  83. }
  84. func serveEmojis(ginServer *gin.Engine) {
  85. ginServer.Static("/emojis/", filepath.Join(util.DataDir, "emojis"))
  86. }
  87. func serveAppearance(ginServer *gin.Engine) {
  88. siyuan := ginServer.Group("", model.CheckAuth)
  89. siyuan.Handle("GET", "/", func(c *gin.Context) {
  90. userAgentHeader := c.GetHeader("User-Agent")
  91. if strings.Contains(userAgentHeader, "Electron") {
  92. c.Redirect(302, "/stage/build/app/?r="+gulu.Rand.String(7))
  93. return
  94. }
  95. ua := user_agent.New(userAgentHeader)
  96. if ua.Mobile() {
  97. c.Redirect(302, "/stage/build/mobile/?r="+gulu.Rand.String(7))
  98. return
  99. }
  100. c.Redirect(302, "/stage/build/desktop/?r="+gulu.Rand.String(7))
  101. })
  102. appearancePath := util.AppearancePath
  103. if "dev" == util.Mode {
  104. appearancePath = filepath.Join(util.WorkingDir, "appearance")
  105. }
  106. siyuan.GET("/appearance/*filepath", func(c *gin.Context) {
  107. filePath := filepath.Join(appearancePath, strings.TrimPrefix(c.Request.URL.Path, "/appearance/"))
  108. if strings.HasSuffix(c.Request.URL.Path, "/theme.js") && !gulu.File.IsExist(filePath) {
  109. // 主题 js 不存在时生成空内容返回
  110. c.Data(200, "application/x-javascript", nil)
  111. return
  112. }
  113. c.File(filePath)
  114. })
  115. siyuan.Static("/stage/", filepath.Join(util.WorkingDir, "stage"))
  116. siyuan.StaticFile("favicon.ico", filepath.Join(util.WorkingDir, "stage", "icon.png"))
  117. siyuan.GET("/check-auth", serveCheckAuth)
  118. }
  119. func serveCheckAuth(c *gin.Context) {
  120. data, err := os.ReadFile(filepath.Join(util.WorkingDir, "stage/auth.html"))
  121. if nil != err {
  122. util.LogErrorf("load auth page failed: %s", err)
  123. c.Status(500)
  124. return
  125. }
  126. c.Data(http.StatusOK, "text/html; charset=utf-8", data)
  127. }
  128. func serveAssets(ginServer *gin.Engine) {
  129. ginServer.POST("/upload", model.CheckAuth, model.Upload)
  130. ginServer.GET("/assets/*path", model.CheckAuth, func(context *gin.Context) {
  131. requestPath := context.Param("path")
  132. relativePath := path.Join("assets", requestPath)
  133. p, err := model.GetAssetAbsPath(relativePath)
  134. if nil != err {
  135. context.Status(404)
  136. return
  137. }
  138. http.ServeFile(context.Writer, context.Request, p)
  139. return
  140. })
  141. ginServer.GET("/history/:dir/assets/*name", model.CheckAuth, func(context *gin.Context) {
  142. dir := context.Param("dir")
  143. name := context.Param("name")
  144. relativePath := path.Join(dir, "assets", name)
  145. p := filepath.Join(util.WorkspaceDir, "history", relativePath)
  146. http.ServeFile(context.Writer, context.Request, p)
  147. return
  148. })
  149. }
  150. func serveDebug(ginServer *gin.Engine) {
  151. ginServer.GET("/debug/pprof/", gin.WrapF(pprof.Index))
  152. ginServer.GET("/debug/pprof/allocs", gin.WrapF(pprof.Index))
  153. ginServer.GET("/debug/pprof/block", gin.WrapF(pprof.Index))
  154. ginServer.GET("/debug/pprof/goroutine", gin.WrapF(pprof.Index))
  155. ginServer.GET("/debug/pprof/heap", gin.WrapF(pprof.Index))
  156. ginServer.GET("/debug/pprof/mutex", gin.WrapF(pprof.Index))
  157. ginServer.GET("/debug/pprof/threadcreate", gin.WrapF(pprof.Index))
  158. ginServer.GET("/debug/pprof/cmdline", gin.WrapF(pprof.Cmdline))
  159. ginServer.GET("/debug/pprof/profile", gin.WrapF(pprof.Profile))
  160. ginServer.GET("/debug/pprof/symbol", gin.WrapF(pprof.Symbol))
  161. ginServer.GET("/debug/pprof/trace", gin.WrapF(pprof.Trace))
  162. }
  163. func serveWebSocket(ginServer *gin.Engine) {
  164. util.WebSocketServer.Config.MaxMessageSize = 1024 * 1024 * 8
  165. if "docker" == util.Container { // Docker 容器运行时启用 WebSocket 传输压缩
  166. util.WebSocketServer.Config.EnableCompression = true
  167. util.WebSocketServer.Config.CompressionLevel = 4
  168. }
  169. ginServer.GET("/ws", func(c *gin.Context) {
  170. if err := util.WebSocketServer.HandleRequest(c.Writer, c.Request); nil != err {
  171. util.LogErrorf("handle command failed: %s", err)
  172. }
  173. })
  174. util.WebSocketServer.HandlePong(func(session *melody.Session) {
  175. //model.Logger.Debugf("pong")
  176. })
  177. util.WebSocketServer.HandleConnect(func(s *melody.Session) {
  178. //util.LogInfof("ws check auth for [%s]", s.Request.RequestURI)
  179. authOk := true
  180. if "" != model.Conf.AccessAuthCode {
  181. session, err := cookieStore.Get(s.Request, "siyuan")
  182. if nil != err {
  183. authOk = false
  184. util.LogErrorf("get cookie failed: %s", err)
  185. } else {
  186. val := session.Values["data"]
  187. if nil == val {
  188. authOk = false
  189. } else {
  190. sess := map[string]interface{}{}
  191. err = gulu.JSON.UnmarshalJSON([]byte(val.(string)), &sess)
  192. if nil != err {
  193. authOk = false
  194. util.LogErrorf("unmarshal cookie failed: %s", err)
  195. } else {
  196. authOk = sess["AccessAuthCode"].(string) == model.Conf.AccessAuthCode
  197. }
  198. }
  199. }
  200. }
  201. if !authOk {
  202. s.CloseWithMsg([]byte(" unauthenticated"))
  203. //util.LogWarnf("closed a unauthenticated session [%s]", util.GetRemoteAddr(s))
  204. return
  205. }
  206. util.AddPushChan(s)
  207. //sessionId, _ := s.Get("id")
  208. //util.LogInfof("ws [%s] connected", sessionId)
  209. })
  210. util.WebSocketServer.HandleDisconnect(func(s *melody.Session) {
  211. util.RemovePushChan(s)
  212. //sessionId, _ := s.Get("id")
  213. //model.Logger.Debugf("ws [%s] disconnected", sessionId)
  214. })
  215. util.WebSocketServer.HandleError(func(s *melody.Session, err error) {
  216. //sessionId, _ := s.Get("id")
  217. //util.LogDebugf("ws [%s] failed: %s", sessionId, err)
  218. })
  219. util.WebSocketServer.HandleClose(func(s *melody.Session, i int, str string) error {
  220. //sessionId, _ := s.Get("id")
  221. //util.LogDebugf("ws [%s] closed: %v, %v", sessionId, i, str)
  222. return nil
  223. })
  224. util.WebSocketServer.HandleMessage(func(s *melody.Session, msg []byte) {
  225. start := time.Now()
  226. util.LogTracef("request [%s]", shortReqMsg(msg))
  227. request := map[string]interface{}{}
  228. if err := gulu.JSON.UnmarshalJSON(msg, &request); nil != err {
  229. result := util.NewResult()
  230. result.Code = -1
  231. result.Msg = "Bad Request"
  232. responseData, _ := gulu.JSON.MarshalJSON(result)
  233. s.Write(responseData)
  234. return
  235. }
  236. if _, ok := s.Get("app"); !ok {
  237. result := util.NewResult()
  238. result.Code = -1
  239. result.Msg = "Bad Request"
  240. s.Write(result.Bytes())
  241. return
  242. }
  243. cmdStr := request["cmd"].(string)
  244. cmdId := request["reqId"].(float64)
  245. param := request["param"].(map[string]interface{})
  246. command := cmd.NewCommand(cmdStr, cmdId, param, s)
  247. if nil == command {
  248. result := util.NewResult()
  249. result.Code = -1
  250. result.Msg = "can not find command [" + cmdStr + "]"
  251. s.Write(result.Bytes())
  252. return
  253. }
  254. if util.ReadOnly && !command.IsRead() {
  255. result := util.NewResult()
  256. result.Code = -1
  257. result.Msg = model.Conf.Language(34)
  258. s.Write(result.Bytes())
  259. return
  260. }
  261. end := time.Now()
  262. util.LogTracef("parse cmd [%s] consumed [%d]ms", command.Name(), end.Sub(start).Milliseconds())
  263. cmd.Exec(command)
  264. })
  265. }
  266. func shortReqMsg(msg []byte) []byte {
  267. s := gulu.Str.FromBytes(msg)
  268. max := 128
  269. if len(s) > max {
  270. count := 0
  271. for i := range s {
  272. count++
  273. if count > max {
  274. return gulu.Str.ToBytes(s[:i] + "...")
  275. }
  276. }
  277. }
  278. return msg
  279. }