smbfs.go 10 KB

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