Crate smb

Crate smb 

Source
Expand description

§SMB

the smb crate is a pure rust SMB client, supports the SMB2 protocol (including SMB3).

§Basic usage

The most basic functionality that an SMB client should provide is the ability to connect to an SMB server, authenticate, and perform simple file operations.

The Client struct provides a simple interface for interacting with an SMB server. Let’s see how we use it.

use smb::{Client, ClientConfig, UncPath, FileCreateArgs, FileAccessMask};
use std::str::FromStr;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // instantiate the client
    let client = Client::new(ClientConfig::default());

    // Connect to a share
    let target_path = UncPath::from_str(r"\\server\share").unwrap();
    client.share_connect(&target_path, "username", "password".to_string()).await?;

    // And open a file on the server
    let file_to_open = target_path.with_path("file.txt");
    let file_open_args = FileCreateArgs::make_open_existing(FileAccessMask::new().with_generic_read(true));
    let file = client.create_file(&file_to_open, &file_open_args).await?;
    // now, you can do a bunch of operations against `file`, and close it at the end.
    Ok(())
}

Cool! we got ourselves a live connection to an SMB server, and we also got a file open.

But wait… How do we know it’s actually a file? Well, we don’t. The Client::create_file method returns the Resource struct, which is a union to a file, directory, or a pipe - the supported SMB resources in this crate (printers are currently not implemented specifically). What we need to do next, is to find out what type of resource we’ve got:

match &file {
    Resource::File(file) => {
        // We have a file
    }
    Resource::Directory(dir) => {
        // We have a directory
    }
    Resource::Pipe(pipe) => {
        // We have a pipe
    }
}
// Note: we could also use `.unwrap_file()` here,
// or similar method provided by Resource to find out what kind of resource this is!

Cool! Let’s assume we got ourselves a file. Then, we can do the obvious operation of reading or writing a block of data from or to the file:

let file: File = file.unwrap_file();

let mut data: [u8; 1024] = [0; 1024];
file.read_at(&mut data, 0).await?;
file.write_at(&data, 0).await?;

At the end, close the file.

file.close().await?;

§Feature flags

TypeAlgorithmAsyncMulti-threadedSingle-threadedFeature Name
AuthenticationKerberoskerberos
TransportQUICquic
Signing*sign
SigningHMAC_SHA256sign_hmac
SigningAES-128-GCMsign_gmac
SigningAES-128-CCMsign_cmac
Encryption*encrypt
EncryptionAES-128-CCMencrypt_aes128ccm
EncryptionAES-128-GCMencrypt_aes128gcm
EncryptionAES-256-CCMencrypt_aes256ccm
EncryptionAES-256-GCMencrypt_aes256gcm
Compression*compress
CompressionLZ4compress_lz4
CompressionPattern_V1🟡🟡🟡compress_pattern_v1*
CompressionLZNT1/LZ77/+Huffman-
  • The Pattern_V1 compression algorithm currently supports in-bound decompression only.

§Advanced documentation

Re-exports§

pub use client::Client;
pub use client::ClientConfig;
pub use client::UncPath;
pub use connection::Connection;
pub use connection::ConnectionConfig;
pub use error::Error;
pub use resource::Directory;
pub use resource::File;
pub use resource::FileCreateArgs;
pub use resource::GetLen;
pub use resource::ReadAt;
pub use resource::ReadAtChannel;
pub use resource::Resource;
pub use resource::ResourceHandle;
pub use resource::WriteAt;
pub use resource::WriteAtChannel;
pub use session::Session;
pub use tree::DfsRootTreeRef;
pub use tree::Tree;
pub use smb_transport as transport;

Modules§

binrw_util
This module contains utility types for the binrw crate.
cancel
Cancel Request
chained_item
A genric utility struct to wrap “chained”-encoded entries. Many fscc-query structs have a common “next entry offset” field, which is used to chain multiple entries together. This struct wraps the value, and the offset, and provides a way to iterate over them. See ChainedItem<T>::write_chained to see how to write this type when in a list.
client
High-level SMB client interface.
common_info
compressed
Compressed messages
compression
Implements (de)compression logic.
connection
create
Create & Close (files) requests and responses.
crypto
dfsc
dialects
Implements SMB-dialect-specific types and functions.
directory_info
docs
Additional crate docs are submodules.
echo
Echo request and response messages
encrypted
Encrypted messages
error
file
File-related messages: Flush, Read, Write.
filesystem_info
guid
header
info
SMB2 Query and Set Info messages.
ioctl
SMB2 IOCTL packet implementation
lock
message
msg_handler
negotiate
notify
SMB2 Change Notify Request and Response, and Server to Client Notification
oplock
plain
query_dir
Directory-related messages.
query_file_info
resource
security
MS-DTYP 2.4
session
SMB Session logic module.
session_setup
set_file_info
smb1
SMBv1 negotiation packet support.
sync_helpers
This is a helper module that allows easy access and usage of Async/Multi-threaded features in the library, according to the features enabled.
tree
tree_connect
util

Macros§

access_mask
Macro for defining a bitfield for an access mask.
file_info_classes
A macro for generating a file class enums, for both the file information class, and information value. including a trait for the value types.
guid
A macro to create a Guid from a string literal at compile time.
query_info_data
Internal helper macro to easily generate fields & methods for QueryInfoData.

Structs§

ACE
ACL
AccessAce
AccessCallbackAce
AccessMask
AccessObjectAce
AccessObjectCallbackAce
AceFlags
AdditionalInfo
AllocationSize
AppInstanceId
AppInstanceVersion
ArrayData
BlobData
CancelRequest
ChainedItem
ChainedItemList
Implements a chained item list.
ChangeNotifyRequest
ChangeNotifyResponse
ClaimSecurityAttributeRelativeV1
CloseFlags
CloseRequest
CloseResponse
CompressedChainedItem
CompressedChainedMessage
CompressedData
CompressedUnchainedMessage
CompressionCapabilities
CompressionCapsFlags
CreateContext
CreateOptions
CreateRequest
CreateResponse
CreateResponseFlags
DH2QResp
DfsRequestData
RequestData is part of the REQ_GET_DFS_REFERRAL_EX message (section 2.2.3).
DfsRequestFlags
DirAccessMask
DurableHandleReconnect
DurableHandleReconnectV2
DurableHandleRequest
DurableHandleRequestV2
DurableHandleResponse
DurableHandleV2Flags
EaBuffer
EchoMesasge
EncryptedHeader
EncryptedMessage
EncryptionCapabilities
EntryV3DCRefs
2.2.5.3.2 NameListReferral Flag Set to 1
EntryV3V4DfsPaths
2.2.5.3.1 NameListReferral Flag Set to 0
ErrorResponse
ErrorResponseContext
FciClaimSecurityAttributes
FileAccessInformation
FileAccessMask
FileAllInformation
FileAllocationInformation
FileAlternateNameInformation
FileAttributeTagInformation
FileAttributes
MS-FSCC 2.6
FileBasicInformation
FileBothDirectoryInformationInner
FileCompressionInformation
FileDirectoryInformationInner
FileDispositionInformation
FileEaInformation
FileEndOfFileInformation
FileFsAttributeInformation
FileFsControlInformation
FileFsDeviceInformation
FileFsFullSizeInformation
FileFsObjectIdInformation
FileFsSectorSizeInformation
FileFsSizeInformation
FileFsVolumeInformation
FileFullDirectoryInformationInner
FileFullEaInformationInner
FileGetEaInformationInner
FileGetQuotaInformationInner
FileId
2.2.14.1: SMB2_FILEID
FileId64ExtdBothDirectoryInformationInner
FileId64ExtdDirectoryInformationInner
FileIdAllExtdBothDirectoryInformationInner
FileIdAllExtdDirectoryInformationInner
FileIdBothDirectoryInformationInner
FileIdExtdDirectoryInformationInner
FileIdFullDirectoryInformationInner
FileIdInformation
FileInternalInformation
FileLevelTrimRange
MSDN
FileLevelTrimRequest
FileLevelTrimResponse
MS-FSCC 2.3.14
FileLinkInformation
2.4.27.2 - FileLinkInformation for SMB2 protocol
FileModeInformation
FileNameInformation
FileNamesInformationInner
FileNetworkOpenInformation
FileNormalizedNameInformation
FileNotifyInformationInner
FilePipeInformation
FilePipeLocalInformation
FilePipeRemoteInformation
FilePositionInformation
FileQuotaInformationInner
FileRenameInformation2
FileShortNameInformation
FileStandardInformation
FileStreamInformationInner
FileSystemAttributes
FileSystemControlFlags
FileValidDataLengthInformation
FlushRequest
FlushResponse
FsDeviceCharacteristics
GetEaInfoList
GlobalCapabilities
Guid
Represents a standard, 16-byte GUID.
Header
Sync and Async SMB2 Message header.
HeaderFlags
IoctlBuffer
IoctlRequest
IoctlRequestFlags
IoctlResponse
LeaseBreakAckResponse
LeaseBreakNotify
LeaseState
LmrRequestResiliencyResponse
LockElement
LockFlag
LockRequest
LockResponse
LockSequence
LogoffRequest
LogoffResponse
LuidAttrData
MandatoryLabelAccessMask
NegotiateCapabilities
NegotiateContext
NegotiateRequest
NegotiateResponse
NegotiateSecurityMode
NetnameNegotiateContextId
NetworkInterfaceCapability
NetworkInterfaceInfo
NetworkResiliencyRequest
Sent to request resiliency for a specified open file. This request is not valid for the SMB 2.0.2 dialect.
NotifyFilter
NotifyFlags
NotifySessionClosed
NullByte
ObjectAccessMask
ObjectAceFlags
OffloadReadRequest
MS-FSCC 2.3.41
OffloadReadResponse
MS-FSCC 2.3.42
OplockBreakMsg
PipePeekRequest
PipePeekResponse
MS-FSCC 2.3.46
PipeTransceiveRequest
PipeTransceiveResponse
PipeWaitRequest
The FSCTL_PIPE_WAIT Request requests that the server wait until either a time-out interval elapses, or an instance of the specified named pipe is available for connection.
PipeWaitResponse
PlainRequest
A plain, single, SMB2 message.
PlainResponse
A plain, single, SMB2 message.
PreauthIntegrityCapabilities
QueryAllocRangesItem
QueryAllocRangesResult
QueryDirectoryFlags
QueryDirectoryRequest
QueryDirectoryResponse
QueryInfoFlags
QueryInfoRequest
QueryInfoResponse
QueryInfoResponseData
A helpers struct that contains the raw data of a query info response or a set info request, and can be parsed using the QueryInfoResponseData::parse method, to a specific info type.
QueryMaximalAccessRequest
QueryMaximalAccessResponse
QueryNetworkInterfaceInfoRequest
QueryOnDiskIdReq
QueryOnDiskIdResp
QueryQuotaInfo
RawQueryInfoData
RawSetInfoData
RdmaTransformCapabilities
ReadFlags
ReadRequest
ReadResponse
ReferralEntry
ReferralEntryFlags
ReferralEntryValueV1
ReferralEntryValueV2
DO NOT use this struct directly when bin read/writing. Use an instance of ReferralEntry instead.
ReferralEntryValueV3
ReferralEntryValueV4
ReferralHeaderFlags
RemotedIdentityTreeConnect
ReqGetDfsReferral
MS-DFSC 2.2.2: DFS referral requests are sent in the form of an REQ_GET_DFS_REFERRAL message, by using an appropriate transport as specified in section 2.1.
ReqGetDfsReferralEx
RequestLeaseV1
RequestLeaseV2
RespGetDfsReferral
SID
SID (Security identifier)
SectorSizeInfoFlags
SecurityDescriptor
Security Descriptor - MS-DTYP 2.4.6
SecurityDescriptorControl
ServerToClientNotification
SessionFlags
SessionSecurityMode
SessionSetupRequest
SessionSetupResponse
SetFileFullEaInformation
A FileFullEaInformation structure to be used when setting for extended attributes. You may use super::QueryFileFullEaInformation for querying.
SetInfoRequest
SetInfoResponse
SetReparsePointRequest
Stores data for a reparse point.
SetReparsePointResponse
SetupRequestFlags
ShareAccessFlags
ShareFlags
SidAttrData
SidAttrSeGroup
SigningCapabilities
SocketAddrStorageV4
SocketAddrStorageV6
SrvCopyChunkCopyWrite
SrvCopychunkCopy
The Length of source/dest keys in SrvCopyChunk* FSCTLs contents. MS-SMB 2.2.31.1
SrvCopychunkItem
SrvCopychunkResponse
SrvEnumerateSnapshotsRequest
SrvEnumerateSnapshotsResponse
MS-SMB 2.2.7.2.2.1
SrvHashRetrieveFileBased
SrvHashRetrieveHashBased
SrvReadHashReq
SrvReadHashRes
SrvRequestResumeKey
SrvRequestResumeKeyRequest
SrvSnapshotArray
SvhdxOpenDeviceContextV1
MS-RSVD sections 2.2.4.12 and 2.2.4.32.
SvhdxOpenDeviceContextV2
SystemMandatoryLabelAce
SystemResourceAttributeAce
TimewarpToken
TransportCapabilities
TreeCapabilities
TreeConnectContext
TreeConnectRequest
Tree Connect Request
TreeConnectRequestFlags
TreeConnectResponse
TreeDisconnectRequest
TreeDisconnectResponse
ValidateNegotiateInfoRequest
ValidateNegotiateInfoResponse
WriteFlags
WriteRequest
Zero-copy write request.
WriteResponse

Enums§

AceType
AceValue
AclRevision
ClaimSecurityAttributeType
Command
CommunicationChannel
CompressedMessage
CompressionAlgorithm
CreateAction
CreateContextReqData
CreateContextRespData
CreateContextType
CreateDisposition
DfsServerType
Type of server hosting the target
Dialect
EncryptionCipher
EntryV3Value
ErrorId
FileAlignmentInformation
FileCompressionFormat
FsDeviceType
FsctlCodes
GetInfoRequestData
This struct describes the payload to be added in the QueryInfoRequest when asking for information about Quota or Extended Attributes. In other cases, it is empty.
HashAlgorithm
ImpersonationLevel
InfoType
IoctlReqData
NamedPipeConfiguration
NamedPipeEnd
NamedPipeState
NamedPipeType
NegotiateContextType
NegotiateContextValue
NegotiateDialect
Dialects that may be used in the SMB Negotiate Request. The same as Dialect but with a wildcard for SMB 2.0.
Notification
NotificationType
NotifyAction
OplockLevel
PipeCompletionMode
PipeReadMode
QueryDirectoryInfo
QueryDirectoryInfoClass
QueryFileInfo
QueryFileInfoClass
QueryFileSystemInfo
QueryFileSystemInfoClass
QueryInfoClass
QueryInfoData
Represents information passed in get/set info requests. This is the information matching InfoType, and should be used in the get info response and in the set info request.
RdmaTransformId
ReferralEntryValue
ReferralLevel
The DFS referral version supported by the client. See ReqGetDfsReferral::max_referral_level.
ReparseTag
MS-FSCC 2.1.2.1: Each reparse point has a reparse tag. The reparse tag uniquely identifies the owner of that reparse point. The owner is the implementer of the file system filter driver associated with a reparse tag.
Request
RequestContent
RequestLease
Response
ResponseContent
SetFileInfo
SetFileInfoClass
SetFileSystemInfo
SetFileSystemInfoClass
SetInfoClass
A helper class for SetInfoRequest to contain the information class to set. In cases of no class, it will be set to a null byte (0u8).
SetInfoData
Represents information passed in get/set info requests. This is the information matching InfoType, and should be used in the get info response and in the set info request.
ShareCacheMode
ShareType
SigningAlgorithmId
SmbFsccError
FSCC errors
SmbMsgError
SMB Message related errors
SocketAddrStorage
SrvHashRetrievalType
Status
NT Status codes.
SvhdxOpenDeviceContext

Traits§

CreateContextDataReqValue
CreateContextDataRespValue
FileInfoType
Trait for file information types. This trait contains all types of all file info types and classes, specified in MS-FSCC.
FsctlRequest
This is a helper trait that defines, for a certain FSCTL request type, the response type and their matching FSCTL code.
FsctlResponseContent
A trait that helps parsing FSCTL responses by matching the FSCTL code.
IoctlRequestContent
A trait that helps calculating the size of the buffer for IOCTL requests.
QueryDirectoryInfoValue
QueryFileInfoValue
QueryFileSystemInfoValue
SetFileInfoValue
SetFileSystemInfoValue

Type Aliases§

EchoRequest
EchoResponse
EncryptionNonce
The nonce used for encryption. Depending on the encryption algorithm, the nonce may be trimmed to a smaller size when used, or padded with zeroes to match the required size. When transmitted, the full 16 bytes are used.
FileBothDirectoryInformation
FileDirectoryInformation
FileFullDirectoryInformation
FileFullEaInformationCommon
FileGetEaInformation
FileGetQuotaInformation
FileId64ExtdBothDirectoryInformation
FileId64ExtdDirectoryInformation
FileIdAllExtdBothDirectoryInformation
FileIdAllExtdDirectoryInformation
FileIdBothDirectoryInformation
FileIdExtdDirectoryInformation
FileIdFullDirectoryInformation
FileNamesInformation
FileNotifyInformation
FileQuotaInformation
FileStreamInformation
LeaseBreakAck
LeaseBreakResponse
NetworkInterfacesInfo
OplockBreakAck
OplockBreakNotify
OplockBreakResponse
QueryFileFullEaInformation
A FileFullEaInformation structure to be used when querying for extended attributes. You may use super::SetFileFullEaInformation for setting.
ReqCreateContext
RespCreateContext
Result
SMB Result type
SdBuffer