smb2

package module
v0.0.0-...-95be04a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: BSD-2-Clause Imports: 46 Imported by: 30

README

smb2

Build Status Go Reference

Description

An SMB2/3 client implementation. This is a fork of the project github.com/hirochachacha/go-smb2. Any releases will be pre-1.0.0 for some time as features and bug fixes are implemented.

Installation

go get github.com/cloudsoda/go-smb2

Documentation

https://pkg.go.dev/github.com/cloudsoda/go-smb2

Examples

List share names
package main

import (
	"fmt"
	"net"

	"github.com/cloudsoda/go-smb2"
)

func main() {
	d := &smb2.Dialer{
		Initiator: &smb2.NTLMInitiator{
			User:     "USERNAME",
			Password: "PASSWORD",
		},
	}

	s, err := d.Dial(context.Background(), "SERVERNAME:445")
	if err != nil {
		panic(err)
	}
	defer s.Logoff()

	names, err := s.ListSharenames()
	if err != nil {
		panic(err)
	}

	for _, name := range names {
		fmt.Println(name)
	}
}
List shares with their type and description

ListShares returns the same shares as ListSharenames, along with the type and the description that the server reports for each one.

	shares, err := s.ListShares()
	if err != nil {
		panic(err)
	}

	for _, share := range shares {
		// Skip printers, IPC, and shares reserved for remote administration.
		if share.Type() != smb2.ShareTypeDiskTree || share.IsSpecial() {
			continue
		}
		fmt.Printf("%s\t%s\n", share.Name, share.Comment)
	}
File manipulation
package main

import (
	"io"
	"net"

	"github.com/cloudsoda/go-smb2"
)

func main() {
	d := &smb2.Dialer{
		Initiator: &smb2.NTLMInitiator{
			User:     "USERNAME",
			Password: "PASSWORD",
		},
	}

	s, err := d.Dial(context.Background(), "SERVERNAME:445")
	if err != nil {
		panic(err)
	}
	defer s.Logoff()

	fs, err := s.Mount("SHARENAME")
	if err != nil {
		panic(err)
	}
	defer fs.Umount()

	f, err := fs.Create("hello.txt")
	if err != nil {
		panic(err)
	}
	defer fs.Remove("hello.txt")
	defer f.Close()

	_, err = f.Write([]byte("Hello world!"))
	if err != nil {
		panic(err)
	}

	_, err = f.Seek(0, io.SeekStart)
	if err != nil {
		panic(err)
	}

	bs, err := io.ReadAll(f)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(bs))
}
Check error types
package main

import (
	"context"
	"fmt"
	"net"
	"os"

	"github.com/cloudsoda/go-smb2"
)

func main() {
	d := &smb2.Dialer{
		Initiator: &smb2.NTLMInitiator{
			User:     "USERNAME",
			Password: "PASSWORD",
		},
	}

	s, err := d.Dial(context.Background(), "SERVERNAME:445")
	if err != nil {
		panic(err)
	}
	defer s.Logoff()

	fs, err := s.Mount("SHARENAME")
	if err != nil {
		panic(err)
	}
	defer fs.Umount()

	_, err = fs.Open("notExist.txt")

	fmt.Println(os.IsNotExist(err)) // true
	fmt.Println(os.IsExist(err))    // false

	fs.WriteFile("hello2.txt", []byte("test"), 0444)
	err = fs.WriteFile("hello2.txt", []byte("test2"), 0444)
	fmt.Println(os.IsPermission(err)) // true

	ctx, cancel := context.WithTimeout(context.Background(), 0)
	defer cancel()

	_, err = fs.WithContext(ctx).Open("hello.txt")

	fmt.Println(os.IsTimeout(err)) // true
}
Glob and WalkDir through FS interface
package main

import (
	"fmt"
	"net"
	iofs "io/fs"

	"github.com/cloudsoda/go-smb2"
)

func main() {
	d := &smb2.Dialer{
		Initiator: &smb2.NTLMInitiator{
			User:     "USERNAME",
			Password: "PASSWORD",
		},
	}

	s, err := d.Dial(context.Background(), "SERVERNAME:445")
	if err != nil {
		panic(err)
	}
	defer s.Logoff()

	fs, err := s.Mount("SHARENAME")
	if err != nil {
		panic(err)
	}
	defer fs.Umount()

	matches, err := iofs.Glob(fs.DirFS("."), "*")
	if err != nil {
		panic(err)
	}
	for _, match := range matches {
		fmt.Println(match)
	}

	err = iofs.WalkDir(fs.DirFS("."), ".", func(path string, d iofs.DirEntry, err error) error {
		fmt.Println(path, d, err)

		return nil
	})
	if err != nil {
		panic(err)
	}
}
Authenticate with Kerberos

[!NOTE] See gokrb5 documentation for more details on how to initialize a Kerberos client.

package main

import (
	"context"
	"fmt"

	"github.com/cloudsoda/go-smb2"
	"github.com/jcmturner/gokrb5/v8/client"
	"github.com/jcmturner/gokrb5/v8/config"
)

func main() {
	cfg, err := config.Load("/etc/krb5.conf")
	if err != nil {
		panic(err)
	}

	cl := client.NewWithPassword("USERNAME", "REALM", "PASSWORD", cfg)

	d := &smb2.Dialer{
		Initiator: &smb2.Krb5Initiator{
			Client:    cl,
			TargetSPN: "cifs/SERVERNAME",
		},
	}

	s, err := d.Dial(context.Background(), "SERVERNAME:445")
	if err != nil {
		panic(err)
	}
	defer s.Logoff()

	names, err := s.ListSharenames()
	if err != nil {
		panic(err)
	}

	for _, name := range names {
		fmt.Println(name)
	}
}

Documentation

Overview

Package smb2 implements the SMB2/3 client in [MS-SMB2].

https://msdn.microsoft.com/en-us/library/cc246482.aspx

This package doesn't support CAP_UNIX extension. Symlink is supported by FSCTL_SET_REPARSE_POINT and FSCTL_GET_REPARSE_POINT. The symlink-following algorithm is explained in 2.2.2.2.1 and 2.2.2.2.1.1.

https://msdn.microsoft.com/en-us/library/cc246542.aspx

Supported features and protocol versions are declared in feature.go.

Example
package main

import (
	"context"
	"fmt"
	"io"

	"github.com/cloudsoda/go-smb2"
)

func main() {
	d := &smb2.Dialer{
		Initiator: &smb2.NTLMInitiator{
			User:     "Guest",
			Password: "",
			Domain:   "MicrosoftAccount",
		},
	}

	c, err := d.Dial(context.Background(), "localhost:445")
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = c.Logoff()
	}()

	fs, err := c.Mount(`\\localhost\share`)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = fs.Umount()
	}()

	f, err := fs.Create("hello.txt")
	if err != nil {
		panic(err)
	}
	defer func() {
		f.Close()
		_ = fs.Remove("hello.txt")
	}()

	_, err = f.Write([]byte("Hello world!"))
	if err != nil {
		panic(err)
	}

	_, err = f.Seek(0, io.SeekStart)
	if err != nil {
		panic(err)
	}

	bs, err := io.ReadAll(f)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(bs))

	// Hello world!
}

Index

Examples

Constants

View Source
const AES_AUTH_TAG_LEN = 16

length of tag used to verify the integrity of the encrypted data

View Source
const MaxReadSizeLimit = 0x100000 // deprecated constant
View Source
const PathSeparator = '\\'

Variables

View Source
var ErrBadPattern = errors.New("syntax error in pattern")

ErrBadPattern indicates a pattern was malformed.

View Source
var ErrRequestNotAccepted = errors.New(erref.STATUS_REQUEST_NOT_ACCEPTED.Error())

ErrRequestNotAccepted happens when the host cannot accept more connections.

View Source
var NORMALIZE_PATH = true // normalize path arguments automatically

Functions

func IsPathSeparator

func IsPathSeparator(c uint8) bool

func Match

func Match(pattern, name string) (matched bool, err error)

Match reports whether name matches the shell file name pattern. The pattern syntax is:

pattern:
	{ term }
term:
	'*'         matches any sequence of non-Separator characters
	'?'         matches any single non-Separator character
	'[' [ '^' ] { character-range } ']'
	            character class (must be non-empty)
	c           matches character c (c != '*', '?', '[')

character-range:
	c           matches character c (c != '-', ']')
	lo '-' hi   matches character c for lo <= c <= hi

Match requires pattern to match all of name, not just a substring. The only possible returned error is ErrBadPattern, when pattern is malformed.

Types

type Client

type Client = Session // deprecated type name

type Dialer

type Dialer struct {
	MaxCreditBalance uint16 // if it's zero, clientMaxCreditBalance is used. (See feature.go for more details)
	Negotiator       Negotiator
	Initiator        Initiator
}

Dialer contains options for func (*Dialer) Dial.

func (*Dialer) Dial

func (d *Dialer) Dial(ctx context.Context, address string) (*Session, error)

Dial connects to the SMB server and performs negotiation and authentication. The returned session doesn't inherit the context. If you want to use the same context call Session.WithContext.

func (*Dialer) DialConn

func (d *Dialer) DialConn(ctx context.Context, tcpConn net.Conn, address string) (*Session, error)

DialConn performs negotation and authentication to the server at the other end of tcpConn. The returned session doesn't inherit the context. If you want to use the same context call Session.WithContext. Note: Multiple sessions may not be negotiated on a single TCP connection, so if you want another session you must provide another TCP connection.

type DirEntryPlus

type DirEntryPlus struct {
	os.FileInfo
	SecurityDescriptor *sddl.SecurityDescriptor

	// RawSecurityDescriptor is the security descriptor exactly as returned on
	// the wire: a self-relative SECURITY_DESCRIPTOR blob.
	RawSecurityDescriptor []byte

	Err error // non-nil if the security query failed for this entry
}

DirEntryPlus extends os.FileInfo with security metadata obtained via compound requests. It implements fs.DirEntry.

func (*DirEntryPlus) Info

func (d *DirEntryPlus) Info() (os.FileInfo, error)

func (*DirEntryPlus) Name

func (d *DirEntryPlus) Name() string

func (*DirEntryPlus) Type

func (d *DirEntryPlus) Type() os.FileMode

type File

type File struct {
	// contains filtered or unexported fields
}

func (*File) Chmod

func (f *File) Chmod(mode os.FileMode) error

func (*File) Close

func (f *File) Close() error

func (*File) Name

func (f *File) Name() string

func (*File) Read

func (f *File) Read(b []byte) (n int, err error)

func (*File) ReadAt

func (f *File) ReadAt(b []byte, off int64) (n int, err error)

ReadAt implements io.ReaderAt.

func (*File) ReadFrom

func (f *File) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom implements io.ReadFrom. If r is *File on the same *Share as f, it invokes server-side copy.

func (*File) Readdir

func (f *File) Readdir(n int) (fi []os.FileInfo, err error)

func (*File) ReaddirPlus

func (f *File) ReaddirPlus(n int, securityInfo SecurityInformationRequestFlags) ([]DirEntryPlus, error)

ReaddirPlus reads directory entries enriched with security descriptors. Like Readdir(n), it is incremental — each call returns the next n entries with their security descriptors. Returns io.EOF after the last entry.

Security queries use SMB2 compound requests (CREATE+QUERY_INFO+CLOSE batched into single round-trips), sub-batching internally to respect credit limits.

The returned error reflects the state of the directory listing only: nil, io.EOF after the last entry, or a real Readdir failure. Security failures, whether batch-wide or per-file, are reported on DirEntryPlus.Err. A caller can degrade per-entry instead of abandoning the whole listing.

func (*File) Readdirnames

func (f *File) Readdirnames(n int) (names []string, err error)

func (*File) SecurityInfo

func (*File) SecurityInfoRaw

func (f *File) SecurityInfoRaw(info SecurityInformationRequestFlags) ([]byte, error)

SecurityInfoRaw returns the raw security descriptor of the file as a byte array

func (*File) Seek

func (f *File) Seek(offset int64, whence int) (ret int64, err error)

Seek implements io.Seeker.

func (*File) SetSecurityInfo

func (f *File) SetSecurityInfo(flags SecurityInformationRequestFlags, sd *sddl.SecurityDescriptor) error

func (*File) SetSecurityInfoRaw

func (f *File) SetSecurityInfoRaw(flags SecurityInformationRequestFlags, sd smb2.Encoder) error

func (*File) Stat

func (f *File) Stat() (os.FileInfo, error)

func (*File) Statfs

func (f *File) Statfs() (FileFsInfo, error)

func (*File) Sync

func (f *File) Sync() (err error)

func (*File) Truncate

func (f *File) Truncate(size int64) error

func (*File) Write

func (f *File) Write(b []byte) (n int, err error)

func (*File) WriteAt

func (f *File) WriteAt(b []byte, off int64) (n int, err error)

WriteAt implements io.WriterAt.

func (*File) WriteString

func (f *File) WriteString(s string) (n int, err error)

func (*File) WriteTo

func (f *File) WriteTo(w io.Writer) (n int64, err error)

WriteTo implements io.WriteTo. If w is *File on the same *Share as f, it invokes server-side copy.

type FileFsInfo

type FileFsInfo interface {
	// The number of bytes in a single block on the volume. A block is the smallest allocation unit on the volume.
	BlockSize() uint64
	// Number of sectors in each block.
	FragmentSize() uint64
	// Total number of blocks on the volume that are available to the user.
	TotalBlockCount() uint64
	// Total number of blocks on the volume.
	FreeBlockCount() uint64
	// Total number of free blocks on the volume that are available to the user.
	AvailableBlockCount() uint64
}

type FileStat

type FileStat struct {
	CreationTime   time.Time
	LastAccessTime time.Time
	LastWriteTime  time.Time
	ChangeTime     time.Time
	EndOfFile      int64
	AllocationSize int64
	FileAttributes uint32
	// FileId is the server's 64-bit file reference number (the MFT record plus
	// sequence number on NTFS, the inode number on Samba). It is populated by
	// File.Readdir, File.ReaddirPlus and File.Stat.
	//
	// It is 0 from Share.Stat and Share.Lstat, which report the stat carried by
	// the CREATE response rather than issuing a separate query, and that
	// response has no file id; obtain one via File.Stat on an open handle. It
	// is also 0 when the server itself supplies none, as some legacy and
	// non-native backends do.
	FileId uint64

	// ReparsePointTag is the reparse tag of the file when FileAttributes
	// includes FILE_ATTRIBUTE_REPARSE_POINT, and 0 otherwise.
	//
	// File.Readdir and File.ReaddirPlus read the tag from the directory
	// listing, without an additional request. For a reparse point,
	// Share.Stat, Share.Lstat and File.Stat send an additional QUERY_INFO
	// request for the tag. If the server returns an error status for that
	// request, ReparsePointTag is 0 and the method does not return an error.
	ReparsePointTag ReparseTag

	FileName string
}

func (*FileStat) IsDir

func (fs *FileStat) IsDir() bool

func (*FileStat) ModTime

func (fs *FileStat) ModTime() time.Time

func (*FileStat) Mode

func (fs *FileStat) Mode() os.FileMode

Mode returns the file mode bits derived from FileAttributes and ReparsePointTag.

func (*FileStat) Name

func (fs *FileStat) Name() string

func (*FileStat) Size

func (fs *FileStat) Size() int64

func (*FileStat) Sys

func (fs *FileStat) Sys() any

type Initiator

type Initiator interface {
	OID() asn1.ObjectIdentifier
	InitSecContext() ([]byte, error)            // GSS_Init_sec_context
	AcceptSecContext(sc []byte) ([]byte, error) // GSS_Accept_sec_context
	Sum(bs []byte) []byte                       // GSS_getMIC
	SessionKey() []byte                         // QueryContextAttributes(ctx, SECPKG_ATTR_SESSION_KEY, &out)
}

type InternalError

type InternalError struct {
	Message string
}

InternalError represents internal error.

func (*InternalError) Error

func (err *InternalError) Error() string

type InvalidResponseError

type InvalidResponseError struct {
	Message string
}

InvalidResponseError represents a data sent by the server is corrupted or unexpected.

func (*InvalidResponseError) Error

func (err *InvalidResponseError) Error() string

type Krb5Initiator

type Krb5Initiator struct {
	Client    *client.Client
	TargetSPN string
	// contains filtered or unexported fields
}

Krb5Initiator is a GSSAPI initiator for Kerberos 5. It implements the Initiator interface.

func (*Krb5Initiator) AcceptSecContext

func (ki *Krb5Initiator) AcceptSecContext(sc []byte) ([]byte, error)

AcceptSecContext accepts the security context.

func (*Krb5Initiator) InitSecContext

func (ki *Krb5Initiator) InitSecContext() ([]byte, error)

InitSecContext initiates the security context.

func (*Krb5Initiator) OID

OID returns the Kerberos 5 OID.

func (*Krb5Initiator) SessionKey

func (ki *Krb5Initiator) SessionKey() []byte

SessionKey returns the session key.

func (*Krb5Initiator) Sum

func (ki *Krb5Initiator) Sum(bs []byte) []byte

Sum creates a checksum with the session subkey.

type MapChars

type MapChars int

Mapping strategies that can be used when a reserved character is encountered in a file name.

const (
	// Don't map reserved characters
	MapCharsNone MapChars = 0
	// Map reserved characters using the Services for Mac scheme. This is
	// equivalent to using the 'mapposix' when mounting a volume in Linux.
	MapCharsSFM MapChars = 1
	// Map reserved characters using the Services for Unix scheme. This is
	// equivalent to using 'mapchars' when mounting a volume in Linux.
	MapCharsSFU MapChars = 2
)

type MountOption

type MountOption func(*mountOptions)

configures a Session.Mount() call

func WithMapChars

func WithMapChars() MountOption

The mount will apply character mapping to file names with reserved characters equivalent to samba's `mapchars` option.

If no character mapping option is applied, reserved characters will be passed to the SMB server unchanged resulting in a file with an 8.3 file name (e.g. TEXTFI~1.TXT) https://en.wikipedia.org/wiki/8.3_filename.

func WithMapPosix

func WithMapPosix() MountOption

The mount will apply character mapping to file names with reserved characters equivalent to samba's 'mapposix' option.

If no character mapping option is applied, reserved characters will be passed to the SMB server unchanged resulting in a file with an 8.3 file name (e.g. TEXTFI~1.TXT) https://en.wikipedia.org/wiki/8.3_filename.

type NTLMInitiator

type NTLMInitiator struct {
	User        string
	Password    string
	Hash        []byte
	Domain      string
	Workstation string
	TargetSPN   string
	// contains filtered or unexported fields
}

NTLMInitiator implements session-setup through NTLMv2. It doesn't support NTLMv1. You can use Hash instead of Password.

func (*NTLMInitiator) AcceptSecContext

func (i *NTLMInitiator) AcceptSecContext(sc []byte) ([]byte, error)

func (*NTLMInitiator) InitSecContext

func (i *NTLMInitiator) InitSecContext() ([]byte, error)

func (*NTLMInitiator) OID

func (*NTLMInitiator) SessionKey

func (i *NTLMInitiator) SessionKey() []byte

func (*NTLMInitiator) Sum

func (i *NTLMInitiator) Sum(bs []byte) []byte

type Negotiator

type Negotiator struct {
	RequireMessageSigning bool     // enforce signing?
	ClientGuid            [16]byte // if it's zero, generated by crypto/rand.
	SpecifiedDialect      uint16   // if it's zero, clientDialects is used. (See feature.go for more details)
}

Negotiator contains options for func (*Dialer) Dial.

type RemoteFile

type RemoteFile = File // deprecated type name

type RemoteFileStat

type RemoteFileStat = FileStat // deprecated type name

type RemoteFileSystem

type RemoteFileSystem = Share // deprecated type name

type ReparseTag

type ReparseTag uint32

A ReparseTag uniquely identifies the owner of a reparse point. The owner is the implementer of the file system filter driver associated with a reparse tag. https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-fscc/c8e77b37-3909-4fe6-a4ea-2b9d423b1ee4

const (
	// Reserved
	IOReparseTagReservedZero ReparseTag = smb2.IO_REPARSE_TAG_RESERVED_ZERO
	// Reserved
	IOReparseTagReservedOne ReparseTag = smb2.IO_REPARSE_TAG_RESERVED_ONE
	// Reserved
	IOReparseTagReservedTwo ReparseTag = smb2.IO_REPARSE_TAG_RESERVED_TWO
	// Used for mount point support. See MS-FSCC 2.1.2.5.
	IOReparseTagMountPoint ReparseTag = smb2.IO_REPARSE_TAG_MOUNT_POINT
	// Obsolete. Used by legacy Hierarchical Storage Management Product
	IOReparseTagHSM ReparseTag = smb2.IO_REPARSE_TAG_HSM
	// Home server drive extender
	IOReparseTagDriveExtender ReparseTag = smb2.IO_REPARSE_TAG_DRIVE_EXTENDER
	// Obsolete. Used by legacy Hierarchical Storage Management Product.
	IOReparseTagHSM2 ReparseTag = smb2.IO_REPARSE_TAG_HSM2
	// Used by single-instance storage (SIS) filter driver. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagSIS ReparseTag = smb2.IO_REPARSE_TAG_SIS
	// Used by the WIM Mount filter. Server-side interpretation only, not
	// meaningful over the wire.
	IOReparseTagWIM ReparseTag = smb2.IO_REPARSE_TAG_WIM
	// Obsolete. Used by Clustered Shared Volumes (CSV) version 1 in Windows
	// Server 2008 R2 operating system. Server-side interpretation only, not
	// meaningful over the wire.
	IOReparseTagCSV ReparseTag = smb2.IO_REPARSE_TAG_CSV
	// Used by the DFS filter. The DFS is described in the Distributed File
	// System (DFS): Referral Protocol Specification [MS-DFSC]. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagDFS ReparseTag = smb2.IO_REPARSE_TAG_DFS
	// Used by filter manager test harness.
	IOReparseTagFilterManager ReparseTag = smb2.IO_REPARSE_TAG_FILTER_MANAGER
	// Used for symbolic link support. See MS-FSCC 2.1.2.4.
	IOReparseTagSymlink ReparseTag = smb2.IO_REPARSE_TAG_SYMLINK
	// Used by Microsoft Internet Information Services (IIS) caching.
	// Server-side interpretation only, not meaningful over the wire.
	IOReparseTagIISCache ReparseTag = smb2.IO_REPARSE_TAG_IIS_CACHE
	// Used by the DFS filter. The DFS is described in [MS-DFSC]. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagDFSR ReparseTag = smb2.IO_REPARSE_TAG_DFSR
	// Used by the Data Deduplication (Dedup) filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagDedup ReparseTag = smb2.IO_REPARSE_TAG_DEDUP
	// Not used.
	IOReparseTagAppXStrm ReparseTag = smb2.IO_REPARSE_TAG_APPXSTRM
	// Used by the Network File System (NFS) component. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagNFS ReparseTag = smb2.IO_REPARSE_TAG_NFS
	// Obsolete. Used by Windows Shell for legacy placeholder files in Windows
	// 8.1. Server-side interpretation only, not meaningful over the wire.
	IOReparseTagFilePlaceholder ReparseTag = smb2.IO_REPARSE_TAG_FILE_PLACEHOLDER
	// Used by the Dynamic File filter. Server-side interpretation only, not
	// meaningful over the wire.
	IOReparseTagDFM ReparseTag = smb2.IO_REPARSE_TAG_DFM
	// Used by the Windows Overlay filter, for either WIMBoot or single-file
	// compression. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagWOF ReparseTag = smb2.IO_REPARSE_TAG_WOF
	// Used by the Windows Container Isolation filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagWCI ReparseTag = smb2.IO_REPARSE_TAG_WCI
	// Used by the Windows Container Isolation filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagWCI1 ReparseTag = smb2.IO_REPARSE_TAG_WCI_1
	// Used by NPFS to indicate a named pipe symbolic link from a server silo
	// into the host silo. Server-side interpretation only, not meaningful over
	// the wire.
	IOReparseTagGlobalReparse ReparseTag = smb2.IO_REPARSE_TAG_GLOBAL_REPARSE
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as Microsoft OneDrive. Server-side interpretation only, not meaningful
	// over the wire.
	IOReparseTagCloud ReparseTag = smb2.IO_REPARSE_TAG_CLOUD
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud1 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_1
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud2 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_2
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud3 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_3
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud4 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_4
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud5 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_5
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud6 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_6
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud7 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_7
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud8 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_8
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloud9 ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_9
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloudA ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_A
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloudB ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_B
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloudC ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_C
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloudD ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_D
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloudE ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_E
	// Used by the Cloud Files filter, for files managed by a sync engine such
	// as OneDrive. Server-side interpretation only, not meaningful over the
	// wire.
	IOReparseTagCloudF ReparseTag = smb2.IO_REPARSE_TAG_CLOUD_F
	// Used by Universal Windows Platform (UWP) packages to encode information
	// that allows the application to be launched by CreateProcess. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagAppExecLink ReparseTag = smb2.IO_REPARSE_TAG_APPEXECLINK
	// Used by the Windows Projected File System filter, for files managed by a
	// user mode provider such as VFS for Git. Server-side interpretation only,
	// not meaningful over the wire.
	IOReparseTagProjFS ReparseTag = smb2.IO_REPARSE_TAG_PROJFS
	// Used by the Windows Subsystem for Linux (WSL) to represent a UNIX
	// symbolic link. See MS-FSCC 2.1.2.7.
	IOReparseTagLxSymlink ReparseTag = smb2.IO_REPARSE_TAG_LX_SYMLINK
	// Used by the Azure File Sync (AFS) filter. Server-side interpretation
	// only, not meaningful over the wire.
	IOReparseTagStorageSync ReparseTag = smb2.IO_REPARSE_TAG_STORAGE_SYNC
	// Used by the Azure File Sync (AFS) filter for folder. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagStorageSyncFolder ReparseTag = smb2.IO_REPARSE_TAG_STORAGE_SYNC_FOLDER
	// Used by the Windows Container Isolation filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagWCITombstone ReparseTag = smb2.IO_REPARSE_TAG_WCI_TOMBSTONE
	// Used by the Windows Container Isolation filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagUnhandled ReparseTag = smb2.IO_REPARSE_TAG_UNHANDLED
	// Not used.
	IOReparseTagOneDrive ReparseTag = smb2.IO_REPARSE_TAG_ONEDRIVE
	// Used by the Windows Projected File System filter, for files managed by a
	// user mode provider such as VFS for Git. Server-side interpretation only,
	// not meaningful over the wire.
	IOReparseTagProjFSTombstone ReparseTag = smb2.IO_REPARSE_TAG_PROJFS_TOMBSTONE
	// Used to represent a UNIX domain socket. Server-side interpretation only,
	// not meaningful over the wire. No defined structure.
	IOReparseTagAFUnix ReparseTag = smb2.IO_REPARSE_TAG_AF_UNIX
	// Used by the Windows Subsystem for Linux (WSL) to represent a UNIX FIFO
	// (named pipe). Server-side interpretation only, not meaningful over the
	// wire. No defined structure.
	IOReparseTagLxFIFO ReparseTag = smb2.IO_REPARSE_TAG_LX_FIFO
	// Used by the Windows Subsystem for Linux (WSL) to represent a UNIX
	// character special file. Server-side interpretation only, not meaningful
	// over the wire. No defined structure.
	IOReparseTagLxChr ReparseTag = smb2.IO_REPARSE_TAG_LX_CHR
	// Used by the Windows Subsystem for Linux (WSL) to represent a UNIX block
	// special file. Server-side interpretation only, not meaningful over the
	// wire. No defined structure.
	IOReparseTagLxBlk ReparseTag = smb2.IO_REPARSE_TAG_LX_BLK
	// Used by the Windows Container Isolation filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagWCILink ReparseTag = smb2.IO_REPARSE_TAG_WCI_LINK
	// Used by the Windows Container Isolation filter. Server-side
	// interpretation only, not meaningful over the wire.
	IOReparseTagWCILink1 ReparseTag = smb2.IO_REPARSE_TAG_WCI_LINK_1
)

func (ReparseTag) IsDirectory

func (t ReparseTag) IsDirectory() bool

IsDirectory is true if a directory with this tag can have children (the D bit), as Cloud Files and ProjFS directories do. It does not report whether the file is a directory, and has no meaning for a file that is not one.

func (ReparseTag) IsMicrosoft

func (t ReparseTag) IsMicrosoft() bool

IsMicrosoft reports whether the tag is owned by Microsoft (the M bit). Returns false for third-party tags.

func (ReparseTag) IsNameSurrogate

func (t ReparseTag) IsNameSurrogate() bool

IsNameSurrogate is true if a file or directory with the tag represents another named entity in the system, as symbolic links and mount points do (the N bit).

type ResponseError

type ResponseError struct {
	Code uint32 // NTSTATUS
	// contains filtered or unexported fields
}

ResponseError represents a error with a nt status code sent by the server. The NTSTATUS is defined in [MS-ERREF]. https://msdn.microsoft.com/en-au/library/cc704588.aspx

func (*ResponseError) Error

func (err *ResponseError) Error() string

type SecurityDescriptorEncoder

type SecurityDescriptorEncoder struct {
	*sddl.SecurityDescriptor
}

func (*SecurityDescriptorEncoder) Encode

func (se *SecurityDescriptorEncoder) Encode(dest []byte)

func (*SecurityDescriptorEncoder) Size

func (se *SecurityDescriptorEncoder) Size() int

type SecurityInformationRequestFlags

type SecurityInformationRequestFlags uint32

SecurityInformationRequestFlags the data that is expected to be returned in Security Information

const (
	// OwnerSecurityInformation (OWNER_SECURITY_INFORMATION) requests the owner SID to be returned
	OwnerSecurityInformation SecurityInformationRequestFlags = 0x00000001
	// GroupSecurityInformation (GROUP_SECURITY_INFORMATION) requests the group SID to be returned
	GroupSecurityInformation SecurityInformationRequestFlags = 0x00000002
	// DACLSecurityInformation (DACL_SECURITY_INFORMATION) requests the DACL to be returned
	DACLSecurityInformation SecurityInformationRequestFlags = 0x00000004
	// SACLSecurityInformation (SACL_SECURITY_INFORMATION) requests the SACL to be returned
	SACLSecurityInformation SecurityInformationRequestFlags = 0x00000008
)

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents a SMB session.

func (*Session) Echo

func (c *Session) Echo() error

Echo sends an echo request to the server.

func (*Session) ListSharenames

func (c *Session) ListSharenames() ([]string, error)

ListSharenames returns the names of the shares exported by the server. Use ListShares to get the type and the description of each share as well.

func (*Session) ListShares

func (c *Session) ListShares() ([]ShareInfo, error)

ListShares returns the shares exported by the server, including the type and the description the server reports for each one.

func (*Session) Logoff

func (c *Session) Logoff() error

Logoff invalidates the current SMB session.

func (*Session) Mount

func (c *Session) Mount(sharename string, opts ...MountOption) (*Share, error)

Mount mounts the SMB share. sharename must follow format like `<share>` or `\\<server>\<share>`. Note that the mounted share doesn't inherit session's context. If you want to use the same context, call Share.WithContext manually.

func (*Session) WithContext

func (c *Session) WithContext(ctx context.Context) *Session

type Share

type Share struct {
	// contains filtered or unexported fields
}

Share represents a SMB tree connection with VFS interface.

func (*Share) Chmod

func (fs *Share) Chmod(name string, mode os.FileMode) error

func (*Share) Chtimes

func (fs *Share) Chtimes(name string, atime time.Time, mtime time.Time) error

func (*Share) Create

func (fs *Share) Create(name string) (*File, error)

func (*Share) DirFS

func (s *Share) DirFS(dirname string) fs.FS

func (*Share) Glob

func (fs *Share) Glob(pattern string) (matches []string, err error)

Glob should work like filepath.Glob.

func (*Share) Lstat

func (fs *Share) Lstat(name string) (os.FileInfo, error)

func (*Share) Mkdir

func (fs *Share) Mkdir(name string, perm os.FileMode) error

func (*Share) MkdirAll

func (fs *Share) MkdirAll(path string, perm os.FileMode) error

MkdirAll mimics os.MkdirAll

func (*Share) Open

func (fs *Share) Open(name string) (*File, error)

func (*Share) OpenFile

func (fs *Share) OpenFile(name string, flag int, perm os.FileMode) (*File, error)

func (*Share) ReadDir

func (fs *Share) ReadDir(dirname string) ([]os.FileInfo, error)

func (*Share) ReadDirPlus

func (fs *Share) ReadDirPlus(dirname string, securityInfo SecurityInformationRequestFlags) ([]DirEntryPlus, error)

ReadDirPlus returns all directory entries enriched with security descriptors, sorted by name. For directories with many entries, prefer opening the directory and calling File.ReaddirPlus incrementally.

func (*Share) ReadFile

func (fs *Share) ReadFile(filename string) ([]byte, error)
func (fs *Share) Readlink(name string) (string, error)

func (*Share) Remove

func (fs *Share) Remove(name string) error

func (*Share) RemoveAll

func (fs *Share) RemoveAll(path string) error

RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error).

func (*Share) Rename

func (fs *Share) Rename(oldpath, newpath string) error

func (*Share) SecurityInfo

func (fs *Share) SecurityInfo(name string, info SecurityInformationRequestFlags) (*sddl.SecurityDescriptor, error)

SecurityInfo returns the security descriptor of a file

func (*Share) SecurityInfoRaw

func (fs *Share) SecurityInfoRaw(name string, info SecurityInformationRequestFlags) ([]byte, error)

SecurityInfoRaw returns the raw security descriptor of a file as a byte array

func (*Share) SetSecurityInfo

func (fs *Share) SetSecurityInfo(name string, flags SecurityInformationRequestFlags, sd *sddl.SecurityDescriptor) error

func (*Share) SetSecurityInfoRaw

func (fs *Share) SetSecurityInfoRaw(name string, flags SecurityInformationRequestFlags, sd smb2.Encoder) error

func (*Share) Stat

func (fs *Share) Stat(name string) (os.FileInfo, error)

func (*Share) Statfs

func (fs *Share) Statfs(name string) (FileFsInfo, error)
func (fs *Share) Symlink(target, linkpath string) error

Symlink mimics os.Symlink. This API should work on latest Windows and latest MacOS. However it may not work on Linux because Samba doesn't support reparse point well. Also there is a restriction on target pathname. Generally, a pathname begins with leading backslash (e.g `\dir\name`) can be interpreted as two ways. On windows, it is evaluated as a relative path, on other systems, it is evaluated as an absolute path. This implementation always assumes that format is absolute path. So, if you know the target server is Windows, you should avoid that format. If you want to use an absolute target path on windows, you can use // `C:\dir\name` format instead.

func (*Share) Truncate

func (fs *Share) Truncate(name string, size int64) error

func (*Share) Umount

func (fs *Share) Umount() error

Umount disconects the current SMB tree.

func (*Share) WithContext

func (fs *Share) WithContext(ctx context.Context) *Share

func (*Share) WriteFile

func (fs *Share) WriteFile(filename string, data []byte, perm os.FileMode) error

type ShareInfo

type ShareInfo struct {
	// Name is the share name, in the form accepted by Session.Mount.
	Name string

	// Comment is the share's description, as configured on the server.
	Comment string

	// TypeFlags is the share type as sent by the server: a base type in the
	// low bits and independent flags in the high bits. Type, IsSpecial and
	// IsTemporary decode it; TypeFlags also includes the bits they do not
	// decode.
	TypeFlags uint32
}

ShareInfo describes a share on a server, as returned by Session.ListShares. It contains the fields of a SHARE_INFO_1, defined in [MS-SRVS] section 2.2.4.23, at https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-srvs/fc69f110-998d-4c16-9667-514e22fdd80b

func (ShareInfo) IsSpecial

func (s ShareInfo) IsSpecial() bool

IsSpecial reports whether the share is marked as reserved for interprocess communication or remote administration. [MS-SRVS] gives IPC$ and ADMIN$ as examples, and states that the flag can also mark administrative shares such as C$.

func (ShareInfo) IsTemporary

func (s ShareInfo) IsTemporary() bool

IsTemporary reports whether the share is not persisted, so is not recreated when the file server next initializes.

func (ShareInfo) Type

func (s ShareInfo) Type() ShareType

Type returns the base type of the share, without the flag bits.

type ShareType

type ShareType uint32

ShareType is the kind of resource a share exposes. The values are the base share types defined in [MS-SRVS] section 2.2.2.4, at https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-srvs/6069f8c0-c93f-43a0-a5b4-7ed447eb4b84

const (
	ShareTypeDiskTree   ShareType = srvsvc.STYPE_DISKTREE
	ShareTypePrintQueue ShareType = srvsvc.STYPE_PRINTQ
	ShareTypeDevice     ShareType = srvsvc.STYPE_DEVICE
	ShareTypeIPC        ShareType = srvsvc.STYPE_IPC
)

Values of ShareType.

func (ShareType) String

func (t ShareType) String() string

String returns a lowercase name for t, or "unknown" if t is not one of the ShareType constants.

type TransportError

type TransportError struct {
	Err error
}

TransportError represents a error come from net.Conn layer.

func (*TransportError) Error

func (err *TransportError) Error() string

Directories

Path Synopsis
internal
msrpc
Package msrpc implements the client side of the connection-oriented RPC protocol used to call remote procedures over an SMB named pipe.
Package msrpc implements the client side of the connection-oriented RPC protocol used to call remote procedures over an SMB named pipe.
srvsvc
Package srvsvc implements the parts of the Server Service Remote Protocol that enumerate the shares on a server.
Package srvsvc implements the parts of the Server Service Remote Protocol that enumerate the shares on a server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL