smbfs.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. //Create a ticker to check for renewing conncetion once an hour
  71. ticker := time.NewTicker(1 * time.Hour)
  72. go func(s *ServerMessageBlockFileSystemAbstraction) {
  73. for {
  74. select {
  75. case <-done:
  76. return
  77. case <-ticker.C:
  78. //Unable to list share due to session timeout. Close the handler and try connecting again.
  79. s.share.Umount()
  80. time.Sleep(300 * time.Millisecond)
  81. fs, err := s.session.Mount(s.root)
  82. if err != nil {
  83. fmt.Println("[SMBFS] Unable to remount " + s.root)
  84. return
  85. }
  86. fmt.Println("[SMBFS] Session Renewed for " + s.root)
  87. s.share = fs
  88. }
  89. }
  90. }(&fsAbstraction)
  91. log.Println("[SMB-FS] Connected to remote: " + ipaddr)
  92. return fsAbstraction, nil
  93. }
  94. func (a ServerMessageBlockFileSystemAbstraction) Chmod(filename string, mode os.FileMode) error {
  95. filename = filterFilepath(filename)
  96. filename = toWinPath(filename)
  97. return a.share.Chmod(filename, mode)
  98. }
  99. func (a ServerMessageBlockFileSystemAbstraction) Chown(filename string, uid int, gid int) error {
  100. return arozfs.ErrOperationNotSupported
  101. }
  102. func (a ServerMessageBlockFileSystemAbstraction) Chtimes(filename string, atime time.Time, mtime time.Time) error {
  103. filename = filterFilepath(filename)
  104. filename = toWinPath(filename)
  105. return a.share.Chtimes(filename, atime, mtime)
  106. }
  107. func (a ServerMessageBlockFileSystemAbstraction) Create(filename string) (arozfs.File, error) {
  108. filename = filterFilepath(filename)
  109. f, err := a.share.Create(filename)
  110. if err != nil {
  111. return nil, err
  112. }
  113. af := NewSmbFsFile(f)
  114. return af, nil
  115. }
  116. func (a ServerMessageBlockFileSystemAbstraction) Mkdir(filename string, mode os.FileMode) error {
  117. filename = filterFilepath(filename)
  118. filename = toWinPath(filename)
  119. return a.share.Mkdir(filename, mode)
  120. }
  121. func (a ServerMessageBlockFileSystemAbstraction) MkdirAll(filename string, mode os.FileMode) error {
  122. filename = filterFilepath(filename)
  123. filename = toWinPath(filename)
  124. return a.share.MkdirAll(filename, mode)
  125. }
  126. func (a ServerMessageBlockFileSystemAbstraction) Name() string {
  127. return ""
  128. }
  129. func (a ServerMessageBlockFileSystemAbstraction) Open(filename string) (arozfs.File, error) {
  130. filename = toWinPath(filterFilepath(filename))
  131. f, err := a.share.Open(filename)
  132. if err != nil {
  133. return nil, err
  134. }
  135. af := NewSmbFsFile(f)
  136. return af, nil
  137. }
  138. func (a ServerMessageBlockFileSystemAbstraction) OpenFile(filename string, flag int, perm os.FileMode) (arozfs.File, error) {
  139. filename = toWinPath(filterFilepath(filename))
  140. f, err := a.share.OpenFile(filename, flag, perm)
  141. if err != nil {
  142. return nil, err
  143. }
  144. af := NewSmbFsFile(f)
  145. return af, nil
  146. }
  147. func (a ServerMessageBlockFileSystemAbstraction) Remove(filename string) error {
  148. filename = filterFilepath(filename)
  149. filename = toWinPath(filename)
  150. return a.share.Remove(filename)
  151. }
  152. func (a ServerMessageBlockFileSystemAbstraction) RemoveAll(filename string) error {
  153. filename = filterFilepath(filename)
  154. filename = toWinPath(filename)
  155. return a.share.RemoveAll(filename)
  156. }
  157. func (a ServerMessageBlockFileSystemAbstraction) Rename(oldname, newname string) error {
  158. oldname = toWinPath(filterFilepath(oldname))
  159. newname = toWinPath(filterFilepath(newname))
  160. return a.share.Rename(oldname, newname)
  161. }
  162. func (a ServerMessageBlockFileSystemAbstraction) Stat(filename string) (os.FileInfo, error) {
  163. filename = toWinPath(filterFilepath(filename))
  164. return a.share.Stat(filename)
  165. }
  166. func (a ServerMessageBlockFileSystemAbstraction) Close() error {
  167. a.tickerChan <- true
  168. a.share.Umount()
  169. a.session.Logoff()
  170. conn := *(a.conn)
  171. conn.Close()
  172. return nil
  173. }
  174. /*
  175. Abstraction Utilities
  176. */
  177. func (a ServerMessageBlockFileSystemAbstraction) VirtualPathToRealPath(subpath string, username string) (string, error) {
  178. if strings.HasPrefix(subpath, a.UUID+":") {
  179. //This is full virtual path. Trim the uuid and correct the subpath
  180. subpath = strings.TrimPrefix(subpath, a.UUID+":")
  181. }
  182. subpath = filterFilepath(subpath)
  183. if a.Hierarchy == "user" {
  184. return toWinPath(filepath.ToSlash(filepath.Clean(filepath.Join("users", username, subpath)))), nil
  185. } else if a.Hierarchy == "public" {
  186. return toWinPath(filepath.ToSlash(filepath.Clean(subpath))), nil
  187. }
  188. return "", arozfs.ErrVpathResolveFailed
  189. }
  190. func (a ServerMessageBlockFileSystemAbstraction) RealPathToVirtualPath(fullpath string, username string) (string, error) {
  191. fullpath = filterFilepath(fullpath)
  192. fullpath = strings.TrimPrefix(fullpath, "\\")
  193. vpath := a.UUID + ":/" + strings.ReplaceAll(fullpath, "\\", "/")
  194. return vpath, nil
  195. }
  196. func (a ServerMessageBlockFileSystemAbstraction) FileExists(realpath string) bool {
  197. realpath = toWinPath(filterFilepath(realpath))
  198. f, err := a.share.Open(realpath)
  199. if err != nil {
  200. return false
  201. }
  202. f.Close()
  203. return true
  204. }
  205. func (a ServerMessageBlockFileSystemAbstraction) IsDir(realpath string) bool {
  206. realpath = filterFilepath(realpath)
  207. realpath = toWinPath(realpath)
  208. stx, err := a.share.Stat(realpath)
  209. if err != nil {
  210. return false
  211. }
  212. return stx.IsDir()
  213. }
  214. func (a ServerMessageBlockFileSystemAbstraction) Glob(realpathWildcard string) ([]string, error) {
  215. realpathWildcard = strings.ReplaceAll(realpathWildcard, "[", "?")
  216. realpathWildcard = strings.ReplaceAll(realpathWildcard, "]", "?")
  217. matches, err := a.share.Glob(realpathWildcard)
  218. if err != nil {
  219. return []string{}, err
  220. }
  221. return matches, nil
  222. }
  223. func (a ServerMessageBlockFileSystemAbstraction) GetFileSize(realpath string) int64 {
  224. realpath = toWinPath(filterFilepath(realpath))
  225. stat, err := a.share.Stat(realpath)
  226. if err != nil {
  227. return 0
  228. }
  229. return stat.Size()
  230. }
  231. func (a ServerMessageBlockFileSystemAbstraction) GetModTime(realpath string) (int64, error) {
  232. realpath = toWinPath(filterFilepath(realpath))
  233. stat, err := a.share.Stat(realpath)
  234. if err != nil {
  235. return 0, nil
  236. }
  237. return stat.ModTime().Unix(), nil
  238. }
  239. func (a ServerMessageBlockFileSystemAbstraction) WriteFile(filename string, content []byte, mode os.FileMode) error {
  240. filename = toWinPath(filterFilepath(filename))
  241. return a.share.WriteFile(filename, content, mode)
  242. }
  243. func (a ServerMessageBlockFileSystemAbstraction) ReadFile(filename string) ([]byte, error) {
  244. filename = toWinPath(filterFilepath(filename))
  245. return a.share.ReadFile(filename)
  246. }
  247. func (a ServerMessageBlockFileSystemAbstraction) ReadDir(filename string) ([]fs.DirEntry, error) {
  248. filename = toWinPath(filterFilepath(filename))
  249. fis, err := a.share.ReadDir(filename)
  250. if err != nil {
  251. return []fs.DirEntry{}, err
  252. }
  253. dirEntires := []fs.DirEntry{}
  254. for _, fi := range fis {
  255. if fi.Name() == "System Volume Information" || fi.Name() == "$RECYCLE.BIN" || fi.Name() == "$MFT" {
  256. //System folders. Hide it
  257. continue
  258. }
  259. dirEntires = append(dirEntires, newDirEntryFromFileInfo(fi))
  260. }
  261. return dirEntires, nil
  262. }
  263. func (a ServerMessageBlockFileSystemAbstraction) WriteStream(filename string, stream io.Reader, mode os.FileMode) error {
  264. filename = toWinPath(filterFilepath(filename))
  265. f, err := a.share.OpenFile(filename, os.O_CREATE|os.O_WRONLY, mode)
  266. if err != nil {
  267. return err
  268. }
  269. p := make([]byte, 32768)
  270. for {
  271. _, err := stream.Read(p)
  272. if err != nil {
  273. if err == io.EOF {
  274. break
  275. } else {
  276. return err
  277. }
  278. }
  279. _, err = f.Write(p)
  280. if err != nil {
  281. return err
  282. }
  283. }
  284. return nil
  285. }
  286. func (a ServerMessageBlockFileSystemAbstraction) ReadStream(filename string) (io.ReadCloser, error) {
  287. filename = toWinPath(filterFilepath(filename))
  288. f, err := a.share.OpenFile(filename, os.O_RDONLY, 0755)
  289. if err != nil {
  290. return nil, err
  291. }
  292. return f, nil
  293. }
  294. func (a ServerMessageBlockFileSystemAbstraction) Walk(root string, walkFn filepath.WalkFunc) error {
  295. root = toWinPath(filterFilepath(root))
  296. err := fs.WalkDir(a.share.DirFS(root), ".", func(path string, d fs.DirEntry, err error) error {
  297. if err != nil {
  298. return err
  299. }
  300. statInfo, err := d.Info()
  301. if err != nil {
  302. return err
  303. }
  304. walkFn(filepath.ToSlash(filepath.Join(root, path)), statInfo, err)
  305. return nil
  306. })
  307. return err
  308. }
  309. /*
  310. Optional Functions
  311. */
  312. func (a *ServerMessageBlockFileSystemAbstraction) CapacityInfo() {
  313. fsinfo, err := a.share.Statfs(".")
  314. if err != nil {
  315. return
  316. }
  317. fmt.Println(fsinfo)
  318. }
  319. /*
  320. Helper Functions
  321. */
  322. func toWinPath(filename string) string {
  323. backslashed := strings.ReplaceAll(filename, "/", "\\")
  324. return strings.TrimPrefix(backslashed, "\\")
  325. }
  326. func filterFilepath(rawpath string) string {
  327. rawpath = filepath.ToSlash(filepath.Clean(rawpath))
  328. rawpath = strings.TrimSpace(rawpath)
  329. if strings.HasPrefix(rawpath, "./") {
  330. return rawpath[1:]
  331. } else if rawpath == "." || rawpath == "" {
  332. return "/"
  333. }
  334. return rawpath
  335. }
  336. func wildCardToRegexp(pattern string) string {
  337. var result strings.Builder
  338. for i, literal := range strings.Split(pattern, "*") {
  339. // Replace * with .*
  340. if i > 0 {
  341. result.WriteString(".*")
  342. }
  343. // Quote any regular expression meta characters in the
  344. // literal text.
  345. result.WriteString(regexp.QuoteMeta(literal))
  346. }
  347. return result.String()
  348. }