serve.go 15 KB

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