serve.go 15 KB

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