github.com/icexin/eggos@v0.4.2-0.20220216025428-78b167e4f349/fs/smb/fs.go (about) 1 package smb 2 3 import ( 4 "io/fs" 5 "net" 6 "os" 7 8 "github.com/hirochachacha/go-smb2" 9 "github.com/spf13/afero" 10 ) 11 12 // assert that smb.Fs implements afero.Fs. 13 var _ afero.Fs = (*Fs)(nil) 14 15 type Config struct { 16 Host string 17 User string 18 Password string 19 Mount string 20 } 21 22 type Fs struct { 23 config Config 24 conn net.Conn 25 sess *smb2.Session 26 *smb2.Share 27 } 28 29 func New(config *Config) (afero.Fs, error) { 30 conn, err := net.Dial("tcp", config.Host) 31 if err != nil { 32 return nil, err 33 } 34 35 d := &smb2.Dialer{ 36 Initiator: &smb2.NTLMInitiator{ 37 User: config.User, 38 Password: config.Password, 39 }, 40 } 41 42 sess, err := d.Dial(conn) 43 if err != nil { 44 return nil, err 45 } 46 share, err := sess.Mount(config.Mount) 47 if err != nil { 48 return nil, err 49 } 50 51 return &Fs{ 52 config: *config, 53 sess: sess, 54 conn: conn, 55 Share: share, 56 }, nil 57 } 58 59 func (f *Fs) Close() { 60 f.sess.Logoff() 61 f.conn.Close() 62 } 63 64 // Create creates a file in the filesystem, returning the file and an 65 // error, if any happens. 66 func (f *Fs) Create(name string) (afero.File, error) { 67 return f.Share.Create(name) 68 } 69 70 // Open opens a file, returning it or an error, if any happens. 71 func (f *Fs) Open(name string) (afero.File, error) { 72 return f.Share.Open(name) 73 } 74 75 // OpenFile opens a file using the given flags and the given mode. 76 func (f *Fs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) { 77 return f.Share.OpenFile(name, flag, perm) 78 } 79 80 // The name of this FileSystem 81 func (f *Fs) Name() string { 82 return "smbfs" 83 } 84 85 // Chown changes the uid and gid of the named file. 86 func (f *Fs) Chown(name string, uid, gid int) error { 87 // NOTE: go-smb2 doesn't implement the CAP_UNIX extensions, which are 88 // required to handle Unix uid/guid. 89 return fs.ErrInvalid 90 }