syncserver.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package main
  2. import (
  3. "errors"
  4. "io"
  5. "net/http"
  6. "os"
  7. "path/filepath"
  8. "strings"
  9. "imuslab.com/arozos/mod/fileservers"
  10. "imuslab.com/arozos/mod/fileservers/servers/syncserv"
  11. fs "imuslab.com/arozos/mod/filesystem"
  12. "imuslab.com/arozos/mod/filesystem/arozfs"
  13. "imuslab.com/arozos/mod/network"
  14. prout "imuslab.com/arozos/mod/prouter"
  15. user "imuslab.com/arozos/mod/user"
  16. )
  17. /*
  18. syncserver.go
  19. Wires the Sync Server into the file server list: an upload endpoint for
  20. phone automations, such as an iOS Shortcut that sends the photos of the
  21. last days every night. An admin turns it on, picks the groups that may
  22. use it and the largest file. Each of those users turns it on for their
  23. account, picks a folder of their drives and how uploads are sorted in it.
  24. See mod/fileservers/servers/syncserv.
  25. */
  26. // SyncServerManager is nil when the manager could not start.
  27. var SyncServerManager *syncserv.Manager
  28. // SyncServerInit sets up the manager, its endpoints and its list entry.
  29. func SyncServerInit(router, adminRouter *prout.RouterDef) {
  30. var err error
  31. SyncServerManager, err = syncserv.NewManager(&syncserv.ManagerOption{
  32. Sysdb: sysdb,
  33. //The tmp folder is emptied at every boot, which clears what an
  34. //interrupted upload left
  35. SpoolDir: filepath.Join(*tmp_directory, "syncserver"),
  36. CurrentUser: fileServerCurrentUser,
  37. ConfirmPassword: func(w http.ResponseWriter, r *http.Request) bool {
  38. return AuthValidateSecureRequest(w, r, false)
  39. },
  40. CheckLoginPassword: func(username, password string) bool {
  41. ok, _ := authAgent.ValidateUsernameAndPasswordWithReason(username, password)
  42. return ok
  43. },
  44. AllowIP: func(ip string) error {
  45. if allowed, err := authAgent.ValidateLoginIpAccess(ip); !allowed {
  46. if err == nil {
  47. err = errors.New("This address may not sign in")
  48. }
  49. return err
  50. }
  51. return nil
  52. },
  53. ClientIP: func(r *http.Request) string {
  54. ip, _ := network.GetIpFromRequest(r)
  55. return ip
  56. },
  57. LogAuth: fileServerLogAuth("syncserver"),
  58. UserExists: authAgent.UserExists,
  59. IsAdmin: func(username string) bool {
  60. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  61. return err == nil && userinfo.IsAdmin()
  62. },
  63. InGroups: func(username string, groups []string) bool {
  64. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  65. return err == nil && userinfo.UserIsInOneOfTheGroupOf(groups)
  66. },
  67. ListGroups: func() []string {
  68. names := []string{}
  69. for _, group := range permissionHandler.PermissionGroups {
  70. names = append(names, group.Name)
  71. }
  72. return names
  73. },
  74. OpenFolder: syncServerOpenFolder,
  75. })
  76. if err != nil {
  77. systemWideLogger.PrintAndLog("Sync Server", "The Sync Server is not available", err)
  78. SyncServerManager = nil
  79. return
  80. }
  81. //Deliberately outside the session router: phone automations sign in
  82. //with the Username and Authorization headers of every request, which
  83. //HandleUpload checks itself (sync password, login IP rules, wrong
  84. //password delays, login history)
  85. http.HandleFunc(syncserv.UploadPath, SyncServerManager.HandleUpload)
  86. //Any other address below it (a typo in the shortcut, a trailing slash)
  87. //gets an answer that says so, instead of the login page
  88. http.HandleFunc(syncserv.UploadPrefix, SyncServerManager.HandleOtherPath)
  89. router.HandleFunc("/system/storage/syncserver/status", SyncServerManager.HandleStatus)
  90. router.HandleFunc("/system/storage/syncserver/activate", SyncServerManager.HandleActivate)
  91. router.HandleFunc("/system/storage/syncserver/settings", SyncServerManager.HandleSettings)
  92. router.HandleFunc("/system/storage/syncserver/password", SyncServerManager.HandlePassword)
  93. router.HandleFunc("/system/storage/syncserver/deactivate", SyncServerManager.HandleDeactivate)
  94. router.HandleFunc("/system/storage/syncserver/forget", SyncServerManager.HandleForget)
  95. adminRouter.HandleFunc("/system/storage/syncserver/config", SyncServerManager.HandleConfig)
  96. adminRouter.HandleFunc("/system/storage/syncserver/users", SyncServerManager.HandleUsers)
  97. adminRouter.HandleFunc("/system/storage/syncserver/revoke", SyncServerManager.HandleRevoke)
  98. networkFileServerDaemon = append(networkFileServerDaemon, &fileservers.Server{
  99. ID: "syncserver",
  100. Name: "Sync Server",
  101. Desc: "Receive photos and files from phone automations",
  102. IconPath: "img/system/network-folder-syncserver.svg",
  103. DefaultPorts: []int{},
  104. Ports: []int{},
  105. ForwardPortIfUpnp: false, //Served on the web server port
  106. ConnInstrPage: "SystemAO/disk/instr/syncserver.html",
  107. ConfigPage: "SystemAO/disk/syncserver.html",
  108. EnableCheck: SyncServerManager.IsEnabled,
  109. ToggleFunc: SyncServerManager.ServerToggle,
  110. GetEndpoints: SyncServerManager.GetEndpoints,
  111. })
  112. }
  113. // syncFolder is a folder of a user's drives that uploads go to.
  114. type syncFolder struct {
  115. userinfo *user.User
  116. fsh *fs.FileSystemHandler
  117. base string //Virtual path of the folder
  118. //The drive is a folder on a local disk: a received file is renamed into
  119. //place, and only copied when it is on another disk
  120. local bool
  121. }
  122. // syncServerOpenFolder checks a folder a user picked for uploads: the drive
  123. // is there and mounted, and the user can write to the folder.
  124. func syncServerOpenFolder(username, vpath string) (syncserv.Folder, error) {
  125. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  126. if err != nil {
  127. return nil, err
  128. }
  129. fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  130. if err != nil {
  131. return nil, errors.New("This drive cannot be found")
  132. }
  133. if fsh.Closed {
  134. return nil, errors.New("This drive is not mounted")
  135. }
  136. if fsh.ReadOnly || !userinfo.CanWrite(vpath) {
  137. return nil, errors.New("You cannot write to this folder")
  138. }
  139. fshAbs := fsh.FileSystemAbstraction
  140. rpath, err := fshAbs.VirtualPathToRealPath(vpath, username)
  141. if err != nil {
  142. return nil, errors.New("This folder cannot be used")
  143. }
  144. if fshAbs.FileExists(rpath) && !fshAbs.IsDir(rpath) {
  145. return nil, errors.New("This is a file, not a folder")
  146. }
  147. return &syncFolder{
  148. userinfo: userinfo,
  149. fsh: fsh,
  150. base: vpath,
  151. local: !fsh.RequireBuffer && !arozfs.IsNetworkDrive(fsh.Filesystem),
  152. }, nil
  153. }
  154. func (f *syncFolder) VirtualPath(rel string) string {
  155. return strings.TrimSuffix(f.base, "/") + "/" + rel
  156. }
  157. func (f *syncFolder) realPath(rel string) (string, error) {
  158. return f.fsh.FileSystemAbstraction.VirtualPathToRealPath(f.VirtualPath(rel), f.userinfo.Username)
  159. }
  160. func (f *syncFolder) Stat(rel string) (bool, bool, int64) {
  161. rpath, err := f.realPath(rel)
  162. if err != nil {
  163. return false, false, 0
  164. }
  165. info, err := f.fsh.FileSystemAbstraction.Stat(rpath)
  166. if err != nil {
  167. return false, false, 0
  168. }
  169. return true, info.IsDir(), info.Size()
  170. }
  171. func (f *syncFolder) Open(rel string) (io.ReadCloser, error) {
  172. rpath, err := f.realPath(rel)
  173. if err != nil {
  174. return nil, err
  175. }
  176. return f.fsh.FileSystemAbstraction.ReadStream(rpath)
  177. }
  178. func (f *syncFolder) HaveSpace(size int64) bool {
  179. if size <= 0 || f.fsh.Hierarchy != "user" || f.userinfo.StorageQuota == nil {
  180. return true
  181. }
  182. return f.userinfo.StorageQuota.HaveSpace(size)
  183. }
  184. func (f *syncFolder) Place(spool string, rel string) error {
  185. vpath := f.VirtualPath(rel)
  186. //Access is asked on every write: a group or drive rule may have changed
  187. //since the folder was picked
  188. if !f.userinfo.CanWrite(vpath) {
  189. return errors.New("You cannot write to this folder")
  190. }
  191. fshAbs := f.fsh.FileSystemAbstraction
  192. rpath, err := f.realPath(rel)
  193. if err != nil {
  194. return err
  195. }
  196. dir := arozfs.ToSlash(filepath.Dir(rpath))
  197. if !fshAbs.FileExists(dir) {
  198. if err := fshAbs.MkdirAll(dir, 0775); err != nil {
  199. return err
  200. }
  201. }
  202. if fshAbs.FileExists(rpath) {
  203. //The quota no longer counts the file being replaced
  204. f.userinfo.RemoveOwnershipFromFile(f.fsh, vpath)
  205. }
  206. placed := false
  207. if f.local {
  208. if err := os.Rename(spool, rpath); err == nil {
  209. os.Chmod(rpath, 0664)
  210. placed = true
  211. }
  212. }
  213. if !placed {
  214. src, err := os.Open(spool)
  215. if err != nil {
  216. return err
  217. }
  218. err = fshAbs.WriteStream(rpath, src, 0775)
  219. src.Close()
  220. if err != nil {
  221. fshAbs.Remove(rpath)
  222. return err
  223. }
  224. }
  225. f.userinfo.SetOwnerOfFile(f.fsh, vpath)
  226. return nil
  227. }