github.com/jspc/eggos@v0.5.1-0.20221028160421-556c75c878a5/fs/smb/fs.go (about)

     1  package smb
     2  
     3  import (
     4  	"net"
     5  	"os"
     6  
     7  	"github.com/hirochachacha/go-smb2"
     8  	"github.com/spf13/afero"
     9  )
    10  
    11  type Config struct {
    12  	Host     string
    13  	User     string
    14  	Password string
    15  	Mount    string
    16  }
    17  
    18  type Fs struct {
    19  	config Config
    20  	conn   net.Conn
    21  	sess   *smb2.Session
    22  	*smb2.Share
    23  }
    24  
    25  func New(config *Config) (afero.Fs, error) {
    26  	conn, err := net.Dial("tcp", config.Host)
    27  	if err != nil {
    28  		return nil, err
    29  	}
    30  
    31  	d := &smb2.Dialer{
    32  		Initiator: &smb2.NTLMInitiator{
    33  			User:     config.User,
    34  			Password: config.Password,
    35  		},
    36  	}
    37  
    38  	sess, err := d.Dial(conn)
    39  	if err != nil {
    40  		return nil, err
    41  	}
    42  	share, err := sess.Mount(config.Mount)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	return &Fs{
    48  		config: *config,
    49  		sess:   sess,
    50  		conn:   conn,
    51  		Share:  share,
    52  	}, nil
    53  }
    54  
    55  func (f *Fs) Close() {
    56  	f.sess.Logoff()
    57  	f.conn.Close()
    58  }
    59  
    60  // Create creates a file in the filesystem, returning the file and an
    61  // error, if any happens.
    62  func (f *Fs) Create(name string) (afero.File, error) {
    63  	return f.Share.Create(name)
    64  }
    65  
    66  // Open opens a file, returning it or an error, if any happens.
    67  func (f *Fs) Open(name string) (afero.File, error) {
    68  	return f.Share.Open(name)
    69  }
    70  
    71  // OpenFile opens a file using the given flags and the given mode.
    72  func (f *Fs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
    73  	return f.Share.OpenFile(name, flag, perm)
    74  }
    75  
    76  // The name of this FileSystem
    77  func (f *Fs) Name() string {
    78  	return "smbfs"
    79  }