smbfs.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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. go func() {
  147. a.tickerChan <- true
  148. }()
  149. //Unmount the smb folder
  150. time.Sleep(300 * time.Millisecond)
  151. a.share.Umount()
  152. time.Sleep(300 * time.Millisecond)
  153. a.session.Logoff()
  154. time.Sleep(300 * time.Millisecond)
  155. conn := *(a.conn)
  156. conn.Close()
  157. return nil
  158. }
  159. /*
  160. Abstraction Utilities
  161. */
  162. func (a ServerMessageBlockFileSystemAbstraction) VirtualPathToRealPath(subpath string, username string) (string, error) {
  163. if strings.HasPrefix(subpath, a.UUID+":") {
  164. //This is full virtual path. Trim the uuid and correct the subpath
  165. subpath = strings.TrimPrefix(subpath, a.UUID+":")
  166. }
  167. subpath = filterFilepath(subpath)
  168. if a.Hierarchy == "user" {
  169. return toWinPath(filepath.ToSlash(filepath.Clean(filepath.Join("users", username, subpath)))), nil
  170. } else if a.Hierarchy == "public" {
  171. return toWinPath(filepath.ToSlash(filepath.Clean(subpath))), nil
  172. }
  173. return "", arozfs.ErrVpathResolveFailed
  174. }
  175. func (a ServerMessageBlockFileSystemAbstraction) RealPathToVirtualPath(fullpath string, username string) (string, error) {
  176. fullpath = filterFilepath(fullpath)
  177. fullpath = strings.TrimPrefix(fullpath, "\\")
  178. vpath := a.UUID + ":/" + strings.ReplaceAll(fullpath, "\\", "/")
  179. return vpath, nil
  180. }
  181. func (a ServerMessageBlockFileSystemAbstraction) FileExists(realpath string) bool {
  182. realpath = toWinPath(filterFilepath(realpath))
  183. f, err := a.share.Open(realpath)
  184. if err != nil {
  185. return false
  186. }
  187. f.Close()
  188. return true
  189. }
  190. func (a ServerMessageBlockFileSystemAbstraction) IsDir(realpath string) bool {
  191. realpath = filterFilepath(realpath)
  192. realpath = toWinPath(realpath)
  193. stx, err := a.share.Stat(realpath)
  194. if err != nil {
  195. return false
  196. }
  197. return stx.IsDir()
  198. }
  199. func (a ServerMessageBlockFileSystemAbstraction) Glob(realpathWildcard string) ([]string, error) {
  200. realpathWildcard = strings.ReplaceAll(realpathWildcard, "[", "?")
  201. realpathWildcard = strings.ReplaceAll(realpathWildcard, "]", "?")
  202. matches, err := a.share.Glob(realpathWildcard)
  203. if err != nil {
  204. return []string{}, err
  205. }
  206. return matches, nil
  207. }
  208. func (a ServerMessageBlockFileSystemAbstraction) GetFileSize(realpath string) int64 {
  209. realpath = toWinPath(filterFilepath(realpath))
  210. stat, err := a.share.Stat(realpath)
  211. if err != nil {
  212. return 0
  213. }
  214. return stat.Size()
  215. }
  216. func (a ServerMessageBlockFileSystemAbstraction) GetModTime(realpath string) (int64, error) {
  217. realpath = toWinPath(filterFilepath(realpath))
  218. stat, err := a.share.Stat(realpath)
  219. if err != nil {
  220. return 0, nil
  221. }
  222. return stat.ModTime().Unix(), nil
  223. }
  224. func (a ServerMessageBlockFileSystemAbstraction) WriteFile(filename string, content []byte, mode os.FileMode) error {
  225. filename = toWinPath(filterFilepath(filename))
  226. return a.share.WriteFile(filename, content, mode)
  227. }
  228. func (a ServerMessageBlockFileSystemAbstraction) ReadFile(filename string) ([]byte, error) {
  229. filename = toWinPath(filterFilepath(filename))
  230. return a.share.ReadFile(filename)
  231. }
  232. func (a ServerMessageBlockFileSystemAbstraction) ReadDir(filename string) ([]fs.DirEntry, error) {
  233. filename = toWinPath(filterFilepath(filename))
  234. fis, err := a.share.ReadDir(filename)
  235. if err != nil {
  236. return []fs.DirEntry{}, err
  237. }
  238. dirEntires := []fs.DirEntry{}
  239. for _, fi := range fis {
  240. if fi.Name() == "System Volume Information" || fi.Name() == "$RECYCLE.BIN" || fi.Name() == "$MFT" {
  241. //System folders. Hide it
  242. continue
  243. }
  244. dirEntires = append(dirEntires, newDirEntryFromFileInfo(fi))
  245. }
  246. return dirEntires, nil
  247. }
  248. func (a ServerMessageBlockFileSystemAbstraction) WriteStream(filename string, stream io.Reader, mode os.FileMode) error {
  249. filename = toWinPath(filterFilepath(filename))
  250. f, err := a.share.OpenFile(filename, os.O_CREATE|os.O_WRONLY, mode)
  251. if err != nil {
  252. return err
  253. }
  254. p := make([]byte, 32768)
  255. for {
  256. _, err := stream.Read(p)
  257. if err != nil {
  258. if err == io.EOF {
  259. break
  260. } else {
  261. return err
  262. }
  263. }
  264. _, err = f.Write(p)
  265. if err != nil {
  266. return err
  267. }
  268. }
  269. return nil
  270. }
  271. func (a ServerMessageBlockFileSystemAbstraction) ReadStream(filename string) (io.ReadCloser, error) {
  272. filename = toWinPath(filterFilepath(filename))
  273. f, err := a.share.OpenFile(filename, os.O_RDONLY, 0755)
  274. if err != nil {
  275. return nil, err
  276. }
  277. return f, nil
  278. }
  279. //Note that walk on SMB is super slow. Avoid using this if possible.
  280. func (a ServerMessageBlockFileSystemAbstraction) Walk(root string, walkFn filepath.WalkFunc) error {
  281. root = toWinPath(filterFilepath(root))
  282. err := fs.WalkDir(a.share.DirFS(root), ".", func(path string, d fs.DirEntry, err error) error {
  283. if err != nil {
  284. return err
  285. }
  286. statInfo, err := d.Info()
  287. if err != nil {
  288. return err
  289. }
  290. walkFn(filepath.ToSlash(filepath.Join(root, path)), statInfo, err)
  291. return nil
  292. })
  293. return err
  294. }
  295. func (a ServerMessageBlockFileSystemAbstraction) Heartbeat() error {
  296. _, err := a.share.Stat("")
  297. return err
  298. }
  299. /*
  300. Optional Functions
  301. */
  302. func (a *ServerMessageBlockFileSystemAbstraction) CapacityInfo() {
  303. fsinfo, err := a.share.Statfs(".")
  304. if err != nil {
  305. return
  306. }
  307. fmt.Println(fsinfo)
  308. }
  309. /*
  310. Helper Functions
  311. */
  312. func toWinPath(filename string) string {
  313. backslashed := strings.ReplaceAll(filename, "/", "\\")
  314. return strings.TrimPrefix(backslashed, "\\")
  315. }
  316. func filterFilepath(rawpath string) string {
  317. rawpath = filepath.ToSlash(filepath.Clean(rawpath))
  318. rawpath = strings.TrimSpace(rawpath)
  319. if strings.HasPrefix(rawpath, "./") {
  320. return rawpath[1:]
  321. } else if rawpath == "." || rawpath == "" {
  322. return "/"
  323. }
  324. return rawpath
  325. }
  326. func wildCardToRegexp(pattern string) string {
  327. var result strings.Builder
  328. for i, literal := range strings.Split(pattern, "*") {
  329. // Replace * with .*
  330. if i > 0 {
  331. result.WriteString(".*")
  332. }
  333. // Quote any regular expression meta characters in the
  334. // literal text.
  335. result.WriteString(regexp.QuoteMeta(literal))
  336. }
  337. return result.String()
  338. }