syncthing.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package main
  2. import (
  3. "errors"
  4. "net/http"
  5. "path/filepath"
  6. "strings"
  7. "imuslab.com/arozos/mod/fileservers"
  8. "imuslab.com/arozos/mod/fileservers/servers/syncthingserv"
  9. "imuslab.com/arozos/mod/filesystem/arozfs"
  10. prout "imuslab.com/arozos/mod/prouter"
  11. "imuslab.com/arozos/mod/quota"
  12. )
  13. /*
  14. syncthing.go
  15. Wires the embedded Syncthing device into the file server list. An admin
  16. turns it on and picks the permission groups that may use it (admins
  17. always can). Each of those users links their own phones and computers and
  18. picks, for every folder they share, a folder of their drives to keep it in.
  19. */
  20. // SyncthingManager is nil where this build carries no Syncthing.
  21. var SyncthingManager *syncthingserv.Manager
  22. // SyncthingInit sets up the manager, its endpoints and its list entry.
  23. func SyncthingInit(router, adminRouter *prout.RouterDef) {
  24. if !syncthingserv.Available() {
  25. return
  26. }
  27. var err error
  28. SyncthingManager, err = syncthingserv.NewManager(&syncthingserv.ManagerOption{
  29. Sysdb: sysdb,
  30. StateDir: filepath.Join("system", "syncthing"),
  31. DeviceName: *host_name,
  32. CurrentUser: func(w http.ResponseWriter, r *http.Request) (string, error) {
  33. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  34. if err != nil {
  35. return "", err
  36. }
  37. return userinfo.Username, nil
  38. },
  39. ConfirmPassword: func(w http.ResponseWriter, r *http.Request) bool {
  40. return AuthValidateSecureRequest(w, r, false)
  41. },
  42. UserExists: authAgent.UserExists,
  43. IsAdmin: func(username string) bool {
  44. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  45. return err == nil && userinfo.IsAdmin()
  46. },
  47. InGroups: func(username string, groups []string) bool {
  48. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  49. return err == nil && userinfo.UserIsInOneOfTheGroupOf(groups)
  50. },
  51. ListGroups: func() []string {
  52. names := []string{}
  53. for _, group := range permissionHandler.PermissionGroups {
  54. names = append(names, group.Name)
  55. }
  56. return names
  57. },
  58. ResolveFolder: syncthingResolveFolder,
  59. })
  60. if err != nil {
  61. systemWideLogger.PrintAndLog("Syncthing", "The Syncthing server is not available", err)
  62. SyncthingManager = nil
  63. return
  64. }
  65. router.HandleFunc("/system/storage/syncthing/status", SyncthingManager.HandleStatus)
  66. router.HandleFunc("/system/storage/syncthing/qr", SyncthingManager.HandleQR)
  67. router.HandleFunc("/system/storage/syncthing/device/add", SyncthingManager.HandleDeviceAdd)
  68. router.HandleFunc("/system/storage/syncthing/device/edit", SyncthingManager.HandleDeviceEdit)
  69. router.HandleFunc("/system/storage/syncthing/device/remove", SyncthingManager.HandleDeviceRemove)
  70. router.HandleFunc("/system/storage/syncthing/folder/add", SyncthingManager.HandleFolderAdd)
  71. router.HandleFunc("/system/storage/syncthing/folder/edit", SyncthingManager.HandleFolderEdit)
  72. router.HandleFunc("/system/storage/syncthing/folder/remove", SyncthingManager.HandleFolderRemove)
  73. router.HandleFunc("/system/storage/syncthing/folder/rescan", SyncthingManager.HandleFolderRescan)
  74. router.HandleFunc("/system/storage/syncthing/offer/ignore", SyncthingManager.HandleOfferIgnore)
  75. adminRouter.HandleFunc("/system/storage/syncthing/config", SyncthingManager.HandleConfig)
  76. adminRouter.HandleFunc("/system/storage/syncthing/overview", SyncthingManager.HandleOverview)
  77. adminRouter.HandleFunc("/system/storage/syncthing/admin/remove", SyncthingManager.HandleAdminRemove)
  78. networkFileServerDaemon = append(networkFileServerDaemon, &fileservers.Server{
  79. ID: "syncthing",
  80. Name: "Syncthing",
  81. Desc: "Sync folders with phones and computers running Syncthing",
  82. IconPath: "img/system/network-folder-syncthing.svg",
  83. DefaultPorts: []int{syncthingserv.DefaultPort},
  84. Ports: []int{},
  85. ForwardPortIfUpnp: false, //Syncthing opens its own port with UPnP / NAT-PMP when allowed
  86. ConnInstrPage: "SystemAO/disk/instr/syncthing.html",
  87. ConfigPage: "SystemAO/disk/syncthing.html",
  88. EnableCheck: SyncthingManager.IsEnabled,
  89. ToggleFunc: SyncthingManager.ServerToggle,
  90. GetEndpoints: SyncthingManager.GetEndpoints,
  91. })
  92. }
  93. // SyncthingShutdown stops Syncthing if it is running.
  94. func SyncthingShutdown() {
  95. if SyncthingManager != nil {
  96. SyncthingManager.Close()
  97. }
  98. }
  99. // syncthingQuota is a user's storage quota as Syncthing sees it.
  100. type syncthingQuota struct {
  101. q *quota.QuotaHandler
  102. }
  103. func (s syncthingQuota) Usage() (int64, int64) {
  104. return s.q.UsedStorageQuota, s.q.TotalStorageQuota
  105. }
  106. func (s syncthingQuota) Recount() {
  107. s.q.CalculateQuotaUsage()
  108. }
  109. // syncthingResolveFolder finds where a folder of a user's drives is on the
  110. // host. Syncthing writes there directly, so the checks here are the ones the
  111. // file operations of the web desktop would make: the user can write to it,
  112. // it is on a local disk (not a network, cloud, cluster or shared drive), and
  113. // no symbolic link carries it off its drive or into the system folder.
  114. func syncthingResolveFolder(username, vpath string, create bool) (syncthingserv.Location, error) {
  115. none := syncthingserv.Location{}
  116. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  117. if err != nil {
  118. return none, err
  119. }
  120. fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  121. if err != nil {
  122. return none, errors.New("This drive cannot be found")
  123. }
  124. if fsh.Closed {
  125. return none, errors.New("This drive is not mounted")
  126. }
  127. if arozfs.IsNetworkDrive(fsh.Filesystem) || fsh.RequireBuffer || fsh.UUID == "tmp" || fsh.Hierarchy == "backup" {
  128. return none, errors.New("Syncthing can only keep folders on a local disk")
  129. }
  130. if fsh.ReadOnly || !userinfo.CanWrite(vpath) {
  131. return none, errors.New("You cannot write to this folder")
  132. }
  133. fshAbs := fsh.FileSystemAbstraction
  134. rpath, err := fshAbs.VirtualPathToRealPath(vpath, username)
  135. if err != nil {
  136. return none, err
  137. }
  138. root, err := fshAbs.VirtualPathToRealPath(fsh.UUID+":/", username)
  139. if err != nil {
  140. return none, err
  141. }
  142. if create && !fshAbs.FileExists(rpath) {
  143. if err := fshAbs.MkdirAll(rpath, 0775); err != nil {
  144. return none, errors.New("The folder could not be created")
  145. }
  146. }
  147. if !fshAbs.IsDir(rpath) {
  148. return none, errors.New("This folder does not exist")
  149. }
  150. resolved, err := resolvedAbs(rpath)
  151. if err != nil {
  152. return none, err
  153. }
  154. resolvedRoot, err := resolvedAbs(root)
  155. if err != nil {
  156. return none, err
  157. }
  158. if !pathWithin(resolved, resolvedRoot) {
  159. return none, errors.New("This folder leads outside its drive")
  160. }
  161. if system, err := resolvedAbs("system"); err == nil && (pathWithin(resolved, system) || pathWithin(system, resolved)) {
  162. return none, errors.New("Syncthing cannot use the system folder")
  163. }
  164. location := syncthingserv.Location{RealPath: resolved}
  165. if fsh.Hierarchy == "user" && userinfo.StorageQuota != nil {
  166. location.Quota = syncthingQuota{q: userinfo.StorageQuota}
  167. }
  168. return location, nil
  169. }
  170. func resolvedAbs(p string) (string, error) {
  171. resolved, err := filepath.EvalSymlinks(p)
  172. if err != nil {
  173. return "", err
  174. }
  175. return filepath.Abs(resolved)
  176. }
  177. // pathWithin reports p being dir or inside it.
  178. func pathWithin(p, dir string) bool {
  179. p, dir = filepath.Clean(p), filepath.Clean(dir)
  180. if strings.EqualFold(p, dir) {
  181. return p == dir || filepath.Separator == '\\'
  182. }
  183. prefix := strings.TrimSuffix(dir, string(filepath.Separator)) + string(filepath.Separator)
  184. if filepath.Separator == '\\' {
  185. return strings.HasPrefix(strings.ToLower(p), strings.ToLower(prefix))
  186. }
  187. return strings.HasPrefix(p, prefix)
  188. }