serve.go 14 KB

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