smbfs.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. package smbfs
  2. import (
  3. "fmt"
  4. "io"
  5. "io/fs"
  6. "log"
  7. "net"
  8. "os"
  9. "path/filepath"
  10. "regexp"
  11. "strings"
  12. "time"
  13. "github.com/hirochachacha/go-smb2"
  14. "imuslab.com/arozos/mod/filesystem/arozfs"
  15. )
  16. /*
  17. Server Message Block.go
  18. This is a file abstraction that mount SMB folders onto ArozOS as virtual drive
  19. */
  20. type ServerMessageBlockFileSystemAbstraction struct {
  21. UUID string
  22. Hierarchy string
  23. root string
  24. ipaddr string
  25. user string
  26. pass string
  27. conn *net.Conn
  28. session *smb2.Session
  29. share *smb2.Share
  30. tickerChan chan bool
  31. }
  32. func NewServerMessageBlockFileSystemAbstraction(uuid string, hierarchy string, ipaddr string, rootShare string, username string, password string) (ServerMessageBlockFileSystemAbstraction, error) {
  33. log.Println("[SMB-FS] Connecting to " + uuid + ":/ (" + ipaddr + ")")
  34. nd := net.Dialer{Timeout: 10 * time.Second}
  35. conn, err := nd.Dial("tcp", ipaddr)
  36. if err != nil {
  37. log.Println("[SMB-FS] Unable to connect to remote: ", err.Error())
  38. return ServerMessageBlockFileSystemAbstraction{}, err
  39. }
  40. d := &smb2.Dialer{
  41. Initiator: &smb2.NTLMInitiator{
  42. User: username,
  43. Password: password,
  44. },
  45. }
  46. s, err := d.Dial(conn)
  47. if err != nil {
  48. log.Println("[SMB-FS] Unable to connect to remote: ", err.Error())
  49. return ServerMessageBlockFileSystemAbstraction{}, err
  50. }
  51. //Mound remote storage
  52. fs, err := s.Mount(rootShare)
  53. if err != nil {
  54. log.Println("[SMB-FS] Unable to connect to remote: ", err.Error())
  55. return ServerMessageBlockFileSystemAbstraction{}, err
  56. }
  57. done := make(chan bool)
  58. fsAbstraction := ServerMessageBlockFileSystemAbstraction{
  59. UUID: uuid,
  60. Hierarchy: hierarchy,
  61. root: rootShare,
  62. ipaddr: ipaddr,
  63. user: username,
  64. pass: password,
  65. conn: &conn,
  66. session: s,
  67. share: fs,
  68. tickerChan: done,
  69. }
  70. return fsAbstraction, nil
  71. }
  72. func (a ServerMessageBlockFileSystemAbstraction) Chmod(filename string, mode os.FileMode) error {
  73. filename = filterFilepath(filename)
  74. filename = toWinPath(filename)
  75. return a.share.Chmod(filename, mode)
  76. }
  77. func (a ServerMessageBlockFileSystemAbstraction) Chown(filename string, uid int, gid int) error {
  78. return arozfs.ErrOperationNotSupported
  79. }
  80. func (a ServerMessageBlockFileSystemAbstraction) Chtimes(filename string, atime time.Time, mtime time.Time) error {
  81. filename = filterFilepath(filename)
  82. filename = toWinPath(filename)
  83. return a.share.Chtimes(filename, atime, mtime)
  84. }
  85. func (a ServerMessageBlockFileSystemAbstraction) Create(filename string) (arozfs.File, error) {
  86. filename = filterFilepath(filename)
  87. f, err := a.share.Create(filename)
  88. if err != nil {
  89. return nil, err
  90. }
  91. af := NewSmbFsFile(f)
  92. return af, nil
  93. }
  94. func (a ServerMessageBlockFileSystemAbstraction) Mkdir(filename string, mode os.FileMode) error {
  95. filename = filterFilepath(filename)
  96. filename = toWinPath(filename)
  97. return a.share.Mkdir(filename, mode)
  98. }
  99. func (a ServerMessageBlockFileSystemAbstraction) MkdirAll(filename string, mode os.FileMode) error {
  100. filename = filterFilepath(filename)
  101. filename = toWinPath(filename)
  102. return a.share.MkdirAll(filename, mode)
  103. }
  104. func (a ServerMessageBlockFileSystemAbstraction) Name() string {
  105. return ""
  106. }
  107. func (a ServerMessageBlockFileSystemAbstraction) Open(filename string) (arozfs.File, error) {
  108. filename = toWinPath(filterFilepath(filename))
  109. f, err := a.share.Open(filename)
  110. if err != nil {
  111. return nil, err
  112. }
  113. af := NewSmbFsFile(f)
  114. return af, nil
  115. }
  116. func (a ServerMessageBlockFileSystemAbstraction) OpenFile(filename string, flag int, perm os.FileMode) (arozfs.File, error) {
  117. filename = toWinPath(filterFilepath(filename))
  118. f, err := a.share.OpenFile(filename, flag, perm)
  119. if err != nil {
  120. return nil, err
  121. }
  122. af := NewSmbFsFile(f)
  123. return af, nil
  124. }
  125. func (a ServerMessageBlockFileSystemAbstraction) Remove(filename string) error {
  126. filename = filterFilepath(filename)
  127. filename = toWinPath(filename)
  128. return a.share.Remove(filename)
  129. }
  130. func (a ServerMessageBlockFileSystemAbstraction) RemoveAll(filename string) error {
  131. filename = filterFilepath(filename)
  132. filename = toWinPath(filename)
  133. return a.share.RemoveAll(filename)
  134. }
  135. func (a ServerMessageBlockFileSystemAbstraction) Rename(oldname, newname string) error {
  136. oldname = toWinPath(filterFilepath(oldname))
  137. newname = toWinPath(filterFilepath(newname))
  138. return a.share.Rename(oldname, newname)
  139. }
  140. func (a ServerMessageBlockFileSystemAbstraction) Stat(filename string) (os.FileInfo, error) {
  141. filename = toWinPath(filterFilepath(filename))
  142. return a.share.Stat(filename)
  143. }
  144. func (a ServerMessageBlockFileSystemAbstraction) Close() error {
  145. //Stop connection checker
  146. a.tickerChan <- true
  147. //Unmount the smb folder
  148. a.share.Umount()
  149. a.session.Logoff()
  150. conn := *(a.conn)
  151. conn.Close()
  152. return nil
  153. }
  154. /*
  155. Abstraction Utilities
  156. */
  157. func (a ServerMessageBlockFileSystemAbstraction) VirtualPathToRealPath(subpath string, username string) (string, error) {
  158. if strings.HasPrefix(subpath, a.UUID+":") {
  159. //This is full virtual path. Trim the uuid and correct the subpath
  160. subpath = strings.TrimPrefix(subpath, a.UUID+":")
  161. }
  162. subpath = filterFilepath(subpath)
  163. if a.Hierarchy == "user" {
  164. return toWinPath(filepath.ToSlash(filepath.Clean(filepath.Join("users", username, subpath)))), nil
  165. } else if a.Hierarchy == "public" {
  166. return toWinPath(filepath.ToSlash(filepath.Clean(subpath))), nil
  167. }
  168. return "", arozfs.ErrVpathResolveFailed
  169. }
  170. func (a ServerMessageBlockFileSystemAbstraction) RealPathToVirtualPath(fullpath string, username string) (string, error) {
  171. fullpath = filterFilepath(fullpath)
  172. fullpath = strings.TrimPrefix(fullpath, "\\")
  173. vpath := a.UUID + ":/" + strings.ReplaceAll(fullpath, "\\", "/")
  174. return vpath, nil
  175. }
  176. func (a ServerMessageBlockFileSystemAbstraction) FileExists(realpath string) bool {
  177. realpath = toWinPath(filterFilepath(realpath))
  178. f, err := a.share.Open(realpath)
  179. if err != nil {
  180. return false
  181. }
  182. f.Close()
  183. return true
  184. }
  185. func (a ServerMessageBlockFileSystemAbstraction) IsDir(realpath string) bool {
  186. realpath = filterFilepath(realpath)
  187. realpath = toWinPath(realpath)
  188. stx, err := a.share.Stat(realpath)
  189. if err != nil {
  190. return false
  191. }
  192. return stx.IsDir()
  193. }
  194. func (a ServerMessageBlockFileSystemAbstraction) Glob(realpathWildcard string) ([]string, error) {
  195. realpathWildcard = strings.ReplaceAll(realpathWildcard, "[", "?")
  196. realpathWildcard = strings.ReplaceAll(realpathWildcard, "]", "?")
  197. matches, err := a.share.Glob(realpathWildcard)
  198. if err != nil {
  199. return []string{}, err
  200. }
  201. return matches, nil
  202. }
  203. func (a ServerMessageBlockFileSystemAbstraction) GetFileSize(realpath string) int64 {
  204. realpath = toWinPath(filterFilepath(realpath))
  205. stat, err := a.share.Stat(realpath)
  206. if err != nil {
  207. return 0
  208. }
  209. return stat.Size()
  210. }
  211. func (a ServerMessageBlockFileSystemAbstraction) GetModTime(realpath string) (int64, error) {
  212. realpath = toWinPath(filterFilepath(realpath))
  213. stat, err := a.share.Stat(realpath)
  214. if err != nil {
  215. return 0, nil
  216. }
  217. return stat.ModTime().Unix(), nil
  218. }
  219. func (a ServerMessageBlockFileSystemAbstraction) WriteFile(filename string, content []byte, mode os.FileMode) error {
  220. filename = toWinPath(filterFilepath(filename))
  221. return a.share.WriteFile(filename, content, mode)
  222. }
  223. func (a ServerMessageBlockFileSystemAbstraction) ReadFile(filename string) ([]byte, error) {
  224. filename = toWinPath(filterFilepath(filename))
  225. return a.share.ReadFile(filename)
  226. }
  227. func (a ServerMessageBlockFileSystemAbstraction) ReadDir(filename string) ([]fs.DirEntry, error) {
  228. filename = toWinPath(filterFilepath(filename))
  229. fis, err := a.share.ReadDir(filename)
  230. if err != nil {
  231. return []fs.DirEntry{}, err
  232. }
  233. dirEntires := []fs.DirEntry{}
  234. for _, fi := range fis {
  235. if fi.Name() == "System Volume Information" || fi.Name() == "$RECYCLE.BIN" || fi.Name() == "$MFT" {
  236. //System folders. Hide it
  237. continue
  238. }
  239. dirEntires = append(dirEntires, newDirEntryFromFileInfo(fi))
  240. }
  241. return dirEntires, nil
  242. }
  243. func (a ServerMessageBlockFileSystemAbstraction) WriteStream(filename string, stream io.Reader, mode os.FileMode) error {
  244. filename = toWinPath(filterFilepath(filename))
  245. f, err := a.share.OpenFile(filename, os.O_CREATE|os.O_WRONLY, mode)
  246. if err != nil {
  247. return err
  248. }
  249. p := make([]byte, 32768)
  250. for {
  251. _, err := stream.Read(p)
  252. if err != nil {
  253. if err == io.EOF {
  254. break
  255. } else {
  256. return err
  257. }
  258. }
  259. _, err = f.Write(p)
  260. if err != nil {
  261. return err
  262. }
  263. }
  264. return nil
  265. }
  266. func (a ServerMessageBlockFileSystemAbstraction) ReadStream(filename string) (io.ReadCloser, error) {
  267. filename = toWinPath(filterFilepath(filename))
  268. f, err := a.share.OpenFile(filename, os.O_RDONLY, 0755)
  269. if err != nil {
  270. return nil, err
  271. }
  272. return f, nil
  273. }
  274. //Note that walk on SMB is super slow. Avoid using this if possible.
  275. func (a ServerMessageBlockFileSystemAbstraction) Walk(root string, walkFn filepath.WalkFunc) error {
  276. root = toWinPath(filterFilepath(root))
  277. err := fs.WalkDir(a.share.DirFS(root), ".", func(path string, d fs.DirEntry, err error) error {
  278. if err != nil {
  279. return err
  280. }
  281. statInfo, err := d.Info()
  282. if err != nil {
  283. return err
  284. }
  285. walkFn(filepath.ToSlash(filepath.Join(root, path)), statInfo, err)
  286. return nil
  287. })
  288. return err
  289. }
  290. func (a ServerMessageBlockFileSystemAbstraction) Heartbeat() error {
  291. _, err := a.share.Stat("")
  292. return err
  293. }
  294. /*
  295. Optional Functions
  296. */
  297. func (a *ServerMessageBlockFileSystemAbstraction) CapacityInfo() {
  298. fsinfo, err := a.share.Statfs(".")
  299. if err != nil {
  300. return
  301. }
  302. fmt.Println(fsinfo)
  303. }
  304. /*
  305. Helper Functions
  306. */
  307. func toWinPath(filename string) string {
  308. backslashed := strings.ReplaceAll(filename, "/", "\\")
  309. return strings.TrimPrefix(backslashed, "\\")
  310. }
  311. func filterFilepath(rawpath string) string {
  312. rawpath = filepath.ToSlash(filepath.Clean(rawpath))
  313. rawpath = strings.TrimSpace(rawpath)
  314. if strings.HasPrefix(rawpath, "./") {
  315. return rawpath[1:]
  316. } else if rawpath == "." || rawpath == "" {
  317. return "/"
  318. }
  319. return rawpath
  320. }
  321. func wildCardToRegexp(pattern string) string {
  322. var result strings.Builder
  323. for i, literal := range strings.Split(pattern, "*") {
  324. // Replace * with .*
  325. if i > 0 {
  326. result.WriteString(".*")
  327. }
  328. // Quote any regular expression meta characters in the
  329. // literal text.
  330. result.WriteString(regexp.QuoteMeta(literal))
  331. }
  332. return result.String()
  333. }