diff --git a/CHANGELOG b/CHANGELOG index e52126b..f6b7268 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,5 +1,109 @@ +pysmb-1.2.7, 30 May 2021 +======================== + +- Fix compatibility issues on file retrievals with Likewise servers (#177) +- Improve SMBConnection's connect() method to remove the need to provide sock_family + parameter for IPv6 addresses in Python 3.x (#180) + +pysmb-1.2.6, 9 Dec 2020 +======================= +- Fix bug in SMB1 store file implmentation which generates SMB_COM_WRITE_ANDX + packets larger than the allowed max buffer size (#175) + +pysmb-1.2.5, 18 Oct 2020 +======================= +- Fix bug in filename encoding which leads to failure for file retrieval and upload operations (#170 #171). +- Improve resetFileAttributes() method in SMBConnection class to allow the + new attribute to be specified in the reset operation (#172). + +pysmb-1.2.4, 6 Oct 2020 +======================= +- Remove dependency on pycrypto as it is no longer under active maintenance + +pysmb-1.2.3, 6 Oct 2020 +======================= +- Fix bug in session key generation during session negotiation (#166) +- Fix bug in SMB message signing which leads to operation failures with Samba services. + +pysmb-1.2.2, 5 Sep 2020 +======================= +- Improve SMB URL handlers to support specifying server's machine name and IP + address. (#162) +- Improvements to documentation on SMB URLs (#160) + +pysmb-1.2.1, 17 May 2020 +======================== +- Fix bug in deleteFiles() method which can fail for certain search patterns. + +pysmb-1.2.0, 17 May 2020 +========================= +- Add new parameter, delete_matching_folders, to deleteFiles() method to + support deletion of child folders that match the search pattern. + +pysmb-1.1.29, 16 May 2020 +========================= +- Fix unhandled exception for short NBNS queries #149 +- Fix wildcard file deletion with servers on SMB2 protocol #33 + +pysmb-1.1.28, 23 Nov 2019 +======================== +- SharedFile instances returned from the listPath() method now has a new + file_id attribute which represents the file reference number given by the SMB server. + +pysmb-1.1.27, 9 Jan 2019 +======================== +- Remove support for SMB-2.1 dialect as it seems to have issues with Windows 2008 R2 + +pysmb-1.1.26, 5 Jan 2019 +======================== +- Prevents OperationError from being raised when listPath() operation does not + return any matching file results. +- SMBConnection is now a context manager #122. + +pysmb-1.1.25, 28 July 2018 +======================== +- Fix buggy support for search parameter in listPath() method. Add + SMB_FILE_ATTRIBUTE_INCL_NORMAL bit constant to include 'normal' files with + other file types in the returned result. From now on, pysmb defines a 'normal' file + as a file entry that is not read-only, not hidden, not system, not archive and + not a directory; it ignores other attributes like compression, indexed, sparse, + temporary and encryption. listPath() method will now include 'normal' files + using the default search parameter. +- Add isNormal property to SharedFile class to support test if the file is a + 'normal' file (according to pysmb definition of 'normal' file). + +pysmb-1.1.24, 19 July 2018 +======================== +- Improve listPath implementation for SMB1 +- Support for STATUS_PENDING responses across all SMB2 operations. + +pysmb-1.1.23, 5 May 2018 +======================== +- Fix bug in listShares() method which fails when the remote server has many shares. +- Improve echo() method to test and fail if the provided data to echo is not a bytes object. +- Fix bug in listPath() method where the path to query is not properly terminated. + +pysmb-1.1.22, 17 Sep 2017 +======================== +- Fix bug in getAttributes() method which should return only the filename + instead of the entire path for the filename property for the return result. + +pysmb-1.1.21, 9 Sep 2017 +======================== +- Fix bug where timestamp values for SMB1 getAttributes() response are not + converted properly from FILETIME to epoch time values. + +pysmb-1.1.20, 13 Aug 2017 +========================= +- Add getSecurity() method to support security descriptors query via SMB2 +- Improve retrieveFile() and retrieveFileFromOffset() methods to allow file + retrievals over SMB2 even when the file is being locked on the server. +- Silently discards NMB SESSION_KEEPALIVE packets instead of raising warnings. +- SMB sessionID will be sent in ECHO requests to conform to SMB2 specs. +- Fix type errors for MD4 functions in python3. + pysmb-1.1.19, 13 Nov 2016 -======================== +========================= - Ignore STATUS_PENDING during delete and file store operations pysmb-1.1.18, 9 Apr 2016 diff --git a/LICENSE b/LICENSE index d183506..a02f43a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ -Copyright (C) 2001-2015 Michael Teo +Copyright (C) 2001-2020 Michael Teo This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..b22628d --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,11 @@ +include LICENSE +include CHANGELOG +recursive-include python2 * +recursive-exclude python2 *.pyc +recursive-exclude python2 *~ +recursive-include python3 * +recursive-exclude python3 *.pyc +recursive-exclude python3 *~ +recursive-include sphinx * +recursive-include docs * +recursive-exclude docs *.zip diff --git a/PKG-INFO b/PKG-INFO index ba886a1..e5c24c8 100644 --- a/PKG-INFO +++ b/PKG-INFO @@ -1,6 +1,6 @@ Metadata-Version: 1.1 Name: pysmb -Version: 1.1.19 +Version: 1.2.7 Summary: pysmb is an experimental SMB/CIFS library written in Python to support file sharing between Windows and Linux machines Home-page: https://miketeo.net/projects/pysmb Author: Michael Teo diff --git a/docs/doctrees/api/nmb_NBNSProtocol.doctree b/docs/doctrees/api/nmb_NBNSProtocol.doctree index 63a5cd0..fd57e9c 100644 Binary files a/docs/doctrees/api/nmb_NBNSProtocol.doctree and b/docs/doctrees/api/nmb_NBNSProtocol.doctree differ diff --git a/docs/doctrees/api/nmb_NetBIOS.doctree b/docs/doctrees/api/nmb_NetBIOS.doctree index 9b279b3..1fe1cb7 100644 Binary files a/docs/doctrees/api/nmb_NetBIOS.doctree and b/docs/doctrees/api/nmb_NetBIOS.doctree differ diff --git a/docs/doctrees/api/smb_SMBConnection.doctree b/docs/doctrees/api/smb_SMBConnection.doctree index 383d6bf..1bdcc6e 100644 Binary files a/docs/doctrees/api/smb_SMBConnection.doctree and b/docs/doctrees/api/smb_SMBConnection.doctree differ diff --git a/docs/doctrees/api/smb_SMBHandler.doctree b/docs/doctrees/api/smb_SMBHandler.doctree index 2fb06a4..338e04c 100644 Binary files a/docs/doctrees/api/smb_SMBHandler.doctree and b/docs/doctrees/api/smb_SMBHandler.doctree differ diff --git a/docs/doctrees/api/smb_SMBProtocolFactory.doctree b/docs/doctrees/api/smb_SMBProtocolFactory.doctree index d424daa..025e84a 100644 Binary files a/docs/doctrees/api/smb_SMBProtocolFactory.doctree and b/docs/doctrees/api/smb_SMBProtocolFactory.doctree differ diff --git a/docs/doctrees/api/smb_SharedDevice.doctree b/docs/doctrees/api/smb_SharedDevice.doctree index eb0fa96..4f162ed 100644 Binary files a/docs/doctrees/api/smb_SharedDevice.doctree and b/docs/doctrees/api/smb_SharedDevice.doctree differ diff --git a/docs/doctrees/api/smb_SharedFile.doctree b/docs/doctrees/api/smb_SharedFile.doctree index faa32e5..ffacd42 100644 Binary files a/docs/doctrees/api/smb_SharedFile.doctree and b/docs/doctrees/api/smb_SharedFile.doctree differ diff --git a/docs/doctrees/api/smb_exceptions.doctree b/docs/doctrees/api/smb_exceptions.doctree index aec1229..8153f53 100644 Binary files a/docs/doctrees/api/smb_exceptions.doctree and b/docs/doctrees/api/smb_exceptions.doctree differ diff --git a/docs/doctrees/api/smb_security_descriptors.doctree b/docs/doctrees/api/smb_security_descriptors.doctree new file mode 100644 index 0000000..ca9fff7 Binary files /dev/null and b/docs/doctrees/api/smb_security_descriptors.doctree differ diff --git a/docs/doctrees/environment.pickle b/docs/doctrees/environment.pickle index 987c4bf..b29b9ce 100644 Binary files a/docs/doctrees/environment.pickle and b/docs/doctrees/environment.pickle differ diff --git a/docs/doctrees/extending.doctree b/docs/doctrees/extending.doctree index dc0b3fc..33636c0 100644 Binary files a/docs/doctrees/extending.doctree and b/docs/doctrees/extending.doctree differ diff --git a/docs/doctrees/index.doctree b/docs/doctrees/index.doctree index 807f40d..b26d5bb 100644 Binary files a/docs/doctrees/index.doctree and b/docs/doctrees/index.doctree differ diff --git a/docs/doctrees/upgrading.doctree b/docs/doctrees/upgrading.doctree new file mode 100644 index 0000000..80066a2 Binary files /dev/null and b/docs/doctrees/upgrading.doctree differ diff --git a/docs/html/.buildinfo b/docs/html/.buildinfo index bf80f8a..81eb6cd 100644 --- a/docs/html/.buildinfo +++ b/docs/html/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: 8ec856095809db2990831edf01ebc5a4 +config: 6727d573e921f0a52e9dd64da58c662b tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/html/_modules/index.html b/docs/html/_modules/index.html index c518f1e..1aa8d8c 100644 --- a/docs/html/_modules/index.html +++ b/docs/html/_modules/index.html @@ -1,57 +1,33 @@ - + - + - - - Overview: module code — pysmb 1.1.18 documentation - + + + Overview: module code — pysmb 1.2.7 documentation + - - - - - - - - - + + + + + + + - + + +
@@ -78,12 +70,16 @@
  • index
  • - +
  • + modules |
  • + + diff --git a/docs/html/_modules/nmb/NetBIOS.html b/docs/html/_modules/nmb/NetBIOS.html index 82bdf75..7593ead 100644 --- a/docs/html/_modules/nmb/NetBIOS.html +++ b/docs/html/_modules/nmb/NetBIOS.html @@ -1,59 +1,34 @@ - - - - + + + + - - - nmb.NetBIOS — pysmb 1.1.18 documentation - + + + nmb.NetBIOS — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + - +
    @@ -61,16 +36,16 @@

    Source code for nmb.NetBIOS

    -
    +
     import os, logging, random, socket, time, select
    -from base import NBNS, NotConnectedError
    -from nmb_constants import TYPE_CLIENT, TYPE_SERVER, TYPE_WORKSTATION
    +from .base import NBNS, NotConnectedError
    +from .nmb_constants import TYPE_CLIENT, TYPE_SERVER, TYPE_WORKSTATION
     
     
    [docs]class NetBIOS(NBNS): log = logging.getLogger('NMB.NetBIOS') -
    [docs] def __init__(self, broadcast = True, listen_port = 0): +
    [docs] def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets. @@ -93,7 +68,7 @@ :return: None """ self.sock.close() - self.sock = None
    + self.sock = None
    def write(self, data, ip, port): assert self.sock, 'Socket is already closed' @@ -137,29 +112,29 @@ assert self.sock, 'Socket is already closed' trn_id = random.randint(1, 0xFFFF) - data = self.prepareNetNameQuery(trn_id, False) + data = self.prepareNetNameQuery(trn_id, False) self.write(data, ip, port) ret = self._pollForQueryPacket(trn_id, timeout) if ret: - return map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret)) + return list(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) else: - return None
    + return None
    # # Protected Methods # def _pollForNetBIOSPacket(self, wait_trn_id, timeout): - end_time = time.time() + timeout - while True: + end_time = time.time() - timeout + while True: try: - _timeout = end_time - time.time() + _timeout = time.time()-end_time if _timeout <= 0: - return None + return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: - return None + return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: @@ -169,8 +144,8 @@ if trn_id == wait_trn_id: return ret - except select.error, ex: - if type(ex) is types.TupleType: + except select.error as ex: + if type(ex) is tuple: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: @@ -180,16 +155,16 @@ # Contributed by Jason Anderson # def _pollForQueryPacket(self, wait_trn_id, timeout): - end_time = time.time() + timeout - while True: + end_time = time.time() - timeout + while True: try: - _timeout = end_time - time.time() + _timeout = time.time()-end_time if _timeout <= 0: - return None + return None ready, _, _ = select.select([ self.sock.fileno() ], [ ], [ ], _timeout) if not ready: - return None + return None data, _ = self.sock.recvfrom(0xFFFF) if len(data) == 0: @@ -199,15 +174,30 @@ if trn_id == wait_trn_id: return ret - except select.error, ex: - if type(ex) is types.TupleType: + except select.error as ex: + if type(ex) is tuple: if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex
    +
    + + +
    @@ -218,13 +208,17 @@
  • index
  • - - +
  • + modules |
  • + + + diff --git a/docs/html/_modules/nmb/NetBIOSProtocol.html b/docs/html/_modules/nmb/NetBIOSProtocol.html index 50dade2..a0fa1f5 100644 --- a/docs/html/_modules/nmb/NetBIOSProtocol.html +++ b/docs/html/_modules/nmb/NetBIOSProtocol.html @@ -1,59 +1,34 @@ - - - - + + + + - - - nmb.NetBIOSProtocol — pysmb 1.1.18 documentation - + + + nmb.NetBIOSProtocol — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + - +
    @@ -61,14 +36,11 @@

    Source code for nmb.NetBIOSProtocol

    -
    +
     import os, logging, random, socket, time
     from twisted.internet import reactor, defer
     from twisted.internet.protocol import DatagramProtocol
    -from nmb_constants import TYPE_SERVER
    -from base import NBNS
    -
    -IP_QUERY, NAME_QUERY = range(2)
    +from .base import NBNS
     
     
    [docs]class NetBIOSTimeout(Exception): """Raised in NBNSProtocol via Deferred.errback method when queryName method has timeout waiting for reply""" @@ -78,7 +50,7 @@ log = logging.getLogger('NMB.NBNSProtocol') -
    [docs] def __init__(self, broadcast = True, listen_port = 0): +
    [docs] def __init__(self, broadcast = True, listen_port = 0): """ Instantiate a NBNSProtocol instance. @@ -94,7 +66,7 @@ self.transport.getHandle().setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) reactor.callLater(1, self.cleanupPendingTrns)
    - def datagramReceived(self, data, from_info): +
    [docs] def datagramReceived(self, data, from_info): host, port = from_info trn_id, ret = self.decodePacket(data) @@ -104,7 +76,7 @@ if ip is NAME_QUERY: # decode as query packet trn_id, ret = self.decodeIPQueryPacket(data) - d.callback(ret) + d.callback(ret)
    def write(self, data, ip, port): # We don't use the transport.write method directly as it keeps raising DeprecationWarning for ip='<broadcast>' @@ -122,8 +94,8 @@ On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) - while True: - if not self.pending_trns.has_key(trn_id): + while True: + if trn_id not in self.pending_trns: break else: trn_id = (trn_id + 1) & 0xFFFF @@ -154,8 +126,8 @@ On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception """ trn_id = random.randint(1, 0xFFFF) - while True: - if not self.pending_trns.has_key(trn_id): + while True: + if trn_id not in self.pending_trns: break else: trn_id = (trn_id + 1) & 0xFFFF @@ -168,21 +140,22 @@ d2.addErrback(d.errback) def stripCode(ret): - if ret is not None: # got valid response. Somehow the callback is also called when there is an error. + if ret is not None: # got valid response. Somehow the callback is also called when there is an error. d.callback(map(lambda s: s[0], filter(lambda s: s[1] == TYPE_SERVER, ret))) d2.addCallback(stripCode) self.pending_trns[trn_id] = ( time.time()+timeout, NAME_QUERY, d2 ) return d
    - def stopProtocol(self): - DatagramProtocol.stopProtocol(self) +
    [docs] def stopProtocol(self): + DatagramProtocol.stopProtocol(self)
    def cleanupPendingTrns(self): now = time.time() # reply should have been received in the past - expired = filter(lambda (trn_id, (expiry_time, name, d)): expiry_time < now, self.pending_trns.iteritems()) + # info is tuple of ( expiry_time, name, d ) + expired = filter(lambda trn_id, info: info[0] < now, self.pending_trns.iteritems()) # remove expired items from dict + call errback def expire_item(item): @@ -199,7 +172,22 @@ reactor.callLater(1, self.cleanupPendingTrns)
    +
    +
    +
    +
    @@ -210,13 +198,17 @@
  • index
  • - - +
  • + modules |
  • + + + diff --git a/docs/html/_modules/smb/SMBConnection.html b/docs/html/_modules/smb/SMBConnection.html index 1df1ca8..1098daf 100644 --- a/docs/html/_modules/smb/SMBConnection.html +++ b/docs/html/_modules/smb/SMBConnection.html @@ -1,59 +1,34 @@ - - - - + + + + - - - smb.SMBConnection — pysmb 1.1.18 documentation - + + + smb.SMBConnection — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + - +
    @@ -61,11 +36,11 @@

    Source code for smb.SMBConnection

    -
    -import os, logging, select, socket, struct, errno
    -from smb_constants import *
    -from smb_structs import *
    -from base import SMB, NotConnectedError, NotReadyError, SMBTimeout
    +
    +import os, logging, select, socket, types, struct, errno
    +from .smb_constants import *
    +from .smb_structs import *
    +from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout
     
     
     
    [docs]class SMBConnection(SMB): @@ -79,11 +54,12 @@ #: SMB messages will only be signed when remote server requires signing. SIGN_WHEN_REQUIRED = 2 -
    [docs] def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): +
    [docs] def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBConnection instance. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. + *password* can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully. Note that you need to call *connect* method to actually establish the SMB connection to the remote server and perform authentication. @@ -92,7 +68,7 @@ Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. - You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+`` + You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. @@ -108,10 +84,10 @@ :param boolean is_direct_tcp: Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139). """ - SMB.__init__(self, username, password, my_name, remote_name, domain, use_ntlm_v2, sign_options, is_direct_tcp) - self.sock = None - self.auth_result = None - self.is_busy = False + SMB.__init__(self, username, password, my_name, remote_name, domain, use_ntlm_v2, sign_options, is_direct_tcp) + self.sock = None + self.auth_result = None + self.is_busy = False self.is_direct_tcp = is_direct_tcp
    # @@ -119,10 +95,10 @@ # def onAuthOK(self): - self.auth_result = True + self.auth_result = True def onAuthFailed(self): - self.auth_result = False + self.auth_result = False def write(self, data): assert self.sock @@ -135,6 +111,15 @@ total_sent = total_sent + sent # + # Support for "with" context + # + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + # # Misc Properties # @@ -148,33 +133,38 @@ # Public Methods # -
    [docs] def connect(self, ip, port = 139, sock_family = socket.AF_INET, timeout = 60): +
    [docs] def connect(self, ip, port = 139, sock_family = None, timeout = 60): """ Establish the SMB connection to the remote SMB/CIFS server. You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication. + :param port: Defaults to 139. If you are using direct TCP mode (is_direct_tcp=true when creating this SMBConnection instance), use 445. + :param sock_family: In Python 3.x, use *None* as we can infer the socket family from the provided *ip*. In Python 2.x, it must be either *socket.AF_INET* or *socket.AF_INET6*. :return: A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise. """ if self.sock: self.sock.close() - self.auth_result = None - self.sock = socket.socket(sock_family) - self.sock.settimeout(timeout) - self.sock.connect(( ip, port )) - - self.is_busy = True + self.auth_result = None + if sock_family: + self.sock = socket.socket(sock_family) + self.sock.settimeout(timeout) + self.sock.connect(( ip, port )) + else: + self.sock = socket.create_connection(( ip, port )) + + self.is_busy = True try: if not self.is_direct_tcp: self.requestNMBSession() else: self.onNMBSessionOK() - while self.auth_result is None: - self._pollForNetBIOSPacket(timeout) - finally: - self.is_busy = False + while self.auth_result is None: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False return self.auth_result
    @@ -184,7 +174,7 @@ """ if self.sock: self.sock.close() - self.sock = None
    + self.sock = None
    [docs] def listShares(self, timeout = 30): """ @@ -198,33 +188,41 @@ results = [ ] def cb(entries): - self.is_busy = False + self.is_busy = False results.extend(entries) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._listShares(cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results
    [docs] def listPath(self, service_name, path, - search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE, + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* + + For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + + Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), + system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files + and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). + If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. + SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). - The default *search* value will query for all read-only, hidden, system, archive files and directories. :param string/unicode pattern: the filter to apply to the results before returning to the client. :return: A list of :doc:`smb.base.SharedFile<smb_SharedFile>` instances. """ @@ -234,20 +232,20 @@ results = [ ] def cb(entries): - self.is_busy = False + self.is_busy = False results.extend(entries) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._listPath(service_name, path, cb, eb, search = search, pattern = pattern, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results
    @@ -267,20 +265,20 @@ results = [ ] def cb(entries): - self.is_busy = False + self.is_busy = False results.extend(entries) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._listSnapshots(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results
    @@ -298,44 +296,75 @@ results = [ ] def cb(info): - self.is_busy = False + self.is_busy = False results.append(info) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._getAttributes(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results[0]
    -
    [docs] def retrieveFile(self, service_name, path, file_obj, timeout = 30): - """ - Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. - - Use *retrieveFileFromOffset()* method if you wish to specify the offset to read from the remote *path* and/or the number of bytes to write to the *file_obj*. +
    [docs] def getSecurity(self, service_name, path, timeout = 30): + """ + Retrieve the security descriptor of the file at *path* on the *service_name*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. - :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. + :return: A :class:`smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file. + """ + if not self.sock: + raise NotConnectedError('Not connected to server') + + results = [ ] + + def cb(info): + self.is_busy = False + results.append(info) + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True + try: + self._getSecurity(service_name, path, cb, eb, timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False + + return results[0]
    + +
    [docs] def retrieveFile(self, service_name, path, file_obj, timeout = 30): + """ + Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. + + Use *retrieveFileFromOffset()* method if you wish to specify the offset to read from the remote *path* and/or the number of bytes to write to the *file_obj*. + + :param string/unicode service_name: the name of the shared folder for the *path* + :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. + :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :return: A 2-element tuple of ( file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ - return self.retrieveFileFromOffset(service_name, path, file_obj, 0L, -1L, timeout)
    - -
    [docs] def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0L, max_length = -1L, timeout = 30): + return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout)
    + +
    [docs] def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be raised. - :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* up to *max_length* number of bytes. + :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* up to *max_length* number of bytes. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the method returns immediately after the file is opened successfully for reading. @@ -348,20 +377,20 @@ results = [ ] def cb(r): - self.is_busy = False + self.is_busy = False results.append(r[1:]) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._retrieveFileFromOffset(service_name, path, file_obj, cb, eb, offset, max_length, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results[0]
    @@ -373,12 +402,12 @@ :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure<smb_exceptions>` will be raised. - :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. + :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. In Python3, this file-like object must have a *read* method which returns a bytes parameter. :return: Number of bytes uploaded """ - return self.storeFileFromOffset(service_name, path, file_obj, 0L, True, timeout)
    - -
    [docs] def storeFileFromOffset(self, service_name, path, file_obj, offset = 0L, truncate = False, timeout = 30): + return self.storeFileFromOffset(service_name, path, file_obj, 0, True, timeout)
    + +
    [docs] def storeFileFromOffset(self, service_name, path, file_obj, offset = 0, truncate = False, timeout = 30): """ Store the contents of the *file_obj* at *path* on the *service_name*. @@ -396,26 +425,28 @@ results = [ ] def cb(r): - self.is_busy = False + self.is_busy = False results.append(r[1]) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._storeFileFromOffset(service_name, path, file_obj, cb, eb, offset, truncate = truncate, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results[0]
    -
    [docs] def deleteFiles(self, service_name, path_file_pattern, timeout = 30): +
    [docs] def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. + + If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. @@ -427,50 +458,54 @@ raise NotConnectedError('Not connected to server') def cb(r): - self.is_busy = False - - def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True - try: - self._deleteFiles(service_name, path_file_pattern, cb, eb, timeout = timeout) - while self.is_busy: - self._pollForNetBIOSPacket(timeout) - finally: - self.is_busy = False
    - -
    [docs] def resetFileAttributes(self, service_name, path_file_pattern, timeout = 30): + self.is_busy = False + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True + try: + self._deleteFiles(service_name, path_file_pattern, delete_matching_folders, cb, eb, timeout = timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False
    + +
    [docs] def resetFileAttributes(self, service_name, path_file_pattern, file_attributes = ATTR_NORMAL, timeout = 30): """ Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. - Note: this function is currently only implemented for SMB2! Technically, it sets the FILE_ATTRIBUTE_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) + By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. + (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) + + Note: this function is currently only implemented for SMB2! :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. + :param int file_attributes: The desired file attributes to set. Defaults to `ATTR_NORMAL`. :return: None """ if not self.sock: raise NotConnectedError('Not connected to server') def cb(r): - self.is_busy = False - - def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True - try: - self._resetFileAttributes(service_name, path_file_pattern, cb, eb, timeout = timeout) - while self.is_busy: - self._pollForNetBIOSPacket(timeout) - finally: - self.is_busy = False
    + self.is_busy = False + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True + try: + self._resetFileAttributes(service_name, path_file_pattern, cb, eb, file_attributes, timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False
    [docs] def createDirectory(self, service_name, path, timeout = 30): """ @@ -485,19 +520,19 @@ raise NotConnectedError('Not connected to server') def cb(r): - self.is_busy = False - - def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True try: self._createDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False
    + self.is_busy = False
    [docs] def deleteDirectory(self, service_name, path, timeout = 30): """ @@ -512,19 +547,19 @@ raise NotConnectedError('Not connected to server') def cb(r): - self.is_busy = False - - def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True try: self._deleteDirectory(service_name, path, cb, eb, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False
    + self.is_busy = False
    [docs] def rename(self, service_name, old_path, new_path, timeout = 30): """ @@ -540,25 +575,25 @@ raise NotConnectedError('Not connected to server') def cb(r): - self.is_busy = False - - def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True try: self._rename(service_name, old_path, new_path, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False
    + self.is_busy = False
    [docs] def echo(self, data, timeout = 10): """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. - :param string data: Data to send to the remote server. + :param bytes data: Data to send to the remote server. Must be a bytes object. :return: The *data* parameter """ if not self.sock: @@ -567,20 +602,20 @@ results = [ ] def cb(r): - self.is_busy = False + self.is_busy = False results.append(r) def eb(failure): - self.is_busy = False - raise failure - - self.is_busy = True + self.is_busy = False + raise failure + + self.is_busy = True try: self._echo(data, cb, eb) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: - self.is_busy = False + self.is_busy = False return results[0]
    @@ -591,7 +626,7 @@ def _pollForNetBIOSPacket(self, timeout): expiry_time = time.time() + timeout read_len = 4 - data = '' + data = b'' while read_len > 0: try: @@ -608,14 +643,14 @@ data = data + d read_len -= len(d) - except select.error, ex: - if isinstance(ex, types.TupleType): + except select.error as ex: + if isinstance(ex, tuple): if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: raise ex - type_, flags, length = struct.unpack('>BBH', data) + type, flags, length = struct.unpack('>BBH', data) if flags & 0x01: length = length | 0x10000 @@ -635,8 +670,8 @@ data = data + d read_len -= len(d) - except select.error, ex: - if isinstance(ex, types.TupleType): + except select.error as ex: + if isinstance(ex, tuple): if ex[0] != errno.EINTR and ex[0] != errno.EAGAIN: raise ex else: @@ -645,7 +680,22 @@ self.feedData(data) +
    + + +
    @@ -656,13 +706,17 @@
  • index
  • - - +
  • + modules |
  • + + + diff --git a/docs/html/_modules/smb/SMBProtocol.html b/docs/html/_modules/smb/SMBProtocol.html index 20cbc73..a1024cd 100644 --- a/docs/html/_modules/smb/SMBProtocol.html +++ b/docs/html/_modules/smb/SMBProtocol.html @@ -1,59 +1,34 @@ - - - - + + + + - - - smb.SMBProtocol — pysmb 1.1.18 documentation - + + + smb.SMBProtocol — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + - +
    @@ -61,13 +36,13 @@

    Source code for smb.SMBProtocol

    -
    +
     import os, logging, time
     from twisted.internet import reactor, defer
     from twisted.internet.protocol import ClientFactory, Protocol
    -from smb_constants import *
    -from smb_structs import *
    -from base import SMB, NotConnectedError, NotReadyError, SMBTimeout
    +from .smb_constants import *
    +from .smb_structs import *
    +from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout
     
     
     __all__ = [ 'SMBProtocolFactory', 'NotConnectedError', 'NotReadyError' ]
    @@ -88,9 +63,10 @@
             else:
                 self.onNMBSessionOK()
     
    +
         def connectionLost(self, reason):
             if self.factory.instance == self:
    -            self.instance = None
    +            self.instance = None
     
         def dataReceived(self, data):
             self.feedData(data)
    @@ -122,7 +98,7 @@
             if self.factory.instance == self:
                 now = time.time()
                 to_remove = []
    -            for mid, r in self.pending_requests.iteritems():
    +            for mid, r in self.pending_requests.items():
                     if r.expiry_time < now:
                         try:
                             r.errback(SMBTimeout())
    @@ -147,7 +123,7 @@
         #: SMB messages will only be signed when remote server requires signing.
         SIGN_WHEN_REQUIRED = 2
     
    -
    [docs] def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): +
    [docs] def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): """ Create a new SMBProtocolFactory instance. You will pass this instance to *reactor.connectTCP()* which will then instantiate the TCP connection to the remote SMB/CIFS server. Note that the default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. @@ -157,7 +133,7 @@ File operations can only be proceeded after the connection has been authenticated successfully. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. - You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+``. + You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. @@ -181,7 +157,7 @@ self.use_ntlm_v2 = use_ntlm_v2 self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp - self.instance = None #: The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly.
    + self.instance = None #: The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly.
    # # Public Property @@ -240,15 +216,23 @@ return d
    [docs] def listPath(self, service_name, path, - search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE, + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* + + For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + + Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), + system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files + and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). + If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. + SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). - The default *search* value will query for all read-only, hidden, system, archive files and directories. :param string/unicode pattern: the filter to apply to the results before returning to the client. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile<smb_SharedFile>` instances. @@ -305,13 +289,13 @@ :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be called in the returned *Deferred* errback. - :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. + :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 3-element tuple of ( *file_obj*, file attributes of the file on server, number of bytes written to *file_obj* ). The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py) """ - return self.retrieveFileFromOffset(service_name, path, file_obj, 0L, -1L, timeout)
    - -
    [docs] def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0L, max_length = -1L, timeout = 30): + return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout)
    + +
    [docs] def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30): """ Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*. @@ -321,7 +305,7 @@ :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure<smb_exceptions>` will be called in the returned *Deferred* errback. - :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. + :param file_obj: A file-like object that has a *write* method. Data will be written continuously to *file_obj* until EOF is received from the remote service. In Python3, this file-like object must have a *write* method which accepts a bytes parameter. :param integer/long offset: the offset in the remote *path* where the first byte will be read and written to *file_obj*. Must be either zero or a positive integer/long value. :param integer/long max_length: maximum number of bytes to read from the remote *path* and write to the *file_obj*. Specify a negative value to read from *offset* to the EOF. If zero, the *Deferred* callback is invoked immediately after the file is opened successfully for reading. @@ -347,7 +331,7 @@ :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: Path of the file on the remote server. If the file at *path* does not exist, it will be created. Otherwise, it will be overwritten. If the *path* refers to a folder or the file cannot be opened for writing, an :doc:`OperationFailure<smb_exceptions>` will be called in the returned *Deferred* errback. - :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. + :param file_obj: A file-like object that has a *read* method. Data will read continuously from *file_obj* until EOF. In Python3, this file-like object must have a *read* method which returns a bytes parameter. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *file_obj*, number of bytes uploaded ). """ if not self.instance: @@ -357,10 +341,12 @@ self.instance._storeFile(service_name, path, file_obj, d.callback, d.errback, timeout = timeout) return d
    -
    [docs] def deleteFiles(self, service_name, path_file_pattern, timeout = 30): +
    [docs] def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. + If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. + :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. @@ -372,7 +358,7 @@ raise NotConnectedError('Not connected to server') d = defer.Deferred() - self.instance._deleteFiles(service_name, path_file_pattern, d.callback, d.errback, timeout = timeout) + self.instance._deleteFiles(service_name, path_file_pattern, delete_matching_folders, d.callback, d.errback, timeout = timeout) return d
    [docs] def createDirectory(self, service_name, path): @@ -431,7 +417,7 @@ """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. - :param string data: Data to send to the remote server. + :param bytes data: Data to send to the remote server. Must be a bytes object. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter. """ @@ -458,13 +444,28 @@ # (Do not touch these unless you know what you are doing) # - def buildProtocol(self, addr): +
    [docs] def buildProtocol(self, addr): p = self.protocol(self.username, self.password, self.my_name, self.remote_name, self.domain, self.use_ntlm_v2, self.sign_options, self.is_direct_tcp) p.factory = self - return p
    + return p
    +
    +
    + +
    @@ -475,13 +476,17 @@
  • index
  • - - +
  • + modules |
  • + + + diff --git a/docs/html/_modules/smb/base.html b/docs/html/_modules/smb/base.html index 9b94c8d..73e8407 100644 --- a/docs/html/_modules/smb/base.html +++ b/docs/html/_modules/smb/base.html @@ -1,59 +1,34 @@ - - - - + + + + - - - smb.base — pysmb 1.1.18 documentation - + + + smb.base — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + - +
    @@ -61,22 +36,23 @@

    Source code for smb.base

    -
    +
     import logging, binascii, time, hmac
     from datetime import datetime
    -from smb_constants import *
    -from smb2_constants import *
    -from smb_structs import *
    -from smb2_structs import *
    +from .smb_constants import *
    +from .smb2_constants import *
    +from .smb_structs import *
    +from .smb2_structs import *
    +from .security_descriptors import SecurityDescriptor
     from nmb.base import NMBSession
    -from utils import convertFILETIMEtoEpoch
    -import ntlm, securityblob
    +from .utils import convertFILETIMEtoEpoch
    +from . import ntlm, securityblob
     
     try:
         import hashlib
         sha256 = hashlib.sha256
     except ImportError:
    -    from utils import sha256
    +    from .utils import sha256
     
     
     
    [docs]class NotReadyError(Exception): @@ -90,12 +66,6 @@
    [docs]class SMBTimeout(Exception): """Raised when a timeout has occurred while waiting for a response or for a SMB/CIFS operation to complete.""" pass
    - - -def _convert_to_unicode(string): - if not isinstance(string, unicode): - string = unicode(string, "utf-8") - return string class SMB(NMBSession): @@ -119,25 +89,26 @@ SIGN_WHEN_SUPPORTED = 1 SIGN_WHEN_REQUIRED = 2 - def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): - NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) - self.username = _convert_to_unicode(username) - self.password = _convert_to_unicode(password) - self.domain = _convert_to_unicode(domain) + def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): + NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) + self.username = username + self._password = password + self.domain = domain self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1 self.smb_message = SMBMessage() - self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True + self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True + self.async_requests = { } #: AsyncID mapped to _PendingRequest instance self.pending_requests = { } #: MID mapped to _PendingRequest instance self.connected_trees = { } #: Share name mapped to TID self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages - self.has_negotiated = False - self.has_authenticated = False - self.is_signing_active = False #: True if the remote server accepts message signing. All outgoing messages will be signed. Simiar to IsSigningActive as described in [MS-CIFS] 3.2.1.2 - self.signing_session_key = None #: Session key for signing packets, if signing is active. Similar to SigningSessionKey as described in [MS-CIFS] 3.2.1.2 - self.signing_challenge_response = None #: Contains the challenge response for signing, if signing is active. Similar to SigningChallengeResponse as described in [MS-CIFS] 3.2.1.2 + self.has_negotiated = False + self.has_authenticated = False + self.is_signing_active = False #: True if the remote server accepts message signing. All outgoing messages will be signed. Simiar to IsSigningActive as described in [MS-CIFS] 3.2.1.2 + self.signing_session_key = None #: Session key for signing packets, if signing is active. Similar to SigningSessionKey as described in [MS-CIFS] 3.2.1.2 + self.signing_challenge_response = None #: Contains the challenge response for signing, if signing is active. Similar to SigningChallengeResponse as described in [MS-CIFS] 3.2.1.2 self.mid = 0 self.uid = 0 self.next_signing_id = 2 #: Similar to ClientNextSendSequenceNumber as described in [MS-CIFS] 3.2.1.2 @@ -149,7 +120,7 @@ # SMB1 attributes # Most of the following attributes will be initialized upon receipt of SMB_COM_NEGOTIATE message from server (via self._updateServerInfo_SMB1 method) - self.use_plaintext_authentication = False #: Similar to PlaintextAuthenticationPolicy in in [MS-CIFS] 3.2.1.1 + self.use_plaintext_authentication = False #: Similar to PlaintextAuthenticationPolicy in in [MS-CIFS] 3.2.1.1 self.max_raw_size = 0 self.max_buffer_size = 0 #: Similar to MaxBufferSize as described in [MS-CIFS] 3.2.1.1 self.max_mpx_count = 0 #: Similar to MaxMpxCount as described in [MS-CIFS] 3.2.1.1 @@ -167,6 +138,11 @@ (self.use_ntlm_v2 and 'v2') or 'v1', (SUPPORT_EXTENDED_SECURITY and 'with') or 'without') + @property + def password(self): + if callable(self._password): + return self._password() + return self._password # # NMBSession Methods @@ -179,12 +155,12 @@ pass def onNMBSessionMessage(self, flags, data): - while True: + while True: try: i = self.smb_message.decode(data) except SMB2ProtocolHeaderError: self.log.info('Now switching over to SMB2 protocol communication') - self.is_using_smb2 = True + self.is_using_smb2 = True self.mid = 0 # Must reset messageID counter, or else remote SMB2 server will disconnect self._setupSMB2Methods() self.smb_message = self._klassSMBMessage() @@ -236,6 +212,7 @@ self._listShares = self._listShares_SMB1 self._listPath = self._listPath_SMB1 self._listSnapshots = self._listSnapshots_SMB1 + self._getSecurity = self._getSecurity_SMB1 self._getAttributes = self._getAttributes_SMB1 self._retrieveFile = self._retrieveFile_SMB1 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1 @@ -258,6 +235,7 @@ self._listShares = self._listShares_SMB2 self._listPath = self._listPath_SMB2 self._listSnapshots = self._listSnapshots_SMB2 + self._getSecurity = self._getSecurity_SMB2 self._getAttributes = self._getAttributes_SMB2 self._retrieveFile = self._retrieveFile_SMB2 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2 @@ -282,7 +260,7 @@ if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB2() - if smb_message.command != SMB2_COM_NEGOTIATE and smb_message.command != SMB2_COM_ECHO: + if smb_message.command != SMB2_COM_NEGOTIATE: smb_message.session_id = self.session_id if self.is_signing_active: @@ -304,7 +282,7 @@ if message.isReply: if message.command == SMB2_COM_NEGOTIATE: if message.status == 0: - self.has_negotiated = True + self.has_negotiated = True self.log.info('SMB2 dialect negotiation successful') self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) @@ -317,12 +295,25 @@ try: result = securityblob.decodeAuthResponseSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_COMPLETED: - self.has_authenticated = True + self.has_authenticated = True self.log.info('Authentication (on SMB2) successful!') + + # [MS-SMB2]: 3.2.5.3.1 + # If the security subsystem indicates that the session was established by an anonymous user, + # Session.SigningRequired MUST be set to FALSE. + # If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the + # SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP + # failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags + # field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired + # MUST be set to FALSE. + if message.payload.isGuestSession or message.payload.isAnonymousSession: + self.is_signing_active = False + self.log.info('Signing disabled because session is guest/anonymous') + self.onAuthOK() else: raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message) - except securityblob.BadSecurityBlobError, ex: + except securityblob.BadSecurityBlobError as ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED self.session_id = message.session_id @@ -330,20 +321,60 @@ result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) - except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ), ex: + except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) - elif message.status == 0xc000006d: # STATUS_LOGON_FAILURE - self.has_authenticated = False + elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE + or message.status == 0xc0000064 # STATUS_NO_SUCH_USER + or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD + self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Please check username and password.') self.onAuthFailed() + elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED + or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account or password has expired.') + self.onAuthFailed() + elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.') + self.onAuthFailed() + elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account has been disabled.') + self.onAuthFailed() + elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS + or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED + or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Not allowed.') + self.onAuthFailed() + elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Domain not trusted.') + self.onAuthFailed() + elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Workstation not trusted.') + self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status, message.raw_data, message) - req = self.pending_requests.pop(message.mid, None) - if req: - req.callback(message, **req.kwargs) - return True + if message.isAsync: + if message.status == 0x00000103: # STATUS_PENDING + req = self.pending_requests.pop(message.mid, None) + if req: + self.async_requests[message.async_id] = req + else: # All other status including SUCCESS + req = self.async_requests.pop(message.async_id, None) + if req: + req.callback(message, **req.kwargs) + return True + else: + req = self.pending_requests.pop(message.mid, None) + if req: + req.callback(message, **req.kwargs) + return True def _updateServerInfo_SMB2(self, payload): @@ -352,7 +383,7 @@ self.max_transact_size = payload.max_transact_size self.max_read_size = payload.max_read_size self.max_write_size = payload.max_write_size - self.use_plaintext_authentication = False # SMB2 never allows plaintext authentication + self.use_plaintext_authentication = False # SMB2 never allows plaintext authentication def _handleNegotiateResponse_SMB2(self, message): @@ -376,14 +407,15 @@ else: self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) - nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) - - ntlm_data = ntlm.generateAuthenticateMessage(server_flags, - nt_challenge_response, - lm_challenge_response, - session_key, - self.username, - self.domain) + nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) + + ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, + nt_challenge_response, + lm_challenge_response, + session_key, + self.username, + self.domain, + self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) @@ -399,13 +431,16 @@ self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: - self.is_signing_active = False + self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") - self.signing_session_key = (session_key + '\0'*16)[:16] + self.signing_session_key = session_signing_key + if self.log.isEnabledFor(logging.DEBUG): + self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key)) + if self.capabilities & CAP_EXTENDED_SECURITY: - self.signing_challenge_response = None + self.signing_challenge_response = None else: self.signing_challenge_response = blob else: @@ -432,7 +467,7 @@ m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid) messages_history.append(m) def connectSrvSvcCB(create_message, **kwargs): @@ -442,9 +477,9 @@ # The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706] # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ - binascii.unhexlify("""05 00 0b 03 10 00 00 00 74 00 00 00""".replace(' ', '')) + \ + binascii.unhexlify(b"""05 00 0b 03 10 00 00 00 74 00 00 00""".replace(b' ', b'')) + \ struct.pack('<I', call_id) + \ - binascii.unhexlify(""" + binascii.unhexlify(b""" b8 10 b8 10 00 00 00 00 02 00 00 00 00 00 01 00 c8 4f 32 4b 70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00 04 5d 88 8a eb 1c c9 11 9f e8 08 00 @@ -452,11 +487,11 @@ 70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00 2c 1c b7 6c 12 98 40 45 03 00 00 00 00 00 00 00 01 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2WriteRequest(create_message.payload.fid, data_bytes, 0)) - m.tid = create_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, fid = create_message.payload.fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) messages_history.append(m) else: errback(OperationFailure('Failed to list shares: Unable to locate Server Service RPC endpoint', messages_history)) @@ -465,45 +500,45 @@ messages_history.append(trans_message) if trans_message.status == 0: m = SMB2Message(SMB2ReadRequest(kwargs['fid'], read_len = 1024, read_offset = 0)) - m.tid = trans_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, fid = kwargs['fid']) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) messages_history.append(m) else: - closeFid(trans_message.tid, kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') + closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') def rpcReadCB(read_message, **kwargs): messages_history.append(read_message) if read_message.status == 0: call_id = self._getNextRPCCallID() - padding = '' + padding = b'' remote_name = '\\\\' + self.remote_name server_len = len(remote_name) + 1 server_bytes_len = server_len * 2 if server_len % 2 != 0: - padding = '\0\0' + padding = b'\0\0' server_bytes_len += 2 # The data bytes are the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ - binascii.unhexlify("""05 00 00 03 10 00 00 00""".replace(' ', '')) + \ + binascii.unhexlify(b"""05 00 00 03 10 00 00 00""".replace(b' ', b'')) + \ struct.pack('<HHI', 72+server_bytes_len, 0, call_id) + \ - binascii.unhexlify("""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(' ', '')) + \ + binascii.unhexlify(b"""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(b' ', b'')) + \ struct.pack('<III', server_len, 0, server_len) + \ (remote_name + '\0').encode('UTF-16LE') + padding + \ - binascii.unhexlify(""" + binascii.unhexlify(b""" 01 00 00 00 01 00 00 00 04 00 02 00 00 00 00 00 00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2IoctlRequest(kwargs['fid'], 0x0011C017, flags = 0x01, max_out_size = 8196, in_data = data_bytes)) - m.tid = read_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) messages_history.append(m) else: - closeFid(read_message.tid, kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') + closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') def listShareResultsCB(result_message, **kwargs): messages_history.append(result_message) @@ -511,14 +546,12 @@ # The payload.data_bytes will contain the results of the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. data_bytes = result_message.payload.out_data - if ord(data_bytes[3]) & 0x02 == 0: - sendReadRequest(result_message.tid, kwargs['fid'], data_bytes) - else: - decodeResults(result_message.tid, kwargs['fid'], data_bytes) - elif result_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[result_message.mid] = _PendingRequest(result_message.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) - else: - closeFid(result_message.tid, kwargs['fid']) + if data_bytes[3] & 0x02 == 0: + sendReadRequest(kwargs['tid'], kwargs['fid'], data_bytes) + else: + decodeResults(kwargs['tid'], kwargs['fid'], data_bytes) + else: + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def decodeResults(tid, fid, data_bytes): @@ -526,13 +559,13 @@ results = [ ] # A list of SharedDevice instances offset = 36 + 12 # You need to study the byte stream to understand the meaning of these constants for i in range(0, shares_count): - results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None)) + results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None)) offset += 12 for i in range(0, shares_count): max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 - results[i].name = unicode(data_bytes[offset:offset+length*2-2], 'UTF-16LE') + results[i].name = data_bytes[offset:offset+length*2-2].decode('UTF-16LE') if length % 2 != 0: offset += (length * 2 + 2) @@ -541,7 +574,7 @@ max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 - results[i].comments = unicode(data_bytes[offset:offset+length*2-2], 'UTF-16LE') + results[i].comments = data_bytes[offset:offset+length*2-2].decode('UTF-16LE') if length % 2 != 0: offset += (length * 2 + 2) @@ -557,23 +590,22 @@ m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, - fid = fid, data_bytes = data_bytes) + tid = tid, fid = fid, data_bytes = data_bytes) def readCB(read_message, **kwargs): messages_history.append(read_message) if read_message.status == 0: - data_len = read_message.payload.data_length data_bytes = read_message.payload.data - if ord(data_bytes[3]) & 0x02 == 0: - sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - closeFid(read_message.tid, kwargs['fid']) + if data_bytes[3] & 0x02 == 0: + sendReadRequest(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + decodeResults(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) - def closeFid(tid, fid, results = None, error = None): + def closeFid(tid, fid, results = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -581,12 +613,12 @@ messages_history.append(m) def closeCB(close_message, **kwargs): - if kwargs['results'] is not None: + if kwargs['results'] is not None: callback(kwargs['results']) - elif kwargs['error'] is not None: + elif kwargs['error'] is not None: errback(OperationFailure(kwargs['error'], messages_history)) - if not self.connected_trees.has_key(path): + if path not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -595,7 +627,7 @@ else: errback(OperationFailure('Failed to list shares: Unable to connect to IPC$', messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), path ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), path ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = path) messages_history.append(m) @@ -616,14 +648,14 @@ results = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, @@ -635,39 +667,44 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendQuery(create_message.tid, create_message.payload.fid, '') + sendQuery(kwargs['tid'], create_message.payload.fid, b'') + elif create_message.status == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID + errback(OperationFailure('Failed to list %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to list %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendQuery(tid, fid, data_buf): m = SMB2Message(SMB2QueryDirectoryRequest(fid, pattern, - info_class = 0x03, # FileBothDirectoryInformation + info_class = 0x25, # FileIdBothDirectoryInformation flags = 0, output_buf_len = self.max_transact_size)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, fid = fid, data_buf = data_buf) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = tid, fid = fid, data_buf = data_buf) messages_history.append(m) def queryCB(query_message, **kwargs): messages_history.append(query_message) if query_message.status == 0: data_buf = decodeQueryStruct(kwargs['data_buf'] + query_message.payload.data) - sendQuery(query_message.tid, kwargs['fid'], data_buf) - elif query_message.status == 0x80000006L: # STATUS_NO_MORE_FILES - closeFid(query_message.tid, kwargs['fid'], results = results) - else: - closeFid(query_message.tid, kwargs['fid'], error = query_message.status) + sendQuery(kwargs['tid'], kwargs['fid'], data_buf) + elif query_message.status == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # If there are no matching files, we just treat as success instead of failing + closeFid(kwargs['tid'], kwargs['fid'], results = results) + elif query_message.status == 0x80000006: # STATUS_NO_MORE_FILES + closeFid(kwargs['tid'], kwargs['fid'], results = results) + else: + closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def decodeQueryStruct(data_bytes): - # SMB_FIND_FILE_BOTH_DIRECTORY_INFO structure. See [MS-CIFS]: 2.2.8.1.7 and [MS-SMB]: 2.2.8.1.1 - info_format = '<IIQQQQQQIIIBB24s' + # FileIdBothDirectoryInformation structure. See [MS-SMB]: 2.2.8.1.3 and [MS-FSCC]: 2.4.17 + info_format = '<IIQQQQQQIIIBB24sHQ' info_size = struct.calcsize(info_format) data_length = len(data_bytes) @@ -679,25 +716,32 @@ next_offset, _, \ create_time, last_access_time, last_write_time, last_attr_change_time, \ file_size, alloc_size, file_attributes, filename_length, ea_size, \ - short_name_length, _, short_name = struct.unpack(info_format, data_bytes[offset:offset+info_size]) + short_name_length, _, short_name, _, file_id = struct.unpack(info_format, data_bytes[offset:offset+info_size]) offset2 = offset + info_size if offset2 + filename_length > data_length: return data_bytes[offset:] filename = data_bytes[offset2:offset2+filename_length].decode('UTF-16LE') - short_name = short_name.decode('UTF-16LE') - results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), - convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), - file_size, alloc_size, file_attributes, short_name, filename)) + short_name = short_name[:short_name_length].decode('UTF-16LE') + + accept_result = False + if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc + accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) + else: + accept_result = (file_attributes & search) > 0 + if accept_result: + results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), + convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, short_name, filename, file_id)) if next_offset: offset += next_offset else: break - return '' - - def closeFid(tid, fid, results = None, error = None): + return b'' + + def closeFid(tid, fid, results = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -705,12 +749,16 @@ messages_history.append(m) def closeCB(close_message, **kwargs): - if kwargs['results'] is not None: + if kwargs['results'] is not None: callback(kwargs['results']) - elif kwargs['error'] is not None: - errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) - - if not self.connected_trees.has_key(service_name): + elif kwargs['error'] is not None: + if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files + callback([ ]) + else: + errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) + + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -719,7 +767,7 @@ else: errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -758,21 +806,22 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: p = create_message.payload + filename = self._extractLastPathComponent(path) info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time, p.file_size, p.allocation_size, p.file_attributes, - unicode(path), unicode(path)) - closeFid(create_message.tid, p.fid, info = info) + filename, filename) + closeFid(kwargs['tid'], p.fid, info = info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history)) - def closeFid(tid, fid, info = None, error = None): + def closeFid(tid, fid, info = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -780,12 +829,12 @@ messages_history.append(m) def closeCB(close_message, **kwargs): - if kwargs['info'] is not None: + if kwargs['info'] is not None: callback(kwargs['info']) - elif kwargs['error'] is not None: + elif kwargs['error'] is not None: errback(OperationFailure('Failed to get attributes for %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -794,17 +843,14 @@ else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) else: sendCreate(self.connected_trees[service_name]) - def _retrieveFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): - return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0L, -1L, timeout) - - def _retrieveFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30): + def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') @@ -818,18 +864,102 @@ results = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + m = SMB2Message(SMB2CreateRequest(path, + file_attributes = 0, + access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + oplock = SMB2_OPLOCK_LEVEL_NONE, + impersonation = SEC_IMPERSONATE, + create_options = 0, + create_disp = FILE_OPEN)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) + messages_history.append(m) + + def createCB(create_message, **kwargs): + messages_history.append(create_message) + if create_message.status == 0: + m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, + flags = 0, + additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + info_type = SMB2_INFO_SECURITY, + file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12 + input_buf = '', + output_buf_len = self.max_transact_size)) + m.tid = kwargs['tid'] + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) + messages_history.append(m) + else: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history)) + + def queryCB(query_message, **kwargs): + messages_history.append(query_message) + if query_message.status == 0: + security = SecurityDescriptor.from_bytes(query_message.payload.data) + closeFid(kwargs['tid'], kwargs['fid'], result = security) + else: + closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) + + def closeFid(tid, fid, result = None, error = None): + m = SMB2Message(SMB2CloseRequest(fid)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error) + messages_history.append(m) + + def closeCB(close_message, **kwargs): + if kwargs['result'] is not None: + callback(kwargs['result']) + elif kwargs['error'] is not None: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if connect_message.status == 0: + self.connected_trees[service_name] = connect_message.tid + sendCreate(connect_message.tid) + else: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + sendCreate(self.connected_trees[service_name]) + + def _retrieveFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): + return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0, -1, timeout) + + def _retrieveFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + expiry_time = time.time() + timeout + path = path.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + messages_history = [ ] + results = [ ] + + def sendCreate(tid): + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, - share_access = FILE_SHARE_READ, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, @@ -847,16 +977,18 @@ flags = 0, additional_info = 0, info_type = SMB2_INFO_FILE, - file_info_class = 0x16, # FileStreamInformation [MS-FSCC] 2.4 - input_buf = '', + file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4 + input_buf = b'', output_buf_len = 4096)) - m.tid = create_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback, - fid = create_message.payload.fid, file_attributes = create_message.payload.file_attributes) + tid = kwargs['tid'], + fid = create_message.payload.fid, + file_attributes = create_message.payload.file_attributes) messages_history.append(m) else: - errback(OperationFailure('Failed to list %s on %s: Unable to open file' % ( path, service_name ), messages_history)) + errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def infoCB(info_message, **kwargs): messages_history.append(info_message) @@ -871,9 +1003,9 @@ remaining_len = file_len if starting_offset + remaining_len > file_len: remaining_len = file_len - starting_offset - sendRead(info_message.tid, kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) - else: - errback(OperationFailure('Failed to list %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) + sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) + else: + errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes): read_count = min(self.max_read_size, remaining_len) @@ -881,7 +1013,7 @@ m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, - fid = fid, offset = offset, + tid = tid, fid = fid, offset = offset, remaining_len = remaining_len, read_len = read_len, file_attributes = file_attributes) @@ -895,14 +1027,14 @@ remaining_len = kwargs['remaining_len'] - data_len if remaining_len > 0: - sendRead(read_message.tid, kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) - else: - closeFid(read_message.tid, kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) + sendRead(kwargs['tid'], kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) + else: + closeFid(kwargs['tid'], kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) else: messages_history.append(read_message) - closeFid(read_message.tid, kwargs['fid'], error = read_message.status) - - def closeFid(tid, fid, ret = None, error = None): + closeFid(kwargs['tid'], kwargs['fid'], error = read_message.status) + + def closeFid(tid, fid, ret = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -910,12 +1042,12 @@ messages_history.append(m) def closeCB(close_message, **kwargs): - if kwargs['ret'] is not None: + if kwargs['ret'] is not None: callback(kwargs['ret']) - elif kwargs['error'] is not None: + elif kwargs['error'] is not None: errback(OperationFailure('Failed to retrieve %s on %s: Read failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -924,7 +1056,7 @@ else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -932,12 +1064,13 @@ sendCreate(self.connected_trees[service_name]) def _storeFile_SMB2(self, service_name, path, file_obj, callback, errback, timeout = 30): - self._storeFileFromOffset_SMB2(service_name, path, file_obj, callback, errback, 0L, True, timeout) - - def _storeFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30): + self._storeFileFromOffset_SMB2(service_name, path, file_obj, callback, errback, 0, True, timeout) + + def _storeFileFromOffset_SMB2(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') + expiry_time = time.time() + timeout path = path.replace('/', '\\') if path.startswith('\\'): path = path[1:] @@ -946,7 +1079,7 @@ messages_history = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 20 00 00 00 10 00 04 00 @@ -955,7 +1088,7 @@ 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = ATTR_ARCHIVE, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_APPEND_DATA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | FILE_READ_EA | FILE_WRITE_EA | READ_CONTROL | SYNCHRONIZE, @@ -971,6 +1104,7 @@ messages_history.append(m) def createCB(create_message, **kwargs): + create_message.tid = kwargs['tid'] messages_history.append(create_message) if create_message.status == 0: sendWrite(create_message.tid, create_message.payload.fid, starting_offset) @@ -985,20 +1119,20 @@ m = SMB2Message(SMB2WriteRequest(fid, data, offset)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, fid = fid, offset = offset+data_len) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, tid = tid, fid = fid, offset = offset+data_len) else: closeFid(tid, fid, offset = offset) def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if write_message.status == 0: - sendWrite(write_message.tid, kwargs['fid'], kwargs['offset']) + sendWrite(kwargs['tid'], kwargs['fid'], kwargs['offset']) else: messages_history.append(write_message) - closeFid(write_message.tid, kwargs['fid']) + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) - def closeFid(tid, fid, error = None, offset = None): + def closeFid(tid, fid, error = None, offset = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -1006,12 +1140,12 @@ messages_history.append(m) def closeCB(close_message, **kwargs): - if kwargs['offset'] is not None: + if kwargs['offset'] is not None: callback(( file_obj, kwargs['offset'] )) # Note that this is a tuple of 2-elements - elif kwargs['error'] is not None: + elif kwargs['error'] is not None: errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -1020,7 +1154,7 @@ else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) messages_history.append(m) @@ -1028,27 +1162,110 @@ sendCreate(self.connected_trees[service_name]) - def _deleteFiles_SMB2(self, service_name, path_file_pattern, callback, errback, timeout = 30): + def _deleteFiles_SMB2(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout + pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] + else: + path_components = path.split('\\') + if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: + path = '\\'.join(path_components[:-1]) + pattern = path_components[-1] + messages_history, files_queue = [ ], [ ] + + if pattern is None: + path_components = path.split('\\') + if len(path_components) > 1: + files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) + else: + files_queue.append(( '', path )) + + def deleteCB(path): + if files_queue: + p, filename = files_queue.pop(0) + if filename: + if p: + filename = p + '\\' + filename + self._deleteFiles_SMB2__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) + else: + self._deleteDirectory_SMB2(service_name, p, deleteCB, errback, timeout) + else: + callback(path_file_pattern) + + def listCB(files_list): + files_queue.extend(files_list) + deleteCB(None) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if connect_message.status == 0: + self.connected_trees[service_name] = connect_message.tid + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + + def _deleteFiles_SMB2__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): + folder_queue = [ ] + files_list = [ ] + current_path = [ path ] + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL + + def listCB(results): + files = [ ] + for f in filter(lambda x: x.filename not in [ '.', '..' ], results): + if f.isDirectory: + if delete_matching_folders: + folder_queue.append(current_path[0]+'\\'+f.filename) + else: + files.append(( current_path[0], f.filename )) + if current_path[0]!=path and delete_matching_folders: + files.append(( current_path[0], None )) + + if files: + files_list[0:0] = files + + if folder_queue: + p = folder_queue.pop() + current_path[0] = p + self._listPath_SMB2(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) + else: + callback(files_list) + + self._listPath_SMB2(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) + + def _deleteFiles_SMB2__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" -28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 -44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 -00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 -00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 -00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 -51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) + create_context_data = binascii.unhexlify(b""" + 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 + 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 + 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 + 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 + 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 + 51 46 69 64 00 00 00 00 + """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, @@ -1064,9 +1281,14 @@ messages_history.append(m) def createCB(open_message, **kwargs): + open_message.tid = kwargs['tid'] messages_history.append(open_message) if open_message.status == 0: sendDelete(open_message.tid, open_message.payload.fid) + elif open_message.status == 0xc0000034: # STATUS_OBJECT_NAME_NOT_FOUND + callback(path) + elif open_message.status == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY + errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -1075,25 +1297,21 @@ additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO - data = '\x01')) - ''' - Resources: - https://msdn.microsoft.com/en-us/library/cc246560.aspx - https://msdn.microsoft.com/en-us/library/cc232098.aspx - ''' - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, fid = fid) + data = b'\x01')) + # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4.11 + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) messages_history.append(m) def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if delete_message.status == 0: - closeFid(delete_message.tid, kwargs['fid'], status = 0) - else: - closeFid(delete_message.tid, kwargs['fid'], status = delete_message.status) - - def closeFid(tid, fid, status = None): + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) + + def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -1102,27 +1320,13 @@ def closeCB(close_message, **kwargs): if kwargs['status'] == 0: - callback(path_file_pattern) + callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if connect_message.status == 0: - self.connected_trees[service_name] = connect_message.tid - sendCreate(connect_message.tid) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendCreate(self.connected_trees[service_name]) - - def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, timeout = 30): + sendCreate(tid) + + def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, file_attributes = ATTR_NORMAL, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') @@ -1135,14 +1339,14 @@ messages_history = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, @@ -1161,7 +1365,7 @@ def createCB(open_message, **kwargs): messages_history.append(open_message) if open_message.status == 0: - sendReset(open_message.tid, open_message.payload.fid) + sendReset(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -1170,27 +1374,21 @@ additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 4, # FileBasicInformation - data = struct.pack('qqqqii',0,0,0,0,0x80,0))) # FILE_ATTRIBUTE_NORMAL - ''' - Resources: - https://msdn.microsoft.com/en-us/library/cc246560.aspx - https://msdn.microsoft.com/en-us/library/cc232064.aspx - https://msdn.microsoft.com/en-us/library/cc232094.aspx - https://msdn.microsoft.com/en-us/library/cc232110.aspx - ''' - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, fid = fid) + data = struct.pack('qqqqii', 0, 0, 0, 0, file_attributes, 0))) + # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4, [MS-FSCC]: 2.4.7, [MS-FSCC]: 2.6 + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, tid = tid, fid = fid) messages_history.append(m) def resetCB(reset_message, **kwargs): messages_history.append(reset_message) if reset_message.status == 0: - closeFid(reset_message.tid, kwargs['fid'], status = 0) - else: - closeFid(reset_message.tid, kwargs['fid'], status = reset_message.status) - - def closeFid(tid, fid, status = None): + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = reset_message.status) + + def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -1203,7 +1401,7 @@ else: errback(OperationFailure('Failed to reset attributes of %s on %s: Reset failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -1212,7 +1410,7 @@ else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -1232,14 +1430,14 @@ messages_history = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_WRITE_DATA | FILE_READ_EA | FILE_WRITE_EA | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES | READ_CONTROL | DELETE | SYNCHRONIZE, @@ -1251,13 +1449,13 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - closeFid(create_message.tid, create_message.payload.fid) + closeFid(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) @@ -1271,7 +1469,7 @@ def closeCB(close_message, **kwargs): callback(path) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -1280,7 +1478,7 @@ else: errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -1300,14 +1498,14 @@ messages_history = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES, @@ -1325,7 +1523,7 @@ def createCB(open_message, **kwargs): messages_history.append(open_message) if open_message.status == 0: - sendDelete(open_message.tid, open_message.payload.fid) + sendDelete(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) @@ -1334,20 +1532,20 @@ additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO - data = '\x01')) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, fid = fid) + data = b'\x01')) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) messages_history.append(m) def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if delete_message.status == 0: - closeFid(delete_message.tid, kwargs['fid'], status = 0) - else: - closeFid(delete_message.tid, kwargs['fid'], status = delete_message.status) - - def closeFid(tid, fid, status = None): + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) + + def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -1360,7 +1558,7 @@ else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -1369,7 +1567,7 @@ else: errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -1396,14 +1594,14 @@ old_path = old_path[:-1] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(old_path, file_attributes = 0, access_mask = DELETE | FILE_READ_ATTRIBUTES | SYNCHRONIZE, @@ -1421,12 +1619,12 @@ def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendRename(create_message.tid, create_message.payload.fid) + sendRename(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) def sendRename(tid, fid): - data = '\x00'*16 + struct.pack('<I', len(new_path)*2) + new_path.encode('UTF-16LE') + data = b'\x00'*16 + struct.pack('<I', len(new_path)*2) + new_path.encode('UTF-16LE') m = SMB2Message(SMB2SetInfoRequest(fid, additional_info = 0, info_type = SMB2_INFO_FILE, @@ -1434,17 +1632,17 @@ data = data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, fid = fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, tid = tid, fid = fid) messages_history.append(m) def renameCB(rename_message, **kwargs): messages_history.append(rename_message) if rename_message.status == 0: - closeFid(rename_message.tid, kwargs['fid'], status = 0) - else: - closeFid(rename_message.tid, kwargs['fid'], status = rename_message.status) - - def closeFid(tid, fid, status = None): + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = rename_message.status) + + def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -1457,7 +1655,7 @@ else: errback(OperationFailure('Failed to rename %s on %s: Rename failed' % ( old_path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -1466,7 +1664,7 @@ else: errback(OperationFailure('Failed to rename %s on %s: Unable to connect to shared device' % ( old_path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -1486,12 +1684,12 @@ messages_history = [ ] def sendCreate(tid): - create_context_data = binascii.unhexlify(""" + create_context_data = binascii.unhexlify(b""" 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_ATTRIBUTES | SYNCHRONIZE, @@ -1509,7 +1707,7 @@ def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendEnumSnapshots(create_message.tid, create_message.payload.fid) + sendEnumSnapshots(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) @@ -1517,7 +1715,7 @@ m = SMB2Message(SMB2IoctlRequest(fid, ctlcode = 0x00144064, # FSCTL_SRV_ENUMERATE_SNAPSHOTS flags = 0x0001, - in_data = '')) + in_data = b'')) m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, enumSnapshotsCB, errback, tid = tid, fid = fid) @@ -1530,12 +1728,12 @@ snapshots_count = struct.unpack('<I', enum_message.payload.out_data[4:8])[0] for i in range(0, snapshots_count): s = enum_message.payload.out_data[12+i*50:12+48+i*50].decode('UTF-16LE') - results.append(datetime(*map(int, ( s[5:9], s[10:12], s[13:15], s[16:18], s[19:21], s[22:24] )))) + results.append(datetime(*list(map(int, ( s[5:9], s[10:12], s[13:15], s[16:18], s[19:21], s[22:24] ))))) closeFid(kwargs['tid'], kwargs['fid'], results = results) else: closeFid(kwargs['tid'], kwargs['fid'], status = enum_message.status) - def closeFid(tid, fid, status = None, results = None): + def closeFid(tid, fid, status = None, results = None): m = SMB2Message(SMB2CloseRequest(fid)) m.tid = tid self._sendSMBMessage(m) @@ -1543,12 +1741,12 @@ messages_history.append(m) def closeCB(close_message, **kwargs): - if kwargs['results'] is not None: + if kwargs['results'] is not None: callback(kwargs['results']) else: errback(OperationFailure('Failed to list snapshots %s on %s: List failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if connect_message.status == 0: @@ -1557,7 +1755,7 @@ else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -1621,7 +1819,7 @@ if message.isReply: if message.command == SMB_COM_NEGOTIATE: if not message.status.hasError: - self.has_negotiated = True + self.has_negotiated = True self.log.info('SMB dialect negotiation successful (ExtendedSecurity:%s)', message.hasExtendedSecurity) self._updateServerInfo(message.payload) self._handleNegotiateResponse(message) @@ -1636,23 +1834,52 @@ if result == securityblob.RESULT_ACCEPT_COMPLETED: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid - self.has_authenticated = True + self.has_authenticated = True self.log.info('Authentication (with extended security) successful!') self.onAuthOK() else: raise ProtocolError('SMB_COM_SESSION_SETUP_ANDX status is 0 but security blob negResult value is %d' % result, message.raw_data, message) - except securityblob.BadSecurityBlobError, ex: + except securityblob.BadSecurityBlobError as ex: raise ProtocolError(str(ex), message.raw_data, message) elif message.status.internal_value == 0xc0000016: # STATUS_MORE_PROCESSING_REQUIRED try: result, ntlm_token = securityblob.decodeChallengeSecurityBlob(message.payload.security_blob) if result == securityblob.RESULT_ACCEPT_INCOMPLETE: self._handleSessionChallenge(message, ntlm_token) - except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ), ex: + except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) - elif message.status.internal_value == 0xc000006d: # STATUS_LOGON_FAILURE - self.has_authenticated = False - self.log.info('Authentication (with extended security) failed. Please check username and password. You may need to enable/disable NTLMv2 authentication.') + elif (message.status.internal_value == 0xc000006d # STATUS_LOGON_FAILURE + or message.status.internal_value == 0xc0000064 # STATUS_NO_SUCH_USER + or message.status.internal_value == 0xc000006a): # STATUS_WRONG_PASSWORD + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Please check username and password.') + self.onAuthFailed() + elif (message.status.internal_value == 0xc0000193 # STATUS_ACCOUNT_EXPIRED + or message.status.internal_value == 0xC0000071): # STATUS_PASSWORD_EXPIRED + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account or password has expired.') + self.onAuthFailed() + elif message.status.internal_value == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account has been locked due to too many invalid logon attempts.') + self.onAuthFailed() + elif message.status.internal_value == 0xc0000072: # STATUS_ACCOUNT_DISABLED + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account has been disabled.') + self.onAuthFailed() + elif (message.status.internal_value == 0xc000006f # STATUS_INVALID_LOGON_HOURS + or message.status.internal_value == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED + or message.status.internal_value == 0xc0000070): # STATUS_INVALID_WORKSTATION + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Not allowed.') + self.onAuthFailed() + elif message.status.internal_value == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Domain not trusted.') + self.onAuthFailed() + elif message.status.internal_value == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status.internal_value, @@ -1661,11 +1888,11 @@ if message.status.internal_value == 0: self.log.debug('SMB uid is now %d', message.uid) self.uid = message.uid - self.has_authenticated = True + self.has_authenticated = True self.log.info('Authentication (without extended security) successful!') self.onAuthOK() else: - self.has_authenticated = False + self.has_authenticated = False self.log.info('Authentication (without extended security) failed. Please check username and password') self.onAuthFailed() elif message.command == SMB_COM_TREE_CONNECT_ANDX: @@ -1677,10 +1904,10 @@ if not message.status.hasError: self.connected_trees[req.kwargs['path']] = message.tid - req = self.pending_requests.pop(message.mid, None) + req = self.pending_requests.pop(message.mid, None) if req: req.callback(message, **req.kwargs) - return True + return True def _updateServerInfo_SMB1(self, payload): @@ -1712,14 +1939,15 @@ else: self.log.info('Performing NTLMv1 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) - nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) - - ntlm_data = ntlm.generateAuthenticateMessage(server_flags, - nt_challenge_response, - lm_challenge_response, - session_key, - self.username, - self.domain) + nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) + + ntlm_data, signing_session_key = ntlm.generateAuthenticateMessage(server_flags, + nt_challenge_response, + lm_challenge_response, + session_key, + self.username, + self.domain, + self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) @@ -1735,13 +1963,13 @@ self.log.info('Server supports SMB signing') self.is_signing_active = (self.sign_options == SMB.SIGN_WHEN_SUPPORTED) else: - self.is_signing_active = False + self.is_signing_active = False if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") - self.signing_session_key = session_key + self.signing_session_key = signing_session_key if self.capabilities & CAP_EXTENDED_SECURITY: - self.signing_challenge_response = None + self.signing_challenge_response = None else: self.signing_challenge_response = blob else: @@ -1757,14 +1985,14 @@ blob = securityblob.generateNegotiateSecurityBlob(ntlm_data) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__WithSecurityExtension(message.payload.session_key, blob))) else: - nt_password, _, _ = ntlm.generateChallengeResponseV1(self.password, message.payload.challenge, False) + nt_password, _, _ = ntlm.generateChallengeResponseV1(self.password, message.payload.challenge, False) self.log.info('Performing NTLMv1 authentication (without extended security) with challenge "%s" and hashed password of "%s"', binascii.hexlify(message.payload.challenge), binascii.hexlify(nt_password)) self._sendSMBMessage(SMBMessage(ComSessionSetupAndxRequest__NoSecurityExtension(message.payload.session_key, self.username, nt_password, - True, + True, self.domain))) def _listShares_SMB1(self, callback, errback, timeout = 30): @@ -1798,13 +2026,13 @@ # The data_bytes are binding call to Server Service RPC using DCE v1.1 RPC over SMB. See [MS-SRVS] and [C706] # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ - binascii.unhexlify("""05 00 0b 03 10 00 00 00 48 00 00 00""".replace(' ', '')) + \ + binascii.unhexlify(b"""05 00 0b 03 10 00 00 00 48 00 00 00""".replace(b' ', b'')) + \ struct.pack('<I', call_id) + \ - binascii.unhexlify(""" + binascii.unhexlify(b""" b8 10 b8 10 00 00 00 00 01 00 00 00 00 00 01 00 c8 4f 32 4b 70 16 d3 01 12 78 5a 47 bf 6e e1 88 03 00 00 00 04 5d 88 8a eb 1c c9 11 9f e8 08 00 -2b 10 48 60 02 00 00 00""".replace(' ', '').replace('\n', '')) +2b 10 48 60 02 00 00 00""".replace(b' ', b'').replace(b'\n', b'')) m = SMBMessage(ComTransactionRequest(max_params_count = 0, max_data_count = 4280, max_setup_count = 0, @@ -1822,11 +2050,11 @@ if not trans_message.status.hasError: call_id = self._getNextRPCCallID() - padding = '' + padding = b'' server_len = len(self.remote_name) + 1 server_bytes_len = server_len * 2 if server_len % 2 != 0: - padding = '\0\0' + padding = b'\0\0' server_bytes_len += 2 # See [MS-CIFS]: 2.2.5.6.1 for more information on TRANS_TRANSACT_NMPIPE (0x0026) parameters @@ -1834,15 +2062,15 @@ # The data bytes are the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. # If you wish to understand the meanings of the byte stream, I would suggest you use a recent version of WireShark to packet capture the stream data_bytes = \ - binascii.unhexlify("""05 00 00 03 10 00 00 00""".replace(' ', '')) + \ + binascii.unhexlify(b"""05 00 00 03 10 00 00 00""".replace(b' ', b'')) + \ struct.pack('<HHI', 72+server_bytes_len, 0, call_id) + \ - binascii.unhexlify("""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(' ', '')) + \ + binascii.unhexlify(b"""4c 00 00 00 00 00 0f 00 00 00 02 00""".replace(b' ', b'')) + \ struct.pack('<III', server_len, 0, server_len) + \ (self.remote_name + '\0').encode('UTF-16LE') + padding + \ - binascii.unhexlify(""" + binascii.unhexlify(b""" 01 00 00 00 01 00 00 00 04 00 02 00 00 00 00 00 00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00 -""".replace(' ', '').replace('\n', '')) +""".replace(b' ', b'').replace(b'\n', b'')) m = SMBMessage(ComTransactionRequest(max_params_count = 0, max_data_count = 4280, max_setup_count = 0, @@ -1862,7 +2090,7 @@ # The payload.data_bytes will contain the results of the RPC call to NetrShareEnum (Opnum 15) at Server Service RPC. data_bytes = result_message.payload.data_bytes - if ord(data_bytes[3]) & 0x02 == 0: + if data_bytes[3] & 0x02 == 0: sendReadRequest(result_message.tid, kwargs['fid'], data_bytes) else: decodeResults(result_message.tid, kwargs['fid'], data_bytes) @@ -1875,13 +2103,13 @@ results = [ ] # A list of SharedDevice instances offset = 36 + 12 # You need to study the byte stream to understand the meaning of these constants for i in range(0, shares_count): - results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None)) + results.append(SharedDevice(struct.unpack('<I', data_bytes[offset+4:offset+8])[0], None, None)) offset += 12 for i in range(0, shares_count): max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 - results[i].name = unicode(data_bytes[offset:offset+length*2-2], 'UTF-16LE') + results[i].name = data_bytes[offset:offset+length*2-2].decode('UTF-16LE') if length % 2 != 0: offset += (length * 2 + 2) @@ -1890,7 +2118,7 @@ max_length, _, length = struct.unpack('<III', data_bytes[offset:offset+12]) offset += 12 - results[i].comments = unicode(data_bytes[offset:offset+length*2-2], 'UTF-16LE') + results[i].comments = data_bytes[offset:offset+length*2-2].decode('UTF-16LE') if length % 2 != 0: offset += (length * 2 + 2) @@ -1913,13 +2141,12 @@ def readCB(read_message, **kwargs): messages_history.append(read_message) if not read_message.status.hasError: - data_len = read_message.payload.data_length data_bytes = read_message.payload.data - if ord(data_bytes[3]) & 0x02 == 0: - sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) + if data_bytes[3] & 0x02 == 0: + sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) @@ -1938,7 +2165,7 @@ else: errback(OperationFailure('Failed to list shares: Unable to connect to IPC$', messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), path ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), path ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = path) messages_history.append(m) @@ -1954,19 +2181,19 @@ messages_history = [ ] results = [ ] - def sendFindFirst(tid, support_dfs=False): + def sendFindFirst(tid, support_dfs=False): setup_bytes = struct.pack('<H', 0x0001) # TRANS2_FIND_FIRST2 sub-command. See [MS-CIFS]: 2.2.6.2.1 params_bytes = \ struct.pack('<HHHHI', - search, # SearchAttributes + search & 0xFFFF, # SearchAttributes (need to restrict the values due to introduction of SMB_FILE_ATTRIBUTE_INCL_NORMAL) 100, # SearchCount 0x0006, # Flags: SMB_FIND_CLOSE_AT_EOS | SMB_FIND_RETURN_RESUME_KEYS 0x0104, # InfoLevel: SMB_FIND_FILE_BOTH_DIRECTORY_INFO - 0x0000) # SearchStorageType + 0x0000) # SearchStorageType (seems to be ignored by Windows) if support_dfs: params_bytes += ("\\" + self.remote_name + "\\" + service_name + path + pattern + '\0').encode('UTF-16LE') else: - params_bytes += (path + pattern).encode('UTF-16LE') + params_bytes += (path + pattern + '\0').encode('UTF-16LE') m = SMBMessage(ComTransaction2Request(max_params_count = 10, max_data_count = 16644, @@ -1977,7 +2204,7 @@ if support_dfs: m.flags2 |= SMB_FLAGS2_DFS self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, findFirstCB, errback, support_dfs=support_dfs) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, findFirstCB, errback) messages_history.append(m) def decodeFindStruct(data_bytes): @@ -2002,53 +2229,64 @@ filename = data_bytes[offset2:offset2+filename_length].decode('UTF-16LE') short_name = short_name.decode('UTF-16LE') - results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), - convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), - file_size, alloc_size, file_attributes, short_name, filename)) + + accept_result = False + if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc + accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) + else: + accept_result = (file_attributes & search) > 0 + if accept_result: + results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), + convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, short_name, filename)) if next_offset: offset += next_offset else: break - return '' + return b'' def findFirstCB(find_message, **kwargs): messages_history.append(find_message) if not find_message.status.hasError: - if not kwargs.has_key('total_count'): + if 'total_count' not in kwargs: # TRANS2_FIND_FIRST2 response. [MS-CIFS]: 2.2.6.2.2 sid, search_count, end_of_search, _, last_name_offset = struct.unpack('<HHHHH', find_message.payload.params_bytes[:10]) - kwargs.update({ 'sid': sid, 'end_of_search': end_of_search, 'last_name_offset': last_name_offset, 'data_buf': '' }) + kwargs.update({ 'sid': sid, 'end_of_search': end_of_search, 'last_name_offset': last_name_offset, 'data_buf': b'' }) else: sid, end_of_search, last_name_offset = kwargs['sid'], kwargs['end_of_search'], kwargs['last_name_offset'] - send_next = True + send_next = True if find_message.payload.data_bytes: d = decodeFindStruct(kwargs['data_buf'] + find_message.payload.data_bytes) - if not kwargs.has_key('data_count'): + if 'data_count' not in kwargs: if len(find_message.payload.data_bytes) != find_message.payload.total_data_count: kwargs.update({ 'data_count': len(find_message.payload.data_bytes), 'total_count': find_message.payload.total_data_count, 'data_buf': d, }) - send_next = False + send_next = False else: kwargs['data_count'] += len(find_message.payload.data_bytes) kwargs['total_count'] = min(find_message.payload.total_data_count, kwargs['total_count']) kwargs['data_buf'] = d if kwargs['data_count'] != kwargs['total_count']: - send_next = False + send_next = False if not send_next: self.pending_requests[find_message.mid] = _PendingRequest(find_message.mid, expiry_time, findFirstCB, errback, **kwargs) elif end_of_search: callback(results) else: - sendFindNext(find_message.tid, sid, last_name_offset, kwargs.get('support_dfs', False)) - else: - errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) - - def sendFindNext(tid, sid, resume_key, support_dfs=False): + sendFindNext(find_message.tid, sid, 0, results[-1].filename, kwargs.get('support_dfs', False)) + else: + if find_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files + callback([ ]) + else: + errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) + + def sendFindNext(tid, sid, resume_key, resume_file, support_dfs): setup_bytes = struct.pack('<H', 0x0002) # TRANS2_FIND_NEXT2 sub-command. See [MS-CIFS]: 2.2.6.3.1 params_bytes = \ struct.pack('<HHHIH', @@ -2056,11 +2294,8 @@ 100, # SearchCount 0x0104, # InfoLevel: SMB_FIND_FILE_BOTH_DIRECTORY_INFO resume_key, # ResumeKey - 0x000a) # Flags: SMB_FIND_RETURN_RESUME_KEYS | SMB_FIND_CLOSE_AT_EOS | SMB_FIND_RETURN_RESUME_KEYS - if support_dfs: - params_bytes += ("\\" + self.remote_name + "\\" + service_name + path + pattern + '\0').encode('UTF-16LE') - else: - params_bytes += (path + pattern).encode('UTF-16LE') + 0x0006) # Flags: SMB_FIND_RETURN_RESUME_KEYS | SMB_FIND_CLOSE_AT_EOS + params_bytes += (resume_file+'\0').encode('UTF-16LE') m = SMBMessage(ComTransaction2Request(max_params_count = 10, max_data_count = 16644, @@ -2077,36 +2312,36 @@ def findNextCB(find_message, **kwargs): messages_history.append(find_message) if not find_message.status.hasError: - if not kwargs.has_key('total_count'): + if 'total_count' not in kwargs: # TRANS2_FIND_NEXT2 response. [MS-CIFS]: 2.2.6.3.2 search_count, end_of_search, _, last_name_offset = struct.unpack('<HHHH', find_message.payload.params_bytes[:8]) - kwargs.update({ 'end_of_search': end_of_search, 'last_name_offset': last_name_offset, 'data_buf': '' }) + kwargs.update({ 'end_of_search': end_of_search, 'last_name_offset': last_name_offset, 'data_buf': b'' }) else: end_of_search, last_name_offset = kwargs['end_of_search'], kwargs['last_name_offset'] - send_next = True + send_next = True if find_message.payload.data_bytes: d = decodeFindStruct(kwargs['data_buf'] + find_message.payload.data_bytes) - if not kwargs.has_key('data_count'): + if 'data_count' not in kwargs: if len(find_message.payload.data_bytes) != find_message.payload.total_data_count: kwargs.update({ 'data_count': len(find_message.payload.data_bytes), 'total_count': find_message.payload.total_data_count, 'data_buf': d, }) - send_next = False + send_next = False else: kwargs['data_count'] += len(find_message.payload.data_bytes) kwargs['total_count'] = min(find_message.payload.total_data_count, kwargs['total_count']) kwargs['data_buf'] = d if kwargs['data_count'] != kwargs['total_count']: - send_next = False + send_next = False if not send_next: self.pending_requests[find_message.mid] = _PendingRequest(find_message.mid, expiry_time, findNextCB, errback, **kwargs) elif end_of_search: callback(results) else: - sendFindNext(find_message.tid, kwargs['sid'], last_name_offset, kwargs.get('support_dfs', False)) + sendFindNext(find_message.tid, kwargs['sid'], 0, results[-1].filename, kwargs.get('support_dfs', False)) else: errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) @@ -2126,9 +2361,9 @@ messages_history.append(m) def dfsReferralCB(dfs_message, **kwargs): - sendFindFirst(dfs_message.tid, True) - - if not self.connected_trees.has_key(service_name): + sendFindFirst(dfs_message.tid, True) + + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: @@ -2136,11 +2371,11 @@ if connect_message.payload.optional_support & SMB_TREE_CONNECTX_SUPPORT_DFS: sendDFSReferral(connect_message.tid) else: - sendFindFirst(connect_message.tid, False) + sendFindFirst(connect_message.tid, False) else: errback(OperationFailure('Failed to list %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -2184,14 +2419,15 @@ info_size = struct.calcsize(info_format) create_time, last_access_time, last_write_time, last_attr_change_time, \ file_attributes, _, alloc_size, file_size = struct.unpack(info_format, query_message.payload.data_bytes[:info_size]) - - info = SharedFile(create_time, last_access_time, last_write_time, last_attr_change_time, - file_size, alloc_size, file_attributes, unicode(path), unicode(path)) + filename = self._extractLastPathComponent(path) + + info = SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, filename, filename) callback(info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Read failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: @@ -2200,15 +2436,18 @@ else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) else: sendQuery(self.connected_trees[service_name]) + def _getSecurity_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): + raise NotReadyError('getSecurity is not yet implemented for SMB1') + def _retrieveFile_SMB1(self, service_name, path, file_obj, callback, errback, timeout = 30): - return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0L, -1L, timeout) + return self._retrieveFileFromOffset(service_name, path, file_obj, callback, errback, 0, -1, timeout) def _retrieveFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, max_length, timeout = 30): if not self.has_authenticated: @@ -2233,9 +2472,9 @@ if not open_message.status.hasError: if max_length == 0: closeFid(open_message.tid, open_message.payload.fid) - callback(( file_obj, open_message.payload.file_attributes, 0L )) - else: - sendRead(open_message.tid, open_message.payload.fid, starting_offset, open_message.payload.file_attributes, 0L, max_length) + callback(( file_obj, open_message.payload.file_attributes, 0 )) + else: + sendRead(open_message.tid, open_message.payload.fid, starting_offset, open_message.payload.file_attributes, 0, max_length) else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -2285,7 +2524,7 @@ self._sendSMBMessage(m) messages_history.append(m) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: @@ -2294,7 +2533,7 @@ else: errback(OperationFailure('Failed to retrieve %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) messages_history.append(m) @@ -2302,9 +2541,9 @@ sendOpen(self.connected_trees[service_name]) def _storeFile_SMB1(self, service_name, path, file_obj, callback, errback, timeout = 30): - self._storeFileFromOffset_SMB1(service_name, path, file_obj, callback, errback, 0L, True, timeout) - - def _storeFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30): + self._storeFileFromOffset_SMB1(service_name, path, file_obj, callback, errback, 0, True, timeout) + + def _storeFileFromOffset_SMB1(self, service_name, path, file_obj, callback, errback, starting_offset, truncate = False, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') @@ -2330,8 +2569,8 @@ errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def sendWrite(tid, fid, offset): - # For message signing, the total SMB message size must be not exceed the max_buffer_size. Non-message signing does not have this limitation - write_count = min((self.is_signing_active and (self.max_buffer_size-64)) or self.max_raw_size, 0xFFFF-1) # Need to minus 1 byte from 0xFFFF because of the first NULL byte in the ComWriteAndxRequest message data + # [MS-SMB] 2.2.4.5.2.2: The total SMB message size (inclusive of SMB header) must be not exceed the max_buffer_size. + write_count = min(self.max_buffer_size-64, 0xFFFF-64) # SMB header is 32-bytes. We factor in another 32-bytes for the message parameter block data_bytes = file_obj.read(write_count) data_len = len(data_bytes) if data_len > 0: @@ -2358,7 +2597,7 @@ self._sendSMBMessage(m) messages_history.append(m) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: @@ -2367,18 +2606,106 @@ else: errback(OperationFailure('Failed to store %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) messages_history.append(m) else: sendOpen(self.connected_trees[service_name]) - def _deleteFiles_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): + def _deleteFiles_SMB1(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') + expiry_time = time.time() + timeout + pattern = None path = path_file_pattern.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + else: + path_components = path.split('\\') + if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: + path = '\\'.join(path_components[:-1]) + pattern = path_components[-1] + messages_history, files_queue = [ ], [ ] + + if pattern is None: + path_components = path.split('\\') + if len(path_components) > 1: + files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) + else: + files_queue.append(( '', path )) + + def deleteCB(path): + if files_queue: + p, filename = files_queue.pop(0) + if filename: + if p: + filename = p + '\\' + filename + self._deleteFiles_SMB1__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) + else: + self._deleteDirectory_SMB1(service_name, p, deleteCB, errback, timeout = 30) + else: + callback(path_file_pattern) + + def listCB(files_list): + files_queue.extend(files_list) + deleteCB(None) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if not connect_message.status.hasError: + self.connected_trees[service_name] = connect_message.tid + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + + def _deleteFiles_SMB1__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): + folder_queue = [ ] + files_list = [ ] + current_path = [ path ] + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL + + def listCB(results): + files = [ ] + for f in filter(lambda x: x.filename not in [ '.', '..' ], results): + if f.isDirectory: + if delete_matching_folders: + folder_queue.append(current_path[0]+'\\'+f.filename) + else: + files.append(( current_path[0], f.filename )) + if current_path[0]!=path and delete_matching_folders: + files.append(( current_path[0], None )) + + if files: + files_list[0:0] = files + + if folder_queue: + p = folder_queue.pop() + current_path[0] = p + self._listPath_SMB1(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) + else: + callback(files_list) + + self._listPath_SMB1(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) + + def _deleteFiles_SMB1__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendDelete(tid): @@ -2392,97 +2719,90 @@ def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if not delete_message.status.hasError: + callback(path) + elif delete_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # If there are no matching files, we just treat as success instead of failing callback(path_file_pattern) - else: - errback(OperationFailure('Failed to store %s on %s: Delete failed' % ( path, service_name ), messages_history)) - - if not self.connected_trees.has_key(service_name): + elif delete_message.status.internal_value == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY + errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) + elif delete_message.status.internal_value == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID + errback(OperationFailure('Failed to delete %s on %s: Path not found' % ( path, service_name ), messages_history)) + else: + errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) + + sendDelete(tid) + + def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, file_attributes=ATTR_NORMAL, timeout = 30): + raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') + + def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + path = path.replace('/', '\\') + messages_history = [ ] + + def sendCreate(tid): + m = SMBMessage(ComCreateDirectoryRequest(path)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) + messages_history.append(m) + + def createCB(create_message, **kwargs): + messages_history.append(create_message) + if not create_message.status.hasError: + callback(path) + else: + errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if not connect_message.status.hasError: + self.connected_trees[service_name] = connect_message.tid + sendCreate(connect_message.tid) + else: + errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) + messages_history.append(m) + else: + sendCreate(self.connected_trees[service_name]) + + def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + path = path.replace('/', '\\') + messages_history = [ ] + + def sendDelete(tid): + m = SMBMessage(ComDeleteDirectoryRequest(path)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) + messages_history.append(m) + + def deleteCB(delete_message, **kwargs): + messages_history.append(delete_message) + if not delete_message.status.hasError: + callback(path) + else: + errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) + + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: self.connected_trees[service_name] = connect_message.tid sendDelete(connect_message.tid) else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendDelete(self.connected_trees[service_name]) - - def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): - raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') - - def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - path = path.replace('/', '\\') - messages_history = [ ] - - def sendCreate(tid): - m = SMBMessage(ComCreateDirectoryRequest(path)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) - messages_history.append(m) - - def createCB(create_message, **kwargs): - messages_history.append(create_message) - if not create_message.status.hasError: - callback(path) - else: - errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) - - if not self.connected_trees.has_key(service_name): - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if not connect_message.status.hasError: - self.connected_trees[service_name] = connect_message.tid - sendCreate(connect_message.tid) - else: - errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendCreate(self.connected_trees[service_name]) - - def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - path = path.replace('/', '\\') - messages_history = [ ] - - def sendDelete(tid): - m = SMBMessage(ComDeleteDirectoryRequest(path)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) - messages_history.append(m) - - def deleteCB(delete_message, **kwargs): - messages_history.append(delete_message) - if not delete_message.status.hasError: - callback(path) - else: - errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) - - if not self.connected_trees.has_key(service_name): - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if not connect_message.status.hasError: - self.connected_trees[service_name] = connect_message.tid - sendDelete(connect_message.tid) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + errback(OperationFailure('Failed to delete directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) messages_history.append(m) @@ -2513,7 +2833,7 @@ else: errback(OperationFailure('Failed to rename %s on %s: Rename failed' % ( old_path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: @@ -2522,7 +2842,7 @@ else: errback(OperationFailure('Failed to rename %s on %s: Unable to connect to shared device' % ( old_path, service_name ), messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) messages_history.append(m) @@ -2583,7 +2903,7 @@ snapshots_count = struct.unpack('<I', enum_message.payload.data_bytes[4:8])[0] for i in range(0, snapshots_count): s = enum_message.payload.data_bytes[12+i*50:12+48+i*50].decode('UTF-16LE') - results.append(datetime(*map(int, ( s[5:9], s[10:12], s[13:15], s[16:18], s[19:21], s[22:24] )))) + results.append(datetime(*list(map(int, ( s[5:9], s[10:12], s[13:15], s[16:18], s[19:21], s[22:24] ))))) closeFid(kwargs['tid'], kwargs['fid']) callback(results) else: @@ -2596,7 +2916,7 @@ self._sendSMBMessage(m) messages_history.append(m) - if not self.connected_trees.has_key(service_name): + if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): messages_history.append(connect_message) if not connect_message.status.hasError: @@ -2605,7 +2925,7 @@ else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) messages_history.append(m) @@ -2614,6 +2934,9 @@ def _echo_SMB1(self, data, callback, errback, timeout = 30): messages_history = [ ] + + if not isinstance(data, type(b'')): + raise TypeError('Echo data must be %s not %s' % (type(b'').__name__, type(data).__name__)) def echoCB(echo_message, **kwargs): messages_history.append(echo_message) @@ -2627,10 +2950,18 @@ self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, echoCB, errback) messages_history.append(m) + def _extractLastPathComponent(self, path): + return path.replace('\\', '/').split('/')[-1] +
    [docs]class SharedDevice: """ Contains information about a single shared device on the remote server. + + The following attributes are available: + + * name : An unicode string containing the name of the shared device + * comments : An unicode string containing the user description of the shared device """ # The following constants are taken from [MS-SRVS]: 2.2.2.4 @@ -2640,7 +2971,7 @@ COMM_DEVICE = 0x02 IPC = 0x03 - def __init__(self, type, name, comments): + def __init__(self, type, name, comments): self._type = type self.name = name #: An unicode string containing the name of the shared device self.comments = comments #: An unicode string containing the user description of the shared device @@ -2673,7 +3004,7 @@ return bool(self._type & 0x40000000) def __unicode__(self): - return u'Shared device: %s (type:0x%02x comments:%s)' % (self.name, self.type, self.comments )
    + return 'Shared device: %s (type:0x%02x comments:%s)' % (self.name, self.type, self.comments )
    [docs]class SharedFile: @@ -2685,23 +3016,37 @@ If you encounter *SharedFile* instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains - one of these prohibited characters: "\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). + one of these prohibited characters: "\\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). + + The following attributes are available: + + * create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server + * last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server + * last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server + * last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server + * file_size : File size in number of bytes + * alloc_size : Total number of bytes allocated to store this file + * file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. + * short_name : Unicode string containing the short name of this file (usually in 8.3 notation) + * filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. + * file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 """ - def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename): + def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None): self.create_time = create_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server self.last_access_time = last_access_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server self.last_write_time = last_write_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server self.last_attr_change_time = last_attr_change_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server self.file_size = file_size #: File size in number of bytes self.alloc_size = alloc_size #: Total number of bytes allocated to store this file - self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3 + self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. self.short_name = short_name #: Unicode string containing the short name of this file (usually in 8.3 notation) self.filename = filename #: Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. + self.file_id = file_id #: Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 @property def isDirectory(self): - """A convenient property to return True if this file resource is a directory on the remote server""" + """A convenience property to return True if this file resource is a directory on the remote server""" return bool(self.file_attributes & ATTR_DIRECTORY) @property @@ -2709,13 +3054,23 @@ """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY) + @property + def isNormal(self): + """ + A convenient property to return True if this is a normal file. + + Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + """ + return (self.file_attributes==ATTR_NORMAL) or ((self.file_attributes & 0xff)==0) + def __unicode__(self): - return u'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory )
    + return 'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory )
    class _PendingRequest: - def __init__(self, mid, expiry_time, callback, errback, **kwargs): + def __init__(self, mid, expiry_time, callback, errback, **kwargs): self.mid = mid self.expiry_time = expiry_time self.callback = callback @@ -2723,7 +3078,22 @@ self.kwargs = kwargs
    +
    +
    + +
    @@ -2734,13 +3104,17 @@
  • index
  • - - +
  • + modules |
  • + + + diff --git a/docs/html/_modules/smb/security_descriptors.html b/docs/html/_modules/smb/security_descriptors.html new file mode 100644 index 0000000..372b0b4 --- /dev/null +++ b/docs/html/_modules/smb/security_descriptors.html @@ -0,0 +1,447 @@ + + + + + + + + smb.security_descriptors — pysmb 1.2.7 documentation + + + + + + + + + + + +
    +
    +
    +
    + +

    Source code for smb.security_descriptors

    +"""
    +This module implements security descriptors, and the partial structures
    +used in them, as specified in [MS-DTYP].
    +"""
    +
    +import struct
    +
    +
    +# Security descriptor control flags
    +# [MS-DTYP]: 2.4.6
    +SECURITY_DESCRIPTOR_OWNER_DEFAULTED = 0x0001
    +SECURITY_DESCRIPTOR_GROUP_DEFAULTED = 0x0002
    +SECURITY_DESCRIPTOR_DACL_PRESENT = 0x0004
    +SECURITY_DESCRIPTOR_DACL_DEFAULTED = 0x0008
    +SECURITY_DESCRIPTOR_SACL_PRESENT = 0x0010
    +SECURITY_DESCRIPTOR_SACL_DEFAULTED = 0x0020
    +SECURITY_DESCRIPTOR_SERVER_SECURITY = 0x0040
    +SECURITY_DESCRIPTOR_DACL_TRUSTED = 0x0080
    +SECURITY_DESCRIPTOR_DACL_COMPUTED_INHERITANCE_REQUIRED = 0x0100
    +SECURITY_DESCRIPTOR_SACL_COMPUTED_INHERITANCE_REQUIRED = 0x0200
    +SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED = 0x0400
    +SECURITY_DESCRIPTOR_SACL_AUTO_INHERITED = 0x0800
    +SECURITY_DESCRIPTOR_DACL_PROTECTED = 0x1000
    +SECURITY_DESCRIPTOR_SACL_PROTECTED = 0x2000
    +SECURITY_DESCRIPTOR_RM_CONTROL_VALID = 0x4000
    +SECURITY_DESCRIPTOR_SELF_RELATIVE = 0x8000
    +
    +# ACE types
    +# [MS-DTYP]: 2.4.4.1
    +ACE_TYPE_ACCESS_ALLOWED = 0x00
    +ACE_TYPE_ACCESS_DENIED = 0x01
    +ACE_TYPE_SYSTEM_AUDIT = 0x02
    +ACE_TYPE_SYSTEM_ALARM = 0x03
    +ACE_TYPE_ACCESS_ALLOWED_COMPOUND = 0x04
    +ACE_TYPE_ACCESS_ALLOWED_OBJECT = 0x05
    +ACE_TYPE_ACCESS_DENIED_OBJECT = 0x06
    +ACE_TYPE_SYSTEM_AUDIT_OBJECT = 0x07
    +ACE_TYPE_SYSTEM_ALARM_OBJECT = 0x08
    +ACE_TYPE_ACCESS_ALLOWED_CALLBACK = 0x09
    +ACE_TYPE_ACCESS_DENIED_CALLBACK = 0x0A
    +ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = 0x0B
    +ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT = 0x0C
    +ACE_TYPE_SYSTEM_AUDIT_CALLBACK = 0x0D
    +ACE_TYPE_SYSTEM_ALARM_CALLBACK = 0x0E
    +ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = 0x0F
    +ACE_TYPE_SYSTEM_ALARM_CALLBACK_OBJECT = 0x10
    +ACE_TYPE_SYSTEM_MANDATORY_LABEL = 0x11
    +ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE = 0x12
    +ACE_TYPE_SYSTEM_SCOPED_POLICY_ID = 0x13
    +
    +# ACE flags
    +# [MS-DTYP]: 2.4.4.1
    +ACE_FLAG_OBJECT_INHERIT = 0x01
    +ACE_FLAG_CONTAINER_INHERIT = 0x02
    +ACE_FLAG_NO_PROPAGATE_INHERIT = 0x04
    +ACE_FLAG_INHERIT_ONLY = 0x08
    +ACE_FLAG_INHERITED = 0x10
    +ACE_FLAG_SUCCESSFUL_ACCESS = 0x40
    +ACE_FLAG_FAILED_ACCESS = 0x80
    +
    +# Pre-defined well-known SIDs
    +# [MS-DTYP]: 2.4.2.4
    +SID_NULL = "S-1-0-0"
    +SID_EVERYONE = "S-1-1-0"
    +SID_LOCAL = "S-1-2-0"
    +SID_CONSOLE_LOGON = "S-1-2-1"
    +SID_CREATOR_OWNER = "S-1-3-0"
    +SID_CREATOR_GROUP = "S-1-3-1"
    +SID_OWNER_SERVER = "S-1-3-2"
    +SID_GROUP_SERVER = "S-1-3-3"
    +SID_OWNER_RIGHTS = "S-1-3-4"
    +SID_NT_AUTHORITY = "S-1-5"
    +SID_DIALUP = "S-1-5-1"
    +SID_NETWORK = "S-1-5-2"
    +SID_BATCH = "S-1-5-3"
    +SID_INTERACTIVE = "S-1-5-4"
    +SID_SERVICE = "S-1-5-6"
    +SID_ANONYMOUS = "S-1-5-7"
    +SID_PROXY = "S-1-5-8"
    +SID_ENTERPRISE_DOMAIN_CONTROLLERS = "S-1-5-9"
    +SID_PRINCIPAL_SELF = "S-1-5-10"
    +SID_AUTHENTICATED_USERS = "S-1-5-11"
    +SID_RESTRICTED_CODE = "S-1-5-12"
    +SID_TERMINAL_SERVER_USER = "S-1-5-13"
    +SID_REMOTE_INTERACTIVE_LOGON = "S-1-5-14"
    +SID_THIS_ORGANIZATION = "S-1-5-15"
    +SID_IUSR = "S-1-5-17"
    +SID_LOCAL_SYSTEM = "S-1-5-18"
    +SID_LOCAL_SERVICE = "S-1-5-19"
    +SID_NETWORK_SERVICE = "S-1-5-20"
    +SID_COMPOUNDED_AUTHENTICATION = "S-1-5-21-0-0-0-496"
    +SID_CLAIMS_VALID = "S-1-5-21-0-0-0-497"
    +SID_BUILTIN_ADMINISTRATORS = "S-1-5-32-544"
    +SID_BUILTIN_USERS = "S-1-5-32-545"
    +SID_BUILTIN_GUESTS = "S-1-5-32-546"
    +SID_POWER_USERS = "S-1-5-32-547"
    +SID_ACCOUNT_OPERATORS = "S-1-5-32-548"
    +SID_SERVER_OPERATORS = "S-1-5-32-549"
    +SID_PRINTER_OPERATORS = "S-1-5-32-550"
    +SID_BACKUP_OPERATORS = "S-1-5-32-551"
    +SID_REPLICATOR = "S-1-5-32-552"
    +SID_ALIAS_PREW2KCOMPACC = "S-1-5-32-554"
    +SID_REMOTE_DESKTOP = "S-1-5-32-555"
    +SID_NETWORK_CONFIGURATION_OPS = "S-1-5-32-556"
    +SID_INCOMING_FOREST_TRUST_BUILDERS = "S-1-5-32-557"
    +SID_PERFMON_USERS = "S-1-5-32-558"
    +SID_PERFLOG_USERS = "S-1-5-32-559"
    +SID_WINDOWS_AUTHORIZATION_ACCESS_GROUP = "S-1-5-32-560"
    +SID_TERMINAL_SERVER_LICENSE_SERVERS = "S-1-5-32-561"
    +SID_DISTRIBUTED_COM_USERS = "S-1-5-32-562"
    +SID_IIS_IUSRS = "S-1-5-32-568"
    +SID_CRYPTOGRAPHIC_OPERATORS = "S-1-5-32-569"
    +SID_EVENT_LOG_READERS = "S-1-5-32-573"
    +SID_CERTIFICATE_SERVICE_DCOM_ACCESS = "S-1-5-32-574"
    +SID_RDS_REMOTE_ACCESS_SERVERS = "S-1-5-32-575"
    +SID_RDS_ENDPOINT_SERVERS = "S-1-5-32-576"
    +SID_RDS_MANAGEMENT_SERVERS = "S-1-5-32-577"
    +SID_HYPER_V_ADMINS = "S-1-5-32-578"
    +SID_ACCESS_CONTROL_ASSISTANCE_OPS = "S-1-5-32-579"
    +SID_REMOTE_MANAGEMENT_USERS = "S-1-5-32-580"
    +SID_WRITE_RESTRICTED_CODE = "S-1-5-33"
    +SID_NTLM_AUTHENTICATION = "S-1-5-64-10"
    +SID_SCHANNEL_AUTHENTICATION = "S-1-5-64-14"
    +SID_DIGEST_AUTHENTICATION = "S-1-5-64-21"
    +SID_THIS_ORGANIZATION_CERTIFICATE = "S-1-5-65-1"
    +SID_NT_SERVICE = "S-1-5-80"
    +SID_USER_MODE_DRIVERS = "S-1-5-84-0-0-0-0-0"
    +SID_LOCAL_ACCOUNT = "S-1-5-113"
    +SID_LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP = "S-1-5-114"
    +SID_OTHER_ORGANIZATION = "S-1-5-1000"
    +SID_ALL_APP_PACKAGES = "S-1-15-2-1"
    +SID_ML_UNTRUSTED = "S-1-16-0"
    +SID_ML_LOW = "S-1-16-4096"
    +SID_ML_MEDIUM = "S-1-16-8192"
    +SID_ML_MEDIUM_PLUS = "S-1-16-8448"
    +SID_ML_HIGH = "S-1-16-12288"
    +SID_ML_SYSTEM = "S-1-16-16384"
    +SID_ML_PROTECTED_PROCESS = "S-1-16-20480"
    +SID_AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY = "S-1-18-1"
    +SID_SERVICE_ASSERTED_IDENTITY = "S-1-18-2"
    +SID_FRESH_PUBLIC_KEY_IDENTITY = "S-1-18-3"
    +SID_KEY_TRUST_IDENTITY = "S-1-18-4"
    +SID_KEY_PROPERTY_MFA = "S-1-18-5"
    +SID_KEY_PROPERTY_ATTESTATION = "S-1-18-6"
    +
    +
    +
    [docs]class SID(object): + """ + A Windows security identifier. Represents a single principal, such a + user or a group, as a sequence of numbers consisting of the revision, + identifier authority, and a variable-length list of subauthorities. + + See [MS-DTYP]: 2.4.2 + """ + def __init__(self, revision, identifier_authority, subauthorities): + #: Revision, should always be 1. + self.revision = revision + #: An integer representing the identifier authority. + self.identifier_authority = identifier_authority + #: A list of integers representing all subauthorities. + self.subauthorities = subauthorities + + def __str__(self): + """ + String representation, as specified in [MS-DTYP]: 2.4.2.1 + """ + if self.identifier_authority >= 2**32: + id_auth = '%#x' % (self.identifier_authority,) + else: + id_auth = self.identifier_authority + auths = [self.revision, id_auth] + self.subauthorities + return 'S-' + '-'.join(str(subauth) for subauth in auths) + + def __repr__(self): + return 'SID(%r)' % (str(self),) + + @classmethod + def from_bytes(cls, data, return_tail=False): + revision, subauth_count = struct.unpack('<BB', data[:2]) + identifier_authority = struct.unpack('>Q', b'\x00\x00' + data[2:8])[0] + subauth_data = data[8:] + subauthorities = [struct.unpack('<L', subauth_data[4 * i : 4 * (i+1)])[0] + for i in range(subauth_count)] + sid = cls(revision, identifier_authority, subauthorities) + if return_tail: + return sid, subauth_data[4 * subauth_count :] + return sid
    + + +
    [docs]class ACE(object): + """ + Represents a single access control entry. + + See [MS-DTYP]: 2.4.4 + """ + HEADER_FORMAT = '<BBH' + + def __init__(self, type_, flags, mask, sid, additional_data): + #: An integer representing the type of the ACE. One of the + #: ``ACE_TYPE_*`` constants. Corresponds to the ``AceType`` field + #: from [MS-DTYP] 2.4.4.1. + self.type = type_ + #: An integer bitmask with ACE flags, corresponds to the + #: ``AceFlags`` field. + self.flags = flags + #: An integer representing the ``ACCESS_MASK`` as specified in + #: [MS-DTYP] 2.4.3. + self.mask = mask + #: The :class:`SID` of a trustee. + self.sid = sid + #: A dictionary of additional fields present in the ACE, depending + #: on the type. The following fields can be present: + #: + #: * ``flags`` + #: * ``object_type`` + #: * ``inherited_object_type`` + #: * ``application_data`` + #: * ``attribute_data`` + self.additional_data = additional_data + + def __repr__(self): + return "ACE(type=%#04x, flags=%#04x, mask=%#010x, sid=%s)" % ( + self.type, self.flags, self.mask, self.sid, + ) + + @property + def isInheritOnly(self): + """Convenience property which indicates if this ACE is inherit + only, meaning that it doesn't apply to the object itself.""" + return bool(self.flags & ACE_FLAG_INHERIT_ONLY) + + @classmethod + def from_bytes(cls, data): + header_size = struct.calcsize(cls.HEADER_FORMAT) + header = data[:header_size] + type_, flags, size = struct.unpack(cls.HEADER_FORMAT, header) + + assert len(data) >= size + + body = data[header_size:size] + additional_data = {} + + # In all ACE types, the mask immediately follows the header. + mask = struct.unpack('<I', body[:4])[0] + body = body[4:] + + # All OBJECT-type ACEs contain additional flags, and two GUIDs as + # the following fields. + if type_ in (ACE_TYPE_ACCESS_ALLOWED_OBJECT, + ACE_TYPE_ACCESS_DENIED_OBJECT, + ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT, + ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT, + ACE_TYPE_SYSTEM_AUDIT_OBJECT, + ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT): + additional_data['flags'] = struct.unpack('<I', body[:4])[0] + additional_data['object_type'] = body[4:20] + additional_data['inherited_object_type'] = body[20:36] + body = body[36:] + + # Then the SID in all types. + sid, body = SID.from_bytes(body, return_tail=True) + + # CALLBACK-type ACEs (and for some obscure reason, + # SYSTEM_AUDIT_OBJECT) have a final tail of application data. + if type_ in (ACE_TYPE_ACCESS_ALLOWED_CALLBACK, + ACE_TYPE_ACCESS_DENIED_CALLBACK, + ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT, + ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT, + ACE_TYPE_SYSTEM_AUDIT_OBJECT, + ACE_TYPE_SYSTEM_AUDIT_CALLBACK, + ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT): + additional_data['application_data'] = body + + # SYSTEM_RESOURCE_ATTRIBUTE ACEs have a tail of attribute data. + if type_ == ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE: + additional_data['attribute_data'] = body + + return cls(type_, flags, mask, sid, additional_data)
    + + +
    [docs]class ACL(object): + """ + Access control list, encapsulating a sequence of access control + entries. + + See [MS-DTYP]: 2.4.5 + """ + HEADER_FORMAT = '<BBHHH' + + def __init__(self, revision, aces): + #: Integer value of the revision. + self.revision = revision + #: List of :class:`ACE` instances. + self.aces = aces + + def __repr__(self): + return "ACL(%r)" % (self.aces,) + + @classmethod + def from_bytes(cls, data): + revision = None + aces = [] + + header_size = struct.calcsize(cls.HEADER_FORMAT) + header, remaining = data[:header_size], data[header_size:] + revision, sbz1, size, count, sbz2 = struct.unpack(cls.HEADER_FORMAT, header) + + assert len(data) >= size + + for i in range(count): + ace_size = struct.unpack('<H', remaining[2:4])[0] + ace_data, remaining = remaining[:ace_size], remaining[ace_size:] + aces.append(ACE.from_bytes(ace_data)) + + return cls(revision, aces)
    + + +
    [docs]class SecurityDescriptor(object): + """ + Represents a security descriptor. + + See [MS-DTYP]: 2.4.6 + """ + + HEADER_FORMAT = '<BBHIIII' + + def __init__(self, flags, owner, group, dacl, sacl): + #: Integer bitmask of control flags. Corresponds to the + #: ``Control`` field in [MS-DTYP] 2.4.6. + self.flags = flags + #: Instance of :class:`SID` representing the owner user. + self.owner = owner + #: Instance of :class:`SID` representing the owner group. + self.group = group + #: Instance of :class:`ACL` representing the discretionary access + #: control list, which specifies access restrictions of an object. + self.dacl = dacl + #: Instance of :class:`ACL` representing the system access control + #: list, which specifies audit logging of an object. + self.sacl = sacl + + @classmethod + def from_bytes(cls, data): + owner = None + group = None + dacl = None + sacl = None + + header = data[:struct.calcsize(cls.HEADER_FORMAT)] + (revision, sbz1, flags, owner_offset, group_offset, sacl_offset, + dacl_offset) = struct.unpack(cls.HEADER_FORMAT, header) + + assert revision == 1 + assert flags & SECURITY_DESCRIPTOR_SELF_RELATIVE + for offset in (owner_offset, group_offset, sacl_offset, dacl_offset): + assert 0 <= offset < len(data) + + if owner_offset: + owner = SID.from_bytes(data[owner_offset:]) + if group_offset: + group = SID.from_bytes(data[group_offset:]) + if dacl_offset: + dacl = ACL.from_bytes(data[dacl_offset:]) + if sacl_offset: + sacl = ACL.from_bytes(data[sacl_offset:]) + + return cls(flags, owner, group, dacl, sacl)
    +
    + +
    +
    +
    +
    + +
    +
    + + + + \ No newline at end of file diff --git a/docs/html/_modules/smb/smb_structs.html b/docs/html/_modules/smb/smb_structs.html index 61587b1..0bdb0b3 100644 --- a/docs/html/_modules/smb/smb_structs.html +++ b/docs/html/_modules/smb/smb_structs.html @@ -1,59 +1,34 @@ - - - - + + + + - - - smb.smb_structs — pysmb 1.1.18 documentation - + + + smb.smb_structs — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + - +
    @@ -61,26 +36,26 @@

    Source code for smb.smb_structs

    -
    +
     import os, sys, struct, types, logging, binascii, time
    -from StringIO import StringIO
    -from smb_constants import *
    +from io import StringIO
    +from .smb_constants import *
     
     
     # Set to True if you want to enable support for extended security. Required for Windows Vista and later
    -SUPPORT_EXTENDED_SECURITY = True
    +SUPPORT_EXTENDED_SECURITY = True
     
     # Set to True if you want to enable SMB2 protocol.
    -SUPPORT_SMB2 = True
    +SUPPORT_SMB2 = True
     
     # Supported dialects
     DIALECTS = [ ]
    -for i, ( name, dialect ) in enumerate([ ( 'NT_LAN_MANAGER_DIALECT', 'NT LM 0.12' ), ]):
    +for i, ( name, dialect ) in enumerate([ ( 'NT_LAN_MANAGER_DIALECT', b'NT LM 0.12' ), ]):
         DIALECTS.append(dialect)
         globals()[name] = i
     
     DIALECTS2 = [ ]
    -for i, ( name, dialect ) in enumerate([ ( 'SMB2_DIALECT', 'SMB 2.002' ) ]):
    +for i, ( name, dialect ) in enumerate([ ( 'SMB2_DIALECT', b'SMB 2.002' ) ]):
         DIALECTS2.append(dialect)
         globals()[name] = i + len(DIALECTS)
     
    @@ -95,12 +70,12 @@
     
     
    [docs]class ProtocolError(Exception): - def __init__(self, message, data_buf = None, smb_message = None): + def __init__(self, message, data_buf = None, smb_message = None): self.message = message self.data_buf = data_buf self.smb_message = smb_message - def __str__(self): + def __str__(self): b = StringIO() b.write(self.message + os.linesep) if self.smb_message: @@ -109,24 +84,23 @@ if self.data_buf: b.write('=' * 20 + ' SMB Data Packet (hex) ' + '=' * 20 + os.linesep) - b.write(binascii.hexlify(self.data_buf)) + b.write(str(binascii.hexlify(self.data_buf))) b.write(os.linesep) return b.getvalue()
    class SMB2ProtocolHeaderError(ProtocolError): - def __init__(self): - ProtocolError.__init__(self, "Packet header belongs to SMB2") + def __init__(self): + ProtocolError.__init__(self, "Packet header belongs to SMB2")
    [docs]class OperationFailure(Exception): - def __init__(self, message, smb_messages): - self.args = [ message ] + def __init__(self, message, smb_messages): self.message = message self.smb_messages = smb_messages - def __str__(self): + def __str__(self): b = StringIO() b.write(self.message + os.linesep) @@ -137,7 +111,7 @@ b.write(str(m)) b.write('SMB Data Packet (hex):' + os.linesep) b.write('----------------------' + os.linesep) - b.write(binascii.hexlify(m.raw_data)) + b.write(str(binascii.hexlify(m.raw_data))) b.write(os.linesep) return b.getvalue()
    @@ -145,14 +119,14 @@ class SMBError: - def __init__(self): + def __init__(self): self.reset() def reset(self): - self.internal_value = 0L - self.is_ntstatus = True - - def __str__(self): + self.internal_value = 0 + self.is_ntstatus = True + + def __str__(self): if self.is_ntstatus: return 'NTSTATUS=0x%08X' % self.internal_value else: @@ -171,13 +145,13 @@ log = logging.getLogger('SMB.SMBMessage') protocol = 1 - def __init__(self, payload = None): + def __init__(self, payload = None): self.reset() if payload: self.payload = payload self.payload.initMessage(self) - def __str__(self): + def __str__(self): b = StringIO() b.write('Command: 0x%02X (%s) %s' % ( self.command, SMB_COMMAND_NAMES.get(self.command, '<unknown>'), os.linesep )) b.write('Status: %s %s' % ( str(self.status), os.linesep )) @@ -188,12 +162,12 @@ b.write('MID: %d %s' % ( self.mid, os.linesep )) b.write('TID: %d %s' % ( self.tid, os.linesep )) b.write('Security: 0x%016X %s' % ( self.security, os.linesep )) - b.write('Parameters: %d bytes %s%s %s' % ( len(self.parameters_data), os.linesep, binascii.hexlify(self.parameters_data), os.linesep )) - b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, binascii.hexlify(self.data), os.linesep )) + b.write('Parameters: %d bytes %s%s %s' % ( len(self.parameters_data), os.linesep, str(binascii.hexlify(self.parameters_data)), os.linesep )) + b.write('Data: %d bytes %s%s %s' % ( len(self.data), os.linesep, str(binascii.hexlify(self.data)), os.linesep )) return b.getvalue() def reset(self): - self.raw_data = '' + self.raw_data = b'' self.command = 0 self.status = SMBError() self.flags = 0 @@ -202,10 +176,14 @@ self.tid = 0 self.uid = 0 self.mid = 0 - self.security = 0L - self.parameters_data = '' - self.data = '' - self.payload = None + self.security = 0 + self.parameters_data = b'' + self.data = b'' + self.payload = None + + @property + def isAsync(self): + return bool(self.flags & SMB2_FLAGS_ASYNC_COMMAND) @property def isReply(self): @@ -231,7 +209,7 @@ assert parameters_len % 2 == 0 headers_data = struct.pack(self.HEADER_STRUCT_FORMAT, - '\xFFSMB', self.command, self.status.internal_value, self.flags, + b'\xFFSMB', self.command, self.status.internal_value, self.flags, self.flags2, (self.pid >> 16) & 0xFFFF, self.security, self.tid, self.pid & 0xFFFF, self.uid, self.mid, int(parameters_len / 2)) return headers_data + self.parameters_data + struct.pack('<H', len(self.data)) + self.data @@ -259,9 +237,9 @@ self.flags2, pid_high, self.security, self.tid, \ pid_low, self.uid, self.mid, params_count = struct.unpack(self.HEADER_STRUCT_FORMAT, buf[:self.HEADER_STRUCT_SIZE]) - if protocol == '\xFESMB': + if protocol == b'\xFESMB': raise SMB2ProtocolHeaderError() - if protocol != '\xFFSMB': + if protocol != b'\xFFSMB': raise ProtocolError('Invalid 4-byte protocol field', buf) self.pid = (pid_high << 16) | pid_low @@ -317,7 +295,7 @@ class Payload: - DEFAULT_ANDX_PARAM_HEADER = '\xFF\x00\x00\x00' + DEFAULT_ANDX_PARAM_HEADER = b'\xFF\x00\x00\x00' DEFAULT_ANDX_PARAM_SIZE = 4 def initMessage(self, message): @@ -326,10 +304,10 @@ # support SMB_FLAGS2_UNICODE by default. assert message.payload == self message.flags = SMB_FLAGS_CASE_INSENSITIVE | SMB_FLAGS_CANONICALIZED_PATHS - message.flags2 = SMB_FLAGS2_UNICODE | SMB_FLAGS2_NT_STATUS | SMB_FLAGS2_LONG_NAMES | SMB_FLAGS2_EAS + message.flags2 = SMB_FLAGS2_UNICODE | SMB_FLAGS2_NT_STATUS | SMB_FLAGS2_IS_LONG_NAME | SMB_FLAGS2_LONG_NAMES if SUPPORT_EXTENDED_SECURITY: - message.flags2 |= SMB_FLAGS2_EXTENDED_SECURITY | SMB_FLAGS2_SMB_SECURITY_SIGNATURE + message.flags2 |= SMB_FLAGS2_EXTENDED_SECURITY def prepare(self, message): raise NotImplementedError @@ -352,11 +330,11 @@ def prepare(self, message): assert message.payload == self - message.parameters_data = '' + message.parameters_data = b'' if SUPPORT_SMB2: - message.data = ''.join(map(lambda s: '\x02'+s+'\x00', DIALECTS + DIALECTS2)) + message.data = b''.join([b'\x02'+s+b'\x00' for s in DIALECTS + DIALECTS2]) else: - message.data = ''.join(map(lambda s: '\x02'+s+'\x00', DIALECTS)) + message.data = b''.join([b'\x02'+s+b'\x00' for s in DIALECTS]) class ComNegotiateResponse(Payload): @@ -430,11 +408,11 @@ if data_len >= self.challenge_length: self.challenge = message.data[:self.challenge_length] - s = '' + s = b'' offset = self.challenge_length while offset < data_len: _s = message.data[offset:offset+2] - if _s == '\0\0': + if _s == b'\0\0': self.domain = s.decode('UTF-16LE') break else: @@ -463,7 +441,7 @@ PAYLOAD_STRUCT_FORMAT = '<HHHIHII' - def __init__(self, session_key, security_blob): + def __init__(self, session_key, security_blob): self.session_key = session_key self.security_blob = security_blob @@ -485,8 +463,8 @@ message.data = self.security_blob if (SMBMessage.HEADER_STRUCT_SIZE + len(message.parameters_data) + len(message.data)) % 2 != 0: - message.data = message.data + '\0' - message.data = message.data + '\0' * 4 + message.data = message.data + b'\0' + message.data = message.data + b'\0' * 4 class ComSessionSetupAndxRequest__NoSecurityExtension(Payload): @@ -498,7 +476,7 @@ PAYLOAD_STRUCT_FORMAT = '<HHHIHHII' - def __init__(self, session_key, username, password, is_unicode, domain): + def __init__(self, session_key, username, password, is_unicode, domain): self.username = username self.session_key = session_key self.password = password @@ -529,20 +507,20 @@ message.data = self.password if (est_offset + len(message.data)) % 2 != 0 and message.flags2 & SMB_FLAGS2_UNICODE: - message.data = message.data + '\0' + message.data = message.data + b'\0' if message.flags2 & SMB_FLAGS2_UNICODE: - message.data = message.data + self.username.encode('UTF-16LE') + '\0' + message.data = message.data + self.username.encode('UTF-16LE') + b'\0' else: - message.data = message.data + str(self.username) + '\0' + message.data = message.data + str(self.username).encode('UTF-8') + b'\0' if (est_offset + len(message.data)) % 2 != 0 and message.flags2 & SMB_FLAGS2_UNICODE: - message.data = message.data + '\0' + message.data = message.data + b'\0' if message.flags2 & SMB_FLAGS2_UNICODE: - message.data = message.data + self.domain.encode('UTF-16LE') + '\0\0' + 'pysmb'.encode('UTF-16LE') + '\0\0' + message.data = message.data + self.domain.encode('UTF-16LE') + b'\0\0' + 'pysmb'.encode('UTF-16LE') + b'\0\0' else: - message.data = message.data + self.domain + '\0pysmb\0' + message.data = message.data + self.domain.encode('UTF-8') + b'\0pysmb\0' class ComSessionSetupAndxResponse(Payload): @@ -605,7 +583,7 @@ PAYLOAD_STRUCT_FORMAT = '<HH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, path, service, password = ''): + def __init__(self, path, service, password = ''): self.path = path self.service = service self.password = password + '\0' @@ -621,15 +599,15 @@ struct.pack(self.PAYLOAD_STRUCT_FORMAT, 0x08 | \ ((message.hasExtendedSecurity and 0x0004) or 0x00) | \ - ((message.tid and message.tid != 0xFFFF and 0x0001) or 0x00), # Disconnect tid, if message.tid must be non-zero + ((message.tid and message.tid != 0xffff and 0x0001) or 0x00), # Disconnect tid, if message.tid must be non-zero password_len) - padding = '' + padding = b'' if password_len % 2 == 0: - padding = '\0' + padding = b'\0' # Note that service field is never encoded in UTF-16LE. [MS-CIFS]: 2.2.1.1 - message.data = self.password + padding + self.path.encode('UTF-16LE') + '\0\0' + self.service + '\0' + message.data = self.password.encode('UTF-8') + padding + self.path.encode('UTF-16LE') + b'\0\0' + self.service.encode('UTF-8') + b'\0' class ComTreeConnectAndxResponse(Payload): @@ -668,7 +646,7 @@ PAYLOAD_STRUCT_FORMAT = '<BHIIIQIIIIIB' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, filename, flags = 0, root_fid = 0, access_mask = 0, allocation_size = 0L, ext_attr = 0, + def __init__(self, filename, flags = 0, root_fid = 0, access_mask = 0, allocation_size = 0, ext_attr = 0, share_access = 0, create_disp = 0, create_options = 0, impersonation = 0, security_flags = 0): self.filename = (filename + '\0').encode('UTF-16LE') self.flags = flags @@ -705,9 +683,9 @@ self.impersonation, # ImpersonationLevel self.security_flags) # SecurityFlags - padding = '' + padding = b'' if (message.HEADER_STRUCT_SIZE + len(message.parameters_data)) % 2 != 0: - padding = '\0' + padding = b'\0' message.data = padding + self.filename @@ -747,9 +725,9 @@ PAYLOAD_STRUCT_FORMAT = '<HHHHBBHIHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, max_params_count, max_data_count, max_setup_count, + def __init__(self, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, - params_bytes = '', data_bytes = '', setup_bytes = '', + params_bytes = b'', data_bytes = b'', setup_bytes = b'', flags = 0, timeout = 0, name = "\\PIPE\\"): self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) @@ -774,16 +752,16 @@ params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) - padding0 = '' + padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 2 != 0: - padding0 = '\0' + padding0 = b'\0' offset += 1 offset += name_len # For the name field - padding1 = '' + padding1 = b'' if offset % 4 != 0: - padding1 = '\0'*(4-offset%4) + padding1 = b'\0'*(4-offset%4) offset += (4-offset%4) if params_bytes_len > 0: @@ -792,9 +770,9 @@ else: params_bytes_offset = 0 - padding2 = '' + padding2 = b'' if offset % 4 != 0: - padding2 = '\0'*(4-offset%4) + padding2 = b'\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: @@ -887,9 +865,9 @@ PAYLOAD_STRUCT_FORMAT = 'HHHHBBHIHHHHHH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, max_params_count, max_data_count, max_setup_count, + def __init__(self, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, - params_bytes = '', data_bytes = '', setup_bytes = '', + params_bytes = b'', data_bytes = b'', setup_bytes = b'', flags = 0, timeout = 0): self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) @@ -910,18 +888,18 @@ setup_bytes_len = len(self.setup_bytes) params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) - name = '\0\0' - - padding0 = '' + name = b'\0\0' + + padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 2 != 0: - padding0 = '\0' + padding0 = b'\0' offset += 1 offset += 2 # For the name field - padding1 = '' + padding1 = b'' if offset % 4 != 0: - padding1 = '\0'*(4-offset%4) + padding1 = b'\0'*(4-offset%4) if params_bytes_len > 0: params_bytes_offset = offset @@ -929,9 +907,9 @@ else: params_bytes_offset = 0 - padding2 = '' + padding2 = b'' if offset % 4 != 0: - padding2 = '\0'*(4-offset%4) + padding2 = b'\0'*(4-offset%4) if data_bytes_len > 0: data_bytes_offset = offset @@ -1023,7 +1001,7 @@ PAYLOAD_STRUCT_FORMAT = '<HI' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, fid, last_modified_time = 0xFFFFFFFF): + def __init__(self, fid, last_modified_time = 0xFFFFFFFF): self.fid = fid self.last_modified_time = last_modified_time @@ -1033,7 +1011,7 @@ def prepare(self, message): message.parameters_data = struct.pack(self.PAYLOAD_STRUCT_FORMAT, self.fid, self.last_modified_time) - message.data = '' + message.data = b'' class ComOpenAndxRequest(Payload): @@ -1046,7 +1024,7 @@ PAYLOAD_STRUCT_FORMAT = '<HHHHIHIII' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, filename, access_mode, open_mode, flags = 0x0000, search_attributes = 0, file_attributes = 0, create_time = 0, timeout = 0): + def __init__(self, filename, access_mode, open_mode, flags = 0x0000, search_attributes = 0, file_attributes = 0, create_time = 0, timeout = 0): """ @param create_time: Epoch time value to indicate the time of creation for this file. If zero, we will automatically assign the current time @type create_time: int @@ -1080,7 +1058,7 @@ 0, # Timeout (in milli-secs) 0) # Reserved - message.data = '\0' + self.filename.encode('UTF-16LE') + '\0\0' + message.data = b'\0' + self.filename.encode('UTF-16LE') + b'\0\0' class ComOpenAndxResponse(Payload): @@ -1127,7 +1105,7 @@ PAYLOAD_STRUCT_FORMAT = '<HIIHHHHHI' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, fid, data_bytes, offset, write_mode = 0, timeout = 0): + def __init__(self, fid, data_bytes, offset, write_mode = 0, timeout = 0): """ @param timeout: Number of milliseconds to wait for blocked write request before failing. Must be zero for writing to regular file @type timeout: int @@ -1161,7 +1139,7 @@ data_offset, # DataOffset self.offset >> 32) # OffsetHigh field defined in [MS-SMB]: 2.2.4.3.1 - message.data = '\0' + self.data_bytes + message.data = b'\0' + self.data_bytes class ComWriteAndxResponse(Payload): @@ -1197,7 +1175,7 @@ PAYLOAD_STRUCT_FORMAT = '<HIHHIHI' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, fid, offset, max_return_bytes_count, min_return_bytes_count, timeout = 0, remaining = 0): + def __init__(self, fid, offset, max_return_bytes_count, min_return_bytes_count, timeout = 0, remaining = 0): """ @param timeout: If reading from a regular file, this parameter must be 0. @type timeout: int @@ -1225,7 +1203,7 @@ self.remaining, # In [MS-CIFS]: 2.2.4.42.1, this field must be set to 0x0000 self.offset >> 32) - message.data = '' + message.data = b'' class ComReadAndxResponse(Payload): @@ -1261,7 +1239,7 @@ - [MS-CIFS]: 2.2.4.7.1 """ - def __init__(self, filename_pattern, search_attributes = 0): + def __init__(self, filename_pattern, search_attributes = 0): self.filename_pattern = filename_pattern self.search_attributes = search_attributes @@ -1271,7 +1249,7 @@ def prepare(self, message): message.parameters_data = struct.pack('<H', self.search_attributes) - message.data = '\x04' + self.filename_pattern.encode('UTF-16LE') + '\0\0' + message.data = b'\x04' + self.filename_pattern.encode('UTF-16LE') + b'\0\0' class ComCreateDirectoryRequest(Payload): @@ -1284,7 +1262,7 @@ - [MS-CIFS]: 2.2.4.1.1 """ - def __init__(self, path): + def __init__(self, path): self.path = path def initMessage(self, message): @@ -1292,8 +1270,8 @@ message.command = SMB_COM_CREATE_DIRECTORY def prepare(self, message): - message.parameters_data = '' - message.data = '\x04' + self.path.encode('UTF-16LE') + '\0\0' + message.parameters_data = b'' + message.data = b'\x04' + self.path.encode('UTF-16LE') + b'\0\0' class ComDeleteDirectoryRequest(Payload): @@ -1303,7 +1281,7 @@ - [MS-CIFS]: 2.2.4.2.1 """ - def __init__(self, path): + def __init__(self, path): self.path = path def initMessage(self, message): @@ -1311,8 +1289,8 @@ message.command = SMB_COM_DELETE_DIRECTORY def prepare(self, message): - message.parameters_data = '' - message.data = '\x04' + self.path.encode('UTF-16LE') + '\0\0' + message.parameters_data = b'' + message.data = b'\x04' + self.path.encode('UTF-16LE') + b'\0\0' class ComRenameRequest(Payload): @@ -1322,7 +1300,7 @@ - [MS-CIFS]: 2.2.4.8.1 """ - def __init__(self, old_path, new_path, search_attributes = 0): + def __init__(self, old_path, new_path, search_attributes = 0): self.old_path = old_path self.new_path = new_path self.search_attributes = search_attributes @@ -1333,7 +1311,7 @@ def prepare(self, message): message.parameters_data = struct.pack('<H', self.search_attributes) - message.data = '\x04' + self.old_path.encode('UTF-16LE') + '\x00\x00\x04\x00' + self.new_path.encode('UTF-16LE') + '\x00\x00' + message.data = b'\x04' + self.old_path.encode('UTF-16LE') + b'\x00\x00\x04\x00' + self.new_path.encode('UTF-16LE') + b'\x00\x00' class ComEchoRequest(Payload): @@ -1343,7 +1321,7 @@ - [MS-CIFS]: 2.2.4.39.1 """ - def __init__(self, echo_data = '', echo_count = 1): + def __init__(self, echo_data = b'', echo_count = 1): self.echo_count = echo_count self.echo_data = echo_data @@ -1378,9 +1356,9 @@ PAYLOAD_STRUCT_FORMAT = '<BHIIIIIIIIBH' PAYLOAD_STRUCT_SIZE = struct.calcsize(PAYLOAD_STRUCT_FORMAT) - def __init__(self, function, max_params_count, max_data_count, max_setup_count, + def __init__(self, function, max_params_count, max_data_count, max_setup_count, total_params_count = 0, total_data_count = 0, - params_bytes = '', setup_bytes = '', data_bytes = ''): + params_bytes = b'', setup_bytes = b'', data_bytes = b''): self.function = function self.total_params_count = total_params_count or len(params_bytes) self.total_data_count = total_data_count or len(data_bytes) @@ -1400,10 +1378,10 @@ params_bytes_len = len(self.params_bytes) data_bytes_len = len(self.data_bytes) - padding0 = '' + padding0 = b'' offset = message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_bytes_len + 2 # constant 2 is for the ByteCount field in the SMB header (i.e. field which indicates number of data bytes after the SMB parameters) if offset % 4 != 0: - padding0 = '\0'*(4-offset%4) + padding0 = b'\0'*(4-offset%4) offset += (4-offset%4) if params_bytes_len > 0: @@ -1412,9 +1390,9 @@ params_bytes_offset = 0 offset += params_bytes_len - padding1 = '' + padding1 = b'' if offset % 4 != 0: - padding1 = '\0'*(4-offset%4) + padding1 = b'\0'*(4-offset%4) offset += (4-offset%4) if data_bytes_len > 0: @@ -1474,16 +1452,31 @@ params_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.params_bytes = message.data[params_offset:params_offset+params_count] else: - self.params_bytes = '' + self.params_bytes = b'' if data_count > 0: data_offset -= message.HEADER_STRUCT_SIZE + self.PAYLOAD_STRUCT_SIZE + setup_count*2 + 2 self.data_bytes = message.data[data_offset:data_offset+data_count] else: - self.data_bytes = '' + self.data_bytes = b''
    +
    +
    +
    +
    @@ -1494,13 +1487,17 @@
  • index
  • - - +
  • + modules |
  • + + + diff --git a/docs/html/_sources/api/nmb_NBNSProtocol.rst.txt b/docs/html/_sources/api/nmb_NBNSProtocol.rst.txt new file mode 100644 index 0000000..94323fe --- /dev/null +++ b/docs/html/_sources/api/nmb_NBNSProtocol.rst.txt @@ -0,0 +1,18 @@ + +NBNSProtocol Class +================== + +pysmb has a *NBNSProtocol* implementation for Twisted framework. +This allows you to perform name query asynchronously without having your application to block and wait for the results. + +In your project, + 1. Create a NBNSProtocol instance. + 2. Just call *queryName* method which will return a *Deferred* instance. Add your callback function to the *Deferred* instance via *addCallback* method to receive the results of the name query. + 3. When you are done with the NBNSProtocol instance, call its .transport.stopListening method to remove this instance from the reactor. + +.. autoclass:: nmb.NetBIOSProtocol.NBNSProtocol + :members: + :special-members: + +.. autoclass:: nmb.NetBIOSProtocol.NetBIOSTimeout + :members: diff --git a/docs/html/_sources/api/nmb_NetBIOS.rst.txt b/docs/html/_sources/api/nmb_NetBIOS.rst.txt new file mode 100644 index 0000000..2949d95 --- /dev/null +++ b/docs/html/_sources/api/nmb_NetBIOS.rst.txt @@ -0,0 +1,12 @@ + +NetBIOS class +============= + +To use the NetBIOS class in your application, + 1. Create a new NetBIOS instance + 2. Call *queryName* method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout. + 3. When you are done, call *close* method to release the underlying resources. + +.. autoclass:: nmb.NetBIOS.NetBIOS + :members: + :special-members: diff --git a/docs/html/_sources/api/smb_SMBConnection.rst.txt b/docs/html/_sources/api/smb_SMBConnection.rst.txt new file mode 100644 index 0000000..4478210 --- /dev/null +++ b/docs/html/_sources/api/smb_SMBConnection.rst.txt @@ -0,0 +1,55 @@ + +SMBConnection Class +=================== + +The SMBConnection is suitable for developers who wish to use pysmb to perform file operations with a remote SMB/CIFS server sequentially. + +Each file operation method, when invoked, will block and return after it has completed or has encountered an error. + +Example +------- + +The following illustrates a simple file retrieving implementation.:: + + import tempfile + from smb.SMBConnection import SMBConnection + + # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip + # client_machine_name can be an arbitary ASCII string + # server_name should match the remote machine name, or else the connection will be rejected + conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) + assert conn.connect(server_ip, 139) + + file_obj = tempfile.NamedTemporaryFile() + file_attributes, filesize = conn.retrieveFile('smbtest', '/rfc1001.txt', file_obj) + + # Retrieved file contents are inside file_obj + # Do what you need with the file_obj and then close it + # Note that the file obj is positioned at the end-of-file, + # so you might need to perform a file_obj.seek() if you need + # to read from the beginning + file_obj.close() + +SMB2 Support +------------- + +Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. +Otherwise, it will fallback automatically back to using SMB1 protocol. + +To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBConnection* instance.:: + + from smb import smb_structs + smb_structs.SUPPORT_SMB2 = False + +Caveats +------- + +* It is not meant to be used asynchronously. +* A single *SMBConnection* instance should not be used to perform more than one operation concurrently at the same time. +* Do not keep a *SMBConnection* instance "idle" for too long, i.e. keeping a *SMBConnection* instance but not using it. + Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. + If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client. + +.. autoclass:: smb.SMBConnection.SMBConnection + :members: + :special-members: diff --git a/docs/html/_sources/api/smb_SMBHandler.rst.txt b/docs/html/_sources/api/smb_SMBHandler.rst.txt new file mode 100644 index 0000000..9300de1 --- /dev/null +++ b/docs/html/_sources/api/smb_SMBHandler.rst.txt @@ -0,0 +1,83 @@ + +SMbHandler Class +================ + +The SMBHandler class provides support for "smb://" URLs in the `urllib2 `_ python package. + +Notes +----- +* The host component of the URL must be one of the following: + + * A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com + * An IP address. Example: 192.168.1.1 + * A comma-separated string "," where ** is the Windows/NetBIOS machine name for remote SMB service, and ** is the service's IP address. Example: MYSERVER,192.168.1.1 + +* The first component of the path in the URL points to the name of the shared folder. + Subsequent path components will point to the directory/folder of the file. +* You can retrieve and upload files, but you cannot delete files/folders or create folders. + In uploads, if the parent folders do not exist, an *urllib2.URLError* will be raised. + +Example +------- + +The following code snippet illustrates file retrieval with Python 2.:: + + # -*- coding: utf-8 -*- + import urllib2 + from smb.SMBHandler import SMBHandler + + director = urllib2.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') + + # Process fh like a file-like object and then close it. + fh.close() + + # For paths/files with unicode characters, simply pass in the URL as an unicode string + fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') + + # Process fh2 like a file-like object and then close it. + fh2.close() + +The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the *data* parameter in the *open()* method:: + + import urllib2 + from smb.SMBHandler import SMBHandler + + file_fh = open('local_file.dat', 'rb') + + director = urllib2.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) + + # Reading from fh will only return an empty string + fh.close() + + +The following code snippet illustrates file retrieval with Python 3.:: + + import urllib + from smb.SMBHandler import SMBHandler + + director = urllib.request.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') + + # Process fh like a file-like object and then close it. + fh.close() + + # For paths/files with unicode characters, simply pass in the URL as an unicode string + fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') + + # Process fh2 like a file-like object and then close it. + fh2.close() + +The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the *data* parameter in the *open()* method:: + + import urllib + from smb.SMBHandler import SMBHandler + + file_fh = open('local_file.dat', 'rb') + + director = urllib.request.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) + + # Reading from fh will only return an empty string + fh.close() diff --git a/docs/html/_sources/api/smb_SMBHandler.txt b/docs/html/_sources/api/smb_SMBHandler.txt index da106fe..9300de1 100644 --- a/docs/html/_sources/api/smb_SMBHandler.txt +++ b/docs/html/_sources/api/smb_SMBHandler.txt @@ -6,8 +6,12 @@ Notes ----- -* Note that you need to pass in a valid hostname or IP address for the host component of the URL. - Do not use the Windows/NetBIOS machine name for the host component. +* The host component of the URL must be one of the following: + + * A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com + * An IP address. Example: 192.168.1.1 + * A comma-separated string "," where ** is the Windows/NetBIOS machine name for remote SMB service, and ** is the service's IP address. Example: MYSERVER,192.168.1.1 + * The first component of the path in the URL points to the name of the shared folder. Subsequent path components will point to the directory/folder of the file. * You can retrieve and upload files, but you cannot delete files/folders or create folders. @@ -16,7 +20,7 @@ Example ------- -The following code snippet illustrates file retrieval.:: +The following code snippet illustrates file retrieval with Python 2.:: # -*- coding: utf-8 -*- import urllib2 @@ -34,7 +38,7 @@ # Process fh2 like a file-like object and then close it. fh2.close() -The following code snippet illustrates file upload. You need to provide a file-like object for the *data* parameter in the *open()* method:: +The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib2 from smb.SMBHandler import SMBHandler @@ -46,3 +50,34 @@ # Reading from fh will only return an empty string fh.close() + + +The following code snippet illustrates file retrieval with Python 3.:: + + import urllib + from smb.SMBHandler import SMBHandler + + director = urllib.request.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') + + # Process fh like a file-like object and then close it. + fh.close() + + # For paths/files with unicode characters, simply pass in the URL as an unicode string + fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') + + # Process fh2 like a file-like object and then close it. + fh2.close() + +The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the *data* parameter in the *open()* method:: + + import urllib + from smb.SMBHandler import SMBHandler + + file_fh = open('local_file.dat', 'rb') + + director = urllib.request.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) + + # Reading from fh will only return an empty string + fh.close() diff --git a/docs/html/_sources/api/smb_SMBProtocolFactory.rst.txt b/docs/html/_sources/api/smb_SMBProtocolFactory.rst.txt new file mode 100644 index 0000000..dc967c3 --- /dev/null +++ b/docs/html/_sources/api/smb_SMBProtocolFactory.rst.txt @@ -0,0 +1,93 @@ + +SMBProtocolFactory Class +======================== + +For those who want to utilize pysmb in Twisted framework, pysmb has a *smb.SMBProtocol.SMBProtocol* implementation. +In most cases, you do not need to touch or import the *SMBProtocol* directly. All the SMB functionalities are exposed in the *SMBProtocolFactory*. + +In your project, + 1. Create a new class and subclass *SMBProtocolFactory*. + 2. Override the *SMBProtocolFactory.onAuthOK* and *SMBProtocolFactory.onAuthFailed* instance methods to provide your own post-authenthentication handling. + Once *SMBProtocolFactory.onAuthOK* has been called by pymsb internals, your application is ready to communicate with the remote SMB/CIFS service through + the *SMBProtocolFactory* public methods such as *SMBProtocolFactory.storeFile*, *SMBProtocolFactory.retrieveFile*, etc. + 3. When you want to disconnect from the remote SMB/CIFS server, just call *SMBProtocolFactory.closeConnection* method. + +All the *SMBProtocolFactory* public methods that provide file functionlities will return a *twisted.internet.defer.Deferred* instance. +A :doc:`NotReadyError` exception is raised when the underlying SMB is not authenticated. +If the underlying SMB connection has been terminated, a :doc:`NotConnectedError` exception is raised. + +All the file operation methods in *SMBProtocolFactory* class accept a *timeout* parameter. This parameter specifies the time limit where pysmb will wait for the +entire file operation (except *storeFile* and *retrieveFile* methods) to complete. If the file operation fails to complete within the timeout period, the returned +*Deferred* instance's *errback* method will be called with a *SMBTimeout* exception. + +If you are interested in learning the results of the operation or to know when the operation has completed, you should +add a handling method to the returned *Deferred* instance via *Deferred.addCallback*. If the file operation fails, the *Deferred.errback* function will be called +with an :doc:`OperationFailure`; on timeout, it will be called with a :doc:`SMBTimeout`. + +Example +------- + +The following illustrates a simple file retrieving implementation.:: + + import tempfile + from twisted.internet import reactor + from smb.SMBProtocol import SMBProtocolFactory + + class RetrieveFileFactory(SMBProtocolFactory): + + def __init__(self, *args, **kwargs): + SMBProtocolFactory.__init__(self, *args, **kwargs) + + def fileRetrieved(self, write_result): + file_obj, file_attributes, file_size = write_result + + # Retrieved file contents are inside file_obj + # Do what you need with the file_obj and then close it + # Note that the file obj is positioned at the end-of-file, + # so you might need to perform a file_obj.seek() to if you + # need to read from the beginning + file_obj.close() + + self.transport.loseConnection() + + def onAuthOK(self): + d = self.retrieveFile(self.service, self.path, tempfile.NamedTemporaryFile()) + d.addCallback(self.fileRetrieved) + d.addErrback(self.d.errback) + + def onAuthFailed(self): + print 'Auth failed' + + # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip + # client_machine_name can be an arbitary ASCII string + # server_name should match the remote machine name, or else the connection will be rejected + factory = RetrieveFileFactory(userID, password, client_machine_name, server_name, use_ntlm_v2 = True) + factory.service = 'smbtest' + factory.path = '/rfc1001.txt' + reactor.connectTCP(server_ip, 139, factory) + + + + +SMB2 Support +------------- + +Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. +Otherwise, it will fallback automatically back to using SMB1 protocol. + +To disable SMB2 protocol in pysmb, set the *SUPPORT_SMB2* flag in the *smb_structs* module to *False* before creating the *SMBProtocolFactory* instance.:: + + from smb import smb_structs + smb_structs.SUPPORT_SMB2 = False + +Caveats +------- + +* A new factory instance must be created for each SMB connection to the remote SMB/CIFS service. Avoid reusing the same factory instance for more than one SMB connection. +* The remote SMB/CIFS server usually imposes a limit of the number of concurrent file operations for each client. For example, to transfer a thousand files, you may need to setup a queue in your application and call *storeFile* or *retrieveFile* in batches. +* The *timeout* parameter in the file operation methods are not precise; it is accurate to within 1 second interval, i.e. with a timeout of 0.5 sec, pysmb might raise + *SMBTimeout* exception after 1.5 sec. + +.. autoclass:: smb.SMBProtocol.SMBProtocolFactory + :members: + :special-members: diff --git a/docs/html/_sources/api/smb_SharedDevice.rst.txt b/docs/html/_sources/api/smb_SharedDevice.rst.txt new file mode 100644 index 0000000..9ac39b7 --- /dev/null +++ b/docs/html/_sources/api/smb_SharedDevice.rst.txt @@ -0,0 +1,6 @@ + +SharedDevice Class +================== + +.. autoclass:: smb.base.SharedDevice + :members: diff --git a/docs/html/_sources/api/smb_SharedFile.rst.txt b/docs/html/_sources/api/smb_SharedFile.rst.txt new file mode 100644 index 0000000..d71e43c --- /dev/null +++ b/docs/html/_sources/api/smb_SharedFile.rst.txt @@ -0,0 +1,6 @@ + +SharedFile Class +================ + +.. autoclass:: smb.base.SharedFile + :members: diff --git a/docs/html/_sources/api/smb_exceptions.rst.txt b/docs/html/_sources/api/smb_exceptions.rst.txt new file mode 100644 index 0000000..7340639 --- /dev/null +++ b/docs/html/_sources/api/smb_exceptions.rst.txt @@ -0,0 +1,21 @@ + +SMB Exceptions +============== + +.. autoclass:: smb.base.SMBTimeout + :members: + +.. autoclass:: smb.base.NotReadyError + :members: + +.. autoclass:: smb.base.NotConnectedError + :members: + +.. autoclass:: smb.smb_structs.UnsupportedFeature + :members: + +.. autoclass:: smb.smb_structs.ProtocolError + :members: + +.. autoclass:: smb.smb_structs.OperationFailure + :members: diff --git a/docs/html/_sources/api/smb_security_descriptors.rst.txt b/docs/html/_sources/api/smb_security_descriptors.rst.txt new file mode 100644 index 0000000..0f048fe --- /dev/null +++ b/docs/html/_sources/api/smb_security_descriptors.rst.txt @@ -0,0 +1,23 @@ + +Security Descriptors +==================== + +.. module:: smb.security_descriptors + :synopsis: Data structures used in Windows security descriptors. + +This module implements security descriptors, and associated data +structures, as specified in `[MS-DTYP]`_. + +.. autoclass:: SID + :members: + +.. autoclass:: ACE + :members: + +.. autoclass:: ACL + :members: + +.. autoclass:: SecurityDescriptor + :members: + +.. _[MS-DTYP]: https://msdn.microsoft.com/en-us/library/cc230273.aspx diff --git a/docs/html/_sources/api/smb_security_descriptors.txt b/docs/html/_sources/api/smb_security_descriptors.txt new file mode 100644 index 0000000..0f048fe --- /dev/null +++ b/docs/html/_sources/api/smb_security_descriptors.txt @@ -0,0 +1,23 @@ + +Security Descriptors +==================== + +.. module:: smb.security_descriptors + :synopsis: Data structures used in Windows security descriptors. + +This module implements security descriptors, and associated data +structures, as specified in `[MS-DTYP]`_. + +.. autoclass:: SID + :members: + +.. autoclass:: ACE + :members: + +.. autoclass:: ACL + :members: + +.. autoclass:: SecurityDescriptor + :members: + +.. _[MS-DTYP]: https://msdn.microsoft.com/en-us/library/cc230273.aspx diff --git a/docs/html/_sources/extending.rst.txt b/docs/html/_sources/extending.rst.txt new file mode 100644 index 0000000..c39572c --- /dev/null +++ b/docs/html/_sources/extending.rst.txt @@ -0,0 +1,20 @@ + +Extending pysmb For Other Frameworks +==================================== + +This page briefly describes the steps involved in extending pysmb for other frameworks. + +In general, you need to take care of the SMB TCP connection setup, i.e. finding the IP address of the remote server and connect to the SMB/CIFS service. +Then you need to read/write synchronously or asynchronously from and to the SMB socket. And you need to handle post-authentication callback methods, and from these methods, +initiate file operations with the remote SMB/CIFS server. + +Now the above steps in more technical details: + 1. Create a new class which subclasses the *smb.base.SMB* class. Most often, the connection setup will be part of the *__init__* method. + 2. Override the *write(self, data)* method to provide an implementation which will write *data* to the socket. + 3. Write your own loop handling method to read data from the socket. Once data have been read, call *feedData* method with the parameter. + The *feedData* method has its own internal buffer, so it can accept incomplete NetBIOS session packet data. + 4. Override + + * *onAuthOK* method to include your own operations to perform when authentication is successful. You can initiate file operations in this method. + * *onAuthFailed* method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (*use_ntlm_v2* parameter in the constructor). + * *onNMBSessionFailed* method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong *remote_name* parameter in the constructor. diff --git a/docs/html/_sources/index.rst.txt b/docs/html/_sources/index.rst.txt new file mode 100644 index 0000000..b872dec --- /dev/null +++ b/docs/html/_sources/index.rst.txt @@ -0,0 +1,104 @@ +Welcome to pysmb's documentation! +================================= + +pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol +that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. +pysmb is developed in Python 2.7.x and Python 3.8.x and has been tested against shared folders on Windows 7, Windows 10 and Samba 4.x. + +The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. + +License +------- +pysmb itself is licensed under an opensource license. +You are free to use pysmb in any applications, including for commercial purposes. +For more details on the terms of use, please read the LICENSE file that comes with your pysmb source. + +pysmb depends on other 3rd-party modules whose terms of use are not covered by pysmb. +Use of these modules could possibly conflict with your licensing needs. Please exercise your own discretion to determine their suitabilities. +I have listed these modules in the following section. + +Credits +------- +pysmb is not alone. It is made possible with support from other modules. + +* **pyasn1** : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately) +* **md4** and **U32** : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb. +* **pyDes** : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb. +* **sha256** : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when + the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm. + +In various places, there are references to different specifications. Most of these referenced specifications +can be downloaded from Microsoft web site under Microsoft's "Open Specification Promise". If you need to download +a copy of these specifications, please google for it. For example, google for "MS-CIFS" to download the CIFS specification for NT LM dialect. + +Package Contents and Description +================================ + +pysmb is organized into 2 main packages: smb and nmb. +The smb package contains all the functionalities related to Server Message Block (SMB) implementation. +As an application developer, you will be importing this module into your application. +Hence, please take some time to familiarize yourself with the smb package contents. + +* **nmb/base.py** : + Contains the NetBIOSSession and NBNS abstract class which implements NetBIOS session and NetBIOS Name Service communication + without any network transport specifics. +* **nmb/NetBIOS.py**: + Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O. +* **nmb/NetBIOSProtocol.py** : + Provides the NBNS protocol implementation for use in Twisted framework. + +* **smb/base.py** : + Contains the SMB abstract class which implements the SMB communication without any network transport specifics. +* **smb/ntlm.py** : + Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages. +* **smb/securityblob.py** : + Provides routines to encode/decode the NTLMSSP security blob in the SMB messages. +* **smb/smb_constants.py** : + All the constants used in the smb package for SMB1 protocol +* **smb/smb_structs.py** : + Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message. +* **smb/smb2_constants.py** : + All the constants used in the smb package for SMB2 protocol +* **smb/smb2_structs.py** : + Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message. +* **smb/SMBConnection.py** : + Contains a SMB protocol implementation. All operations are blocking I/O. +* **smb/SMBProtocol.py** : + Contains the SMB protocol implementation for use in the Twisted framework. +* **smb/SMBHandler.py** : + Provides support for "smb://" URL in the urllib2 python package. + +Using pysmb +=========== + +As an application developer who is looking to use pysmb to translate NetBIOS names to IP addresses, + * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read + :doc:`nmb.NetBIOS.NetBIOS` documentation. + * To use pysmb in Twisted, please read :doc:`nmb.NetBIOSProtocol.NBNSProtocol` documentation. + +As an application developer who is looking to use pysmb to implement file transfer or authentication over SMB: + * To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read + :doc:`smb.SMBConnection.SMBConnection` documentation. + * To use pysmb in Twisted, please read :doc:`smb.SMBProtocol.SMBProtocolFactory` documentation. + * To support "smb://" URL in urllib2 python package, read :doc:`smb.SMBHandler.SMBHandler` documentation. + +As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks: + * Read :doc:`extending` + +If you are upgrading from older pysmb versions: + * Read :doc:`upgrading` + + +Indices and tables +================== + +.. toctree:: + :glob: + :maxdepth: 1 + + api/* + extending + upgrading + +* :ref:`genindex` +* :ref:`search` diff --git a/docs/html/_sources/index.txt b/docs/html/_sources/index.txt index 7638fcd..e3eb1ac 100644 --- a/docs/html/_sources/index.txt +++ b/docs/html/_sources/index.txt @@ -8,9 +8,9 @@ pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. -pysmb is developed in Python 2.4.6, Python 2.7.1 and Python 3.2.3 and has been tested against shared folders on Windows XP SP3, Windows Vista, Windows 7 and Samba 3.x. +pysmb is developed in Python 2.7.x and Python 3.5.x and has been tested against shared folders on Windows XP SP3, Windows Vista, Windows 7 and Samba 3.x. -The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. +The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. License ------- @@ -90,6 +90,8 @@ As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks: * Read :doc:`extending` +If you are upgrading from older pysmb versions: + * Read :doc:`upgrading` Indices and tables @@ -101,6 +103,7 @@ api/* extending + upgrading * :ref:`genindex` * :ref:`search` diff --git a/docs/html/_sources/upgrading.rst.txt b/docs/html/_sources/upgrading.rst.txt new file mode 100644 index 0000000..8d5e7cd --- /dev/null +++ b/docs/html/_sources/upgrading.rst.txt @@ -0,0 +1,63 @@ +Upgrading from older pysmb versions +==================================== + +This page documents the improvements and changes to the API that could be incompatible with previous releases. + +pysmb 1.2.0 +----------- +- Add new `delete_matching_folders` parameter to `deleteFiles()` method in SMBProtocolFactory and SMBConnection + class to support deletion of sub-folders. If you are passing timeout parameter to the `deleteFiles()` method + in your application, please switch to using named parameter for timeout. + +pysmb 1.1.28 +------------ +- SharedFile instances returned from the `listPath()` method now has a new property + `file_id` attribute which represents the file reference number given by the remote SMB server. + +pysmb 1.1.26 +------------ +- SMBConnection class can now be used as a context manager + +pysmb 1.1.25 +------------ +- SharedFile class has a new property `isNormal` which will be True if the file is a + 'normal' file. pysmb defines a 'normal' file as a file entry that is not + read-only, not hidden, not system, not archive and not a directory; + it ignores other attributes like compression, indexed, sparse, temporary and encryption. +- `listPath()` method in SMBProtocolFactory and SMBConnection class will now include + 'normal' files by default if you do not specify the `search` parameter. + +pysmb 1.1.20 +------------ +- A new method `getSecurity()` was added to SMBConnection and SMBProtocolFactory class. + +pysmb 1.1.15 +------------ +- Add new `truncate` parameter to `storeFileFromOffset()` in SMBProtocolFactory and SMBConnection + class to support truncation of the file before writing. If you are passing timeout parameter + to the `storeFileFromOffset()` method in your application, please switch to using named parameter for timeout. + +pysmb 1.1.11 +------------ +- A new method `storeFileFromOffset()` was added to SMBConnection and SMBProtocolFactory class. + +pysmb 1.1.10 +------------ +- A new method `getAttributes()` was added to SMBConnection and SMBProtocolFactory class +- SharedFile class has a new property `isReadOnly` to indicate the file is read-only on the remote filesystem. + +pysmb 1.1.2 +----------- +- `queryIPForName()` method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names. + +pysmb 1.0.3 +----------- +- Two new methods were added to NBNSProtocol class: `queryIPForName()` and `NetBIOS.queryIPForName()` + to support querying for a machine's NetBIOS name at the given IP address. +- A new method `retrieveFileFromOffset()` was added to SMBProtocolFactory and SMBConnection + to support finer control of file retrieval operation. + +pysmb 1.0.0 +----------- +pysmb was completely rewritten in version 1.0.0. +If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API. diff --git a/docs/html/_sources/upgrading.txt b/docs/html/_sources/upgrading.txt new file mode 100644 index 0000000..8d5e7cd --- /dev/null +++ b/docs/html/_sources/upgrading.txt @@ -0,0 +1,63 @@ +Upgrading from older pysmb versions +==================================== + +This page documents the improvements and changes to the API that could be incompatible with previous releases. + +pysmb 1.2.0 +----------- +- Add new `delete_matching_folders` parameter to `deleteFiles()` method in SMBProtocolFactory and SMBConnection + class to support deletion of sub-folders. If you are passing timeout parameter to the `deleteFiles()` method + in your application, please switch to using named parameter for timeout. + +pysmb 1.1.28 +------------ +- SharedFile instances returned from the `listPath()` method now has a new property + `file_id` attribute which represents the file reference number given by the remote SMB server. + +pysmb 1.1.26 +------------ +- SMBConnection class can now be used as a context manager + +pysmb 1.1.25 +------------ +- SharedFile class has a new property `isNormal` which will be True if the file is a + 'normal' file. pysmb defines a 'normal' file as a file entry that is not + read-only, not hidden, not system, not archive and not a directory; + it ignores other attributes like compression, indexed, sparse, temporary and encryption. +- `listPath()` method in SMBProtocolFactory and SMBConnection class will now include + 'normal' files by default if you do not specify the `search` parameter. + +pysmb 1.1.20 +------------ +- A new method `getSecurity()` was added to SMBConnection and SMBProtocolFactory class. + +pysmb 1.1.15 +------------ +- Add new `truncate` parameter to `storeFileFromOffset()` in SMBProtocolFactory and SMBConnection + class to support truncation of the file before writing. If you are passing timeout parameter + to the `storeFileFromOffset()` method in your application, please switch to using named parameter for timeout. + +pysmb 1.1.11 +------------ +- A new method `storeFileFromOffset()` was added to SMBConnection and SMBProtocolFactory class. + +pysmb 1.1.10 +------------ +- A new method `getAttributes()` was added to SMBConnection and SMBProtocolFactory class +- SharedFile class has a new property `isReadOnly` to indicate the file is read-only on the remote filesystem. + +pysmb 1.1.2 +----------- +- `queryIPForName()` method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names. + +pysmb 1.0.3 +----------- +- Two new methods were added to NBNSProtocol class: `queryIPForName()` and `NetBIOS.queryIPForName()` + to support querying for a machine's NetBIOS name at the given IP address. +- A new method `retrieveFileFromOffset()` was added to SMBProtocolFactory and SMBConnection + to support finer control of file retrieval operation. + +pysmb 1.0.0 +----------- +pysmb was completely rewritten in version 1.0.0. +If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API. diff --git a/docs/html/_static/basic.css b/docs/html/_static/basic.css index c89fc7e..be19270 100644 --- a/docs/html/_static/basic.css +++ b/docs/html/_static/basic.css @@ -4,7 +4,7 @@ * * Sphinx stylesheet -- basic theme. * - * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @@ -13,6 +13,12 @@ div.clearer { clear: both; +} + +div.section::after { + display: block; + content: ''; + clear: left; } /* -- relbar ---------------------------------------------------------------- */ @@ -52,6 +58,8 @@ width: 230px; margin-left: -100%; font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; } div.sphinxsidebar ul { @@ -79,13 +87,25 @@ font-size: 1em; } +div.sphinxsidebar #searchbox form.search { + overflow: hidden; +} + div.sphinxsidebar #searchbox input[type="text"] { - width: 170px; + float: left; + width: 80%; + padding: 0.25em; + box-sizing: border-box; } div.sphinxsidebar #searchbox input[type="submit"] { - width: 30px; -} + float: left; + width: 20%; + border-left: none; + padding: 0.25em; + box-sizing: border-box; +} + img { border: 0; @@ -124,6 +144,8 @@ table.contentstable { width: 90%; + margin-left: auto; + margin-right: auto; } table.contentstable p.biglink { @@ -151,9 +173,14 @@ vertical-align: top; } -table.indextable dl, table.indextable dd { +table.indextable ul { margin-top: 0; margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; } table.indextable tr.pcap { @@ -185,10 +212,39 @@ padding: 0.4em; } +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + /* -- general body styles --------------------------------------------------- */ + +div.body { + min-width: 450px; + max-width: 800px; +} + +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} a.headerlink { visibility: hidden; +} + +a.brackets:before, +span.brackets > a:before{ + content: "["; +} + +a.brackets:after, +span.brackets > a:after { + content: "]"; } h1:hover > a.headerlink, @@ -212,10 +268,6 @@ text-align: left; } -.field-list ul { - padding-left: 1em; -} - .first { margin-top: 0 !important; } @@ -243,11 +295,21 @@ margin-right: auto; } +img.align-default, .figure.align-default { + display: block; + margin-left: auto; + margin-right: auto; +} + .align-left { text-align: left; } .align-center { + text-align: center; +} + +.align-default { text-align: center; } @@ -260,21 +322,27 @@ div.sidebar { margin: 0 0 0.5em 1em; border: 1px solid #ddb; - padding: 7px 7px 0 7px; + padding: 7px; background-color: #ffe; width: 40%; float: right; + clear: right; + overflow-x: auto; } p.sidebar-title { font-weight: bold; +} + +div.admonition, div.topic, blockquote { + clear: left; } /* -- topics ---------------------------------------------------------------- */ div.topic { border: 1px solid #ccc; - padding: 7px 7px 0 7px; + padding: 7px; margin: 10px 0 10px 0; } @@ -296,10 +364,6 @@ font-weight: bold; } -div.admonition dl { - margin-bottom: 0; -} - p.admonition-title { margin: 0px 10px 5px 0px; font-weight: bold; @@ -310,11 +374,40 @@ margin-top: 25px; } +/* -- content of sidebars/topics/admonitions -------------------------------- */ + +div.sidebar > :last-child, +div.topic > :last-child, +div.admonition > :last-child { + margin-bottom: 0; +} + +div.sidebar::after, +div.topic::after, +div.admonition::after, +blockquote::after { + display: block; + content: ''; + clear: both; +} + /* -- tables ---------------------------------------------------------------- */ table.docutils { + margin-top: 10px; + margin-bottom: 10px; border: 0; border-collapse: collapse; +} + +table.align-center { + margin-left: auto; + margin-right: auto; +} + +table.align-default { + margin-left: auto; + margin-right: auto; } table caption span.caption-number { @@ -332,10 +425,6 @@ border-bottom: 1px solid #aaa; } -table.field-list td, table.field-list th { - border: 0 !important; -} - table.footnote td, table.footnote th { border: 0 !important; } @@ -354,6 +443,16 @@ border-bottom: none; } +th > :first-child, +td > :first-child { + margin-top: 0px; +} + +th > :last-child, +td > :last-child { + margin-bottom: 0px; +} + /* -- figures --------------------------------------------------------------- */ div.figure { @@ -372,6 +471,38 @@ div.figure p.caption span.caption-text { } +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + +/* -- hlist styles ---------------------------------------------------------- */ + +table.hlist { + margin: 1em 0; +} + +table.hlist td { + vertical-align: top; +} + /* -- other body styles ----------------------------------------------------- */ @@ -395,11 +526,78 @@ list-style: upper-roman; } +:not(li) > ol > li:first-child > :first-child, +:not(li) > ul > li:first-child > :first-child { + margin-top: 0px; +} + +:not(li) > ol > li:last-child > :last-child, +:not(li) > ul > li:last-child > :last-child { + margin-bottom: 0px; +} + +ol.simple ol p, +ol.simple ul p, +ul.simple ol p, +ul.simple ul p { + margin-top: 0; +} + +ol.simple > li:not(:first-child) > p, +ul.simple > li:not(:first-child) > p { + margin-top: 0; +} + +ol.simple p, +ul.simple p { + margin-bottom: 0; +} + +dl.footnote > dt, +dl.citation > dt { + float: left; + margin-right: 0.5em; +} + +dl.footnote > dd, +dl.citation > dd { + margin-bottom: 0em; +} + +dl.footnote > dd:after, +dl.citation > dd:after { + content: ""; + clear: both; +} + +dl.field-list { + display: grid; + grid-template-columns: fit-content(30%) auto; +} + +dl.field-list > dt { + font-weight: bold; + word-break: break-word; + padding-left: 0.5em; + padding-right: 5px; +} + +dl.field-list > dt:after { + content: ":"; +} + +dl.field-list > dd { + padding-left: 0.5em; + margin-top: 0em; + margin-left: 0em; + margin-bottom: 0em; +} + dl { margin-bottom: 15px; } -dd p { +dd > :first-child { margin-top: 0px; } @@ -413,22 +611,22 @@ margin-left: 30px; } -dt:target, .highlighted { +dl > dd:last-child, +dl > dd:last-child > :last-child { + margin-bottom: 0; +} + +dt:target, span.highlighted { background-color: #fbe54e; } +rect.highlighted { + fill: #fbe54e; +} + dl.glossary dt { font-weight: bold; font-size: 1.1em; -} - -.field-list ul { - margin: 0; - padding-left: 1em; -} - -.field-list p { - margin: 0; } .optional { @@ -477,6 +675,12 @@ font-style: oblique; } +.classifier:before { + font-style: normal; + margin: 0.5em; + content: ":"; +} + abbr, acronym { border-bottom: dotted 1px; cursor: help; @@ -489,22 +693,68 @@ overflow-y: hidden; /* fixes display issues on Chrome browsers */ } +pre, div[class*="highlight-"] { + clear: both; +} + +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + +div[class*="highlight-"] { + margin: 1em 0; +} + td.linenos pre { - padding: 5px 0px; border: 0; background-color: transparent; color: #aaa; } table.highlighttable { - margin-left: 0.5em; + display: block; +} + +table.highlighttable tbody { + display: block; +} + +table.highlighttable tr { + display: flex; } table.highlighttable td { - padding: 0 0.5em 0 0.5em; + margin: 0; + padding: 0; +} + +table.highlighttable td.linenos { + padding-right: 0.5em; +} + +table.highlighttable td.code { + flex: 1; + overflow: hidden; +} + +.highlight .hll { + display: block; +} + +div.highlight pre, +table.highlighttable pre { + margin: 0; +} + +div.code-block-caption + div { + margin-top: 0; } div.code-block-caption { + margin-top: 1em; padding: 2px 5px; font-size: small; } @@ -513,8 +763,10 @@ background-color: transparent; } -div.code-block-caption + div > div.highlight > pre { - margin-top: 0; +table.highlighttable td.linenos, +span.linenos, +div.doctest > div.highlight span.gp { /* gp: Generic.Prompt */ + user-select: none; } div.code-block-caption span.caption-number { @@ -526,11 +778,7 @@ } div.literal-block-wrapper { - padding: 1em 1em 0; -} - -div.literal-block-wrapper div.highlight { - margin: 0; + margin: 1em 0; } code.descname { @@ -578,6 +826,15 @@ span.eqno { float: right; +} + +span.eqno a.headerlink { + position: absolute; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; } /* -- printout stylesheet --------------------------------------------------- */ diff --git a/docs/html/_static/contents.png b/docs/html/_static/contents.png index 7fb8215..6c59aa1 100644 Binary files a/docs/html/_static/contents.png and b/docs/html/_static/contents.png differ diff --git a/docs/html/_static/doctools.js b/docs/html/_static/doctools.js index e2e70cc..144884e 100644 --- a/docs/html/_static/doctools.js +++ b/docs/html/_static/doctools.js @@ -4,7 +4,7 @@ * * Sphinx JavaScript utilities for all documentation. * - * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS. + * :copyright: Copyright 2007-2021 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @@ -45,7 +45,7 @@ * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { - if (typeof s == 'undefined') + if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; @@ -66,29 +66,54 @@ * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { - function highlight(node) { - if (node.nodeType == 3) { + function highlight(node, addItems) { + if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); - if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { - var span = document.createElement("span"); - span.className = className; + if (pos >= 0 && + !jQuery(node.parentNode).hasClass(className) && + !jQuery(node.parentNode).hasClass("nohighlight")) { + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + var bbox = node.parentElement.getBBox(); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { - highlight(this); + highlight(this, addItems); }); } } - return this.each(function() { - highlight(this); + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; }; /* @@ -124,27 +149,30 @@ this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); + if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) { + this.initOnKeyListeners(); + } }, /** * i18n support */ TRANSLATIONS : {}, - PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; - if (typeof translated == 'undefined') + if (typeof translated === 'undefined') return string; - return (typeof translated == 'string') ? translated : translated[0]; + return (typeof translated === 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; - if (typeof translated == 'undefined') + if (typeof translated === 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, @@ -179,7 +207,7 @@ * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { - if (document.location.hash) + if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); @@ -215,7 +243,7 @@ var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); - if (src.substr(-9) == 'minus.png') + if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); @@ -247,11 +275,36 @@ var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { - if (this == '..') + if (this === '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keydown(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box, textarea, dropdown or button + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT' + && activeElementType !== 'BUTTON' && !event.altKey && !event.ctrlKey && !event.metaKey + && !event.shiftKey) { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); } }; diff --git a/docs/html/_static/documentation_options.js b/docs/html/_static/documentation_options.js new file mode 100644 index 0000000..d3946df --- /dev/null +++ b/docs/html/_static/documentation_options.js @@ -0,0 +1,12 @@ +var DOCUMENTATION_OPTIONS = { + URL_ROOT: document.getElementById("documentation_options").getAttribute('data-url_root'), + VERSION: '1.2.7', + LANGUAGE: 'None', + COLLAPSE_INDEX: false, + BUILDER: 'html', + FILE_SUFFIX: '.html', + LINK_SUFFIX: '.html', + HAS_SOURCE: true, + SOURCELINK_SUFFIX: '.txt', + NAVIGATION_WITH_KEYS: false +}; \ No newline at end of file diff --git a/docs/html/_static/file.png b/docs/html/_static/file.png index 254c60b..a858a41 100644 Binary files a/docs/html/_static/file.png and b/docs/html/_static/file.png differ diff --git a/docs/html/_static/jquery-3.5.1.js b/docs/html/_static/jquery-3.5.1.js new file mode 100644 index 0000000..5093733 --- /dev/null +++ b/docs/html/_static/jquery-3.5.1.js @@ -0,0 +1,10872 @@ +/*! + * jQuery JavaScript Library v3.5.1 + * https://jquery.com/ + * + * Includes Sizzle.js + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://jquery.org/license + * + * Date: 2020-05-04T22:49Z + */ +( function( global, factory ) { + + "use strict"; + + if ( typeof module === "object" && typeof module.exports === "object" ) { + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. + // e.g. var jQuery = require("jquery")(window); + // See ticket #14549 for more info. + module.exports = global.document ? + factory( global, true ) : + function( w ) { + if ( !w.document ) { + throw new Error( "jQuery requires a window with a document" ); + } + return factory( w ); + }; + } else { + factory( global ); + } + +// Pass this if window is not defined yet +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { + +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; + +var getProto = Object.getPrototypeOf; + +var slice = arr.slice; + +var flat = arr.flat ? function( array ) { + return arr.flat.call( array ); +} : function( array ) { + return arr.concat.apply( [], array ); +}; + + +var push = arr.push; + +var indexOf = arr.indexOf; + +var class2type = {}; + +var toString = class2type.toString; + +var hasOwn = class2type.hasOwnProperty; + +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + +var support = {}; + +var isFunction = function isFunction( obj ) { + + // Support: Chrome <=57, Firefox <=52 + // In some browsers, typeof returns "function" for HTML elements + // (i.e., `typeof document.createElement( "object" ) === "function"`). + // We don't want to classify *any* DOM node as a function. + return typeof obj === "function" && typeof obj.nodeType !== "number"; + }; + + +var isWindow = function isWindow( obj ) { + return obj != null && obj === obj.window; + }; + + +var document = window.document; + + + + var preservedScriptAttributes = { + type: true, + src: true, + nonce: true, + noModule: true + }; + + function DOMEval( code, node, doc ) { + doc = doc || document; + + var i, val, + script = doc.createElement( "script" ); + + script.text = code; + if ( node ) { + for ( i in preservedScriptAttributes ) { + + // Support: Firefox 64+, Edge 18+ + // Some browsers don't support the "nonce" property on scripts. + // On the other hand, just using `getAttribute` is not enough as + // the `nonce` attribute is reset to an empty string whenever it + // becomes browsing-context connected. + // See https://github.com/whatwg/html/issues/2369 + // See https://html.spec.whatwg.org/#nonce-attributes + // The `node.getAttribute` check was added for the sake of + // `jQuery.globalEval` so that it can fake a nonce-containing node + // via an object. + val = node[ i ] || node.getAttribute && node.getAttribute( i ); + if ( val ) { + script.setAttribute( i, val ); + } + } + } + doc.head.appendChild( script ).parentNode.removeChild( script ); + } + + +function toType( obj ) { + if ( obj == null ) { + return obj + ""; + } + + // Support: Android <=2.3 only (functionish RegExp) + return typeof obj === "object" || typeof obj === "function" ? + class2type[ toString.call( obj ) ] || "object" : + typeof obj; +} +/* global Symbol */ +// Defining this global in .eslintrc.json would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + +var + version = "3.5.1", + + // Define a local copy of jQuery + jQuery = function( selector, context ) { + + // The jQuery object is actually just the init constructor 'enhanced' + // Need init if jQuery is called (just allow error to be thrown if not included) + return new jQuery.fn.init( selector, context ); + }; + +jQuery.fn = jQuery.prototype = { + + // The current version of jQuery being used + jquery: version, + + constructor: jQuery, + + // The default length of a jQuery object is 0 + length: 0, + + toArray: function() { + return slice.call( this ); + }, + + // Get the Nth element in the matched element set OR + // Get the whole matched element set as a clean array + get: function( num ) { + + // Return all the elements in a clean array + if ( num == null ) { + return slice.call( this ); + } + + // Return just the one element from the set + return num < 0 ? this[ num + this.length ] : this[ num ]; + }, + + // Take an array of elements and push it onto the stack + // (returning the new matched element set) + pushStack: function( elems ) { + + // Build a new jQuery matched element set + var ret = jQuery.merge( this.constructor(), elems ); + + // Add the old object onto the stack (as a reference) + ret.prevObject = this; + + // Return the newly-formed element set + return ret; + }, + + // Execute a callback for every element in the matched set. + each: function( callback ) { + return jQuery.each( this, callback ); + }, + + map: function( callback ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { + return callback.call( elem, i, elem ); + } ) ); + }, + + slice: function() { + return this.pushStack( slice.apply( this, arguments ) ); + }, + + first: function() { + return this.eq( 0 ); + }, + + last: function() { + return this.eq( -1 ); + }, + + even: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return ( i + 1 ) % 2; + } ) ); + }, + + odd: function() { + return this.pushStack( jQuery.grep( this, function( _elem, i ) { + return i % 2; + } ) ); + }, + + eq: function( i ) { + var len = this.length, + j = +i + ( i < 0 ? len : 0 ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); + }, + + end: function() { + return this.prevObject || this.constructor(); + }, + + // For internal use only. + // Behaves like an Array's method, not like a jQuery method. + push: push, + sort: arr.sort, + splice: arr.splice +}; + +jQuery.extend = jQuery.fn.extend = function() { + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, + i = 1, + length = arguments.length, + deep = false; + + // Handle a deep copy situation + if ( typeof target === "boolean" ) { + deep = target; + + // Skip the boolean and the target + target = arguments[ i ] || {}; + i++; + } + + // Handle case when target is a string or something (possible in deep copy) + if ( typeof target !== "object" && !isFunction( target ) ) { + target = {}; + } + + // Extend jQuery itself if only one argument is passed + if ( i === length ) { + target = this; + i--; + } + + for ( ; i < length; i++ ) { + + // Only deal with non-null/undefined values + if ( ( options = arguments[ i ] ) != null ) { + + // Extend the base object + for ( name in options ) { + copy = options[ name ]; + + // Prevent Object.prototype pollution + // Prevent never-ending loop + if ( name === "__proto__" || target === copy ) { + continue; + } + + // Recurse if we're merging plain objects or arrays + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = Array.isArray( copy ) ) ) ) { + src = target[ name ]; + + // Ensure proper type for the source value + if ( copyIsArray && !Array.isArray( src ) ) { + clone = []; + } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { + clone = {}; + } else { + clone = src; + } + copyIsArray = false; + + // Never move original objects, clone them + target[ name ] = jQuery.extend( deep, clone, copy ); + + // Don't bring in undefined values + } else if ( copy !== undefined ) { + target[ name ] = copy; + } + } + } + } + + // Return the modified object + return target; +}; + +jQuery.extend( { + + // Unique for each copy of jQuery on the page + expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), + + // Assume jQuery is ready without the ready module + isReady: true, + + error: function( msg ) { + throw new Error( msg ); + }, + + noop: function() {}, + + isPlainObject: function( obj ) { + var proto, Ctor; + + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { + return false; + } + + proto = getProto( obj ); + + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; + } + + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + var name; + + for ( name in obj ) { + return false; + } + return true; + }, + + // Evaluates a script in a provided context; falls back to the global one + // if not specified. + globalEval: function( code, options, doc ) { + DOMEval( code, { nonce: options && options.nonce }, doc ); + }, + + each: function( obj, callback ) { + var length, i = 0; + + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } else { + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; + } + } + } + + return obj; + }, + + // results is for internal usage only + makeArray: function( arr, results ) { + var ret = results || []; + + if ( arr != null ) { + if ( isArrayLike( Object( arr ) ) ) { + jQuery.merge( ret, + typeof arr === "string" ? + [ arr ] : arr + ); + } else { + push.call( ret, arr ); + } + } + + return ret; + }, + + inArray: function( elem, arr, i ) { + return arr == null ? -1 : indexOf.call( arr, elem, i ); + }, + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + merge: function( first, second ) { + var len = +second.length, + j = 0, + i = first.length; + + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; + } + + first.length = i; + + return first; + }, + + grep: function( elems, callback, invert ) { + var callbackInverse, + matches = [], + i = 0, + length = elems.length, + callbackExpect = !invert; + + // Go through the array, only saving the items + // that pass the validator function + for ( ; i < length; i++ ) { + callbackInverse = !callback( elems[ i ], i ); + if ( callbackInverse !== callbackExpect ) { + matches.push( elems[ i ] ); + } + } + + return matches; + }, + + // arg is for internal usage only + map: function( elems, callback, arg ) { + var length, value, + i = 0, + ret = []; + + // Go through the array, translating each of the items to their new values + if ( isArrayLike( elems ) ) { + length = elems.length; + for ( ; i < length; i++ ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + + // Go through every key on the object, + } else { + for ( i in elems ) { + value = callback( elems[ i ], i, arg ); + + if ( value != null ) { + ret.push( value ); + } + } + } + + // Flatten any nested arrays + return flat( ret ); + }, + + // A global GUID counter for objects + guid: 1, + + // jQuery.support is not used in Core but other projects attach their + // properties to it so it needs to exist. + support: support +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} + +// Populate the class2type map +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( _i, name ) { + class2type[ "[object " + name + "]" ] = name.toLowerCase(); +} ); + +function isArrayLike( obj ) { + + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, + type = toType( obj ); + + if ( isFunction( obj ) || isWindow( obj ) ) { + return false; + } + + return type === "array" || length === 0 || + typeof length === "number" && length > 0 && ( length - 1 ) in obj; +} +var Sizzle = +/*! + * Sizzle CSS Selector Engine v2.3.5 + * https://sizzlejs.com/ + * + * Copyright JS Foundation and other contributors + * Released under the MIT license + * https://js.foundation/ + * + * Date: 2020-03-14 + */ +( function( window ) { +var i, + support, + Expr, + getText, + isXML, + tokenize, + compile, + select, + outermostContext, + sortInput, + hasDuplicate, + + // Local document vars + setDocument, + document, + docElem, + documentIsHTML, + rbuggyQSA, + rbuggyMatches, + matches, + contains, + + // Instance-specific data + expando = "sizzle" + 1 * new Date(), + preferredDoc = window.document, + dirruns = 0, + done = 0, + classCache = createCache(), + tokenCache = createCache(), + compilerCache = createCache(), + nonnativeSelectorCache = createCache(), + sortOrder = function( a, b ) { + if ( a === b ) { + hasDuplicate = true; + } + return 0; + }, + + // Instance methods + hasOwn = ( {} ).hasOwnProperty, + arr = [], + pop = arr.pop, + pushNative = arr.push, + push = arr.push, + slice = arr.slice, + + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { + var i = 0, + len = list.length; + for ( ; i < len; i++ ) { + if ( list[ i ] === elem ) { + return i; + } + } + return -1; + }, + + booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + + "ismap|loop|multiple|open|readonly|required|scoped", + + // Regular expressions + + // http://www.w3.org/TR/css3-selectors/#whitespace + whitespace = "[\\x20\\t\\r\\n\\f]", + + // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram + identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", + + // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + + + // Operator (capture 2) + "*([*^$|!~]?=)" + whitespace + + + // "Attribute values must be CSS identifiers [capture 5] + // or strings [capture 3 or capture 4]" + "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + + whitespace + "*\\]", + + pseudos = ":(" + identifier + ")(?:\\((" + + + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: + // 1. quoted (capture 3; capture 4 or capture 5) + "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + + + // 2. simple (capture 6) + "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + + + // 3. anything else (capture 2) + ".*" + + ")\\)|)", + + // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), + rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + + whitespace + "+$", "g" ), + + rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), + rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + + "*" ), + rdescend = new RegExp( whitespace + "|>" ), + + rpseudo = new RegExp( pseudos ), + ridentifier = new RegExp( "^" + identifier + "$" ), + + matchExpr = { + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), + "ATTR": new RegExp( "^" + attributes ), + "PSEUDO": new RegExp( "^" + pseudos ), + "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), + "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), + + // For use in libraries implementing .is() + // We use this for POS matching in `select` + "needsContext": new RegExp( "^" + whitespace + + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) + }, + + rhtml = /HTML$/i, + rinputs = /^(?:input|select|textarea|button)$/i, + rheader = /^h\d$/i, + + rnative = /^[^{]+\{\s*\[native \w/, + + // Easily-parseable/retrievable ID or TAG or CLASS selectors + rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, + + rsibling = /[+~]/, + + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), + funescape = function( escape, nonHex ) { + var high = "0x" + escape.slice( 1 ) - 0x10000; + + return nonHex ? + + // Strip the backslash prefix from a non-hex escape sequence + nonHex : + + // Replace a hexadecimal escape sequence with the encoded Unicode code point + // Support: IE <=11+ + // For values outside the Basic Multilingual Plane (BMP), manually construct a + // surrogate pair + high < 0 ? + String.fromCharCode( high + 0x10000 ) : + String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + inDisabledFieldset = addCombinator( + function( elem ) { + return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; + }, + { dir: "parentNode", next: "legend" } + ); + +// Optimize for push.apply( _, NodeList ) +try { + push.apply( + ( arr = slice.call( preferredDoc.childNodes ) ), + preferredDoc.childNodes + ); + + // Support: Android<4.0 + // Detect silently failing push.apply + // eslint-disable-next-line no-unused-expressions + arr[ preferredDoc.childNodes.length ].nodeType; +} catch ( e ) { + push = { apply: arr.length ? + + // Leverage slice if possible + function( target, els ) { + pushNative.apply( target, slice.call( els ) ); + } : + + // Support: IE<9 + // Otherwise append directly + function( target, els ) { + var j = target.length, + i = 0; + + // Can't trust NodeList.length + while ( ( target[ j++ ] = els[ i++ ] ) ) {} + target.length = j - 1; + } + }; +} + +function Sizzle( selector, context, results, seed ) { + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, + + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; + + results = results || []; + + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + + return results; + } + + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { + setDocument( context ); + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { + + // ID selector + if ( ( m = match[ 1 ] ) ) { + + // Document context + if ( nodeType === 9 ) { + if ( ( elem = context.getElementById( m ) ) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { + return results; + } + + // Element context + } else { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && ( elem = newContext.getElementById( m ) ) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } + } + + // Type selector + } else if ( match[ 2 ] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; + + // Class selector + } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } + } + + // Take advantage of querySelectorAll + if ( support.qsa && + !nonnativeSelectorCache[ selector + " " ] && + ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && + + // Support: IE 8 only + // Exclude object elements + ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { + + newSelector = selector; + newContext = context; + + // qSA considers elements outside a scoping root when evaluating child or + // descendant combinators, which is not what we want. + // In such cases, we work around the behavior by prefixing every selector in the + // list with an ID selector referencing the scope context. + // The technique has to be used as well when a leading combinator is used + // as such selectors are not recognized by querySelectorAll. + // Thanks to Andrew Dupont for this technique. + if ( nodeType === 1 && + ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; + + // We can use :scope instead of the ID hack if the browser + // supports it & if we're not changing the context. + if ( newContext !== context || !support.scope ) { + + // Capture the context ID, setting it first if necessary + if ( ( nid = context.getAttribute( "id" ) ) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", ( nid = expando ) ); + } + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + + toSelector( groups[ i ] ); + } + newSelector = groups.join( "," ); + } + + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + nonnativeSelectorCache( selector, true ); + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } + } + } + } + } + + // All others + return select( selector.replace( rtrim, "$1" ), context, results, seed ); +} + +/** + * Create key-value caches of limited size + * @returns {function(string, object)} Returns the Object data after storing it on itself with + * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) + * deleting the oldest entry + */ +function createCache() { + var keys = []; + + function cache( key, value ) { + + // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) + if ( keys.push( key + " " ) > Expr.cacheLength ) { + + // Only keep the most recent entries + delete cache[ keys.shift() ]; + } + return ( cache[ key + " " ] = value ); + } + return cache; +} + +/** + * Mark a function for special use by Sizzle + * @param {Function} fn The function to mark + */ +function markFunction( fn ) { + fn[ expando ] = true; + return fn; +} + +/** + * Support testing using an element + * @param {Function} fn Passed the created element and returns a boolean result + */ +function assert( fn ) { + var el = document.createElement( "fieldset" ); + + try { + return !!fn( el ); + } catch ( e ) { + return false; + } finally { + + // Remove from its parent by default + if ( el.parentNode ) { + el.parentNode.removeChild( el ); + } + + // release memory in IE + el = null; + } +} + +/** + * Adds the same handler for all of the specified attrs + * @param {String} attrs Pipe-separated list of attributes + * @param {Function} handler The method that will be applied + */ +function addHandle( attrs, handler ) { + var arr = attrs.split( "|" ), + i = arr.length; + + while ( i-- ) { + Expr.attrHandle[ arr[ i ] ] = handler; + } +} + +/** + * Checks document order of two siblings + * @param {Element} a + * @param {Element} b + * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b + */ +function siblingCheck( a, b ) { + var cur = b && a, + diff = cur && a.nodeType === 1 && b.nodeType === 1 && + a.sourceIndex - b.sourceIndex; + + // Use IE sourceIndex if available on both nodes + if ( diff ) { + return diff; + } + + // Check if b follows a + if ( cur ) { + while ( ( cur = cur.nextSibling ) ) { + if ( cur === b ) { + return -1; + } + } + } + + return a ? 1 : -1; +} + +/** + * Returns a function to use in pseudos for input types + * @param {String} type + */ +function createInputPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for buttons + * @param {String} type + */ +function createButtonPseudo( type ) { + return function( elem ) { + var name = elem.nodeName.toLowerCase(); + return ( name === "input" || name === "button" ) && elem.type === type; + }; +} + +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + + // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Only certain elements can match :enabled or :disabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled + // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled + if ( "form" in elem ) { + + // Check for inherited disabledness on relevant non-disabled elements: + // * listed form-associated elements in a disabled fieldset + // https://html.spec.whatwg.org/multipage/forms.html#category-listed + // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled + // * option elements in a disabled optgroup + // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled + // All such elements have a "form" property. + if ( elem.parentNode && elem.disabled === false ) { + + // Option elements defer to a parent optgroup if present + if ( "label" in elem ) { + if ( "label" in elem.parentNode ) { + return elem.parentNode.disabled === disabled; + } else { + return elem.disabled === disabled; + } + } + + // Support: IE 6 - 11 + // Use the isDisabled shortcut property to check for disabled fieldset ancestors + return elem.isDisabled === disabled || + + // Where there is no isDisabled, check manually + /* jshint -W018 */ + elem.isDisabled !== !disabled && + inDisabledFieldset( elem ) === disabled; + } + + return elem.disabled === disabled; + + // Try to winnow out elements that can't be disabled before trusting the disabled property. + // Some victims get caught in our net (label, legend, menu, track), but it shouldn't + // even exist on them, let alone have a boolean value. + } else if ( "label" in elem ) { + return elem.disabled === disabled; + } + + // Remaining elements are neither :enabled nor :disabled + return false; + }; +} + +/** + * Returns a function to use in pseudos for positionals + * @param {Function} fn + */ +function createPositionalPseudo( fn ) { + return markFunction( function( argument ) { + argument = +argument; + return markFunction( function( seed, matches ) { + var j, + matchIndexes = fn( [], seed.length, argument ), + i = matchIndexes.length; + + // Match elements found at the specified indexes + while ( i-- ) { + if ( seed[ ( j = matchIndexes[ i ] ) ] ) { + seed[ j ] = !( matches[ j ] = seed[ j ] ); + } + } + } ); + } ); +} + +/** + * Checks a node for validity as a Sizzle context + * @param {Element|Object=} context + * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value + */ +function testContext( context ) { + return context && typeof context.getElementsByTagName !== "undefined" && context; +} + +// Expose support vars for convenience +support = Sizzle.support = {}; + +/** + * Detects XML nodes + * @param {Element|Object} elem An element or a document + * @returns {Boolean} True iff elem is a non-HTML XML node + */ +isXML = Sizzle.isXML = function( elem ) { + var namespace = elem.namespaceURI, + docElem = ( elem.ownerDocument || elem ).documentElement; + + // Support: IE <=8 + // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes + // https://bugs.jquery.com/ticket/4833 + return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); +}; + +/** + * Sets document-related variables once based on the current document + * @param {Element|Object} [doc] An element or document object to use to set the document + * @returns {Object} Returns the current document + */ +setDocument = Sizzle.setDocument = function( node ) { + var hasCompare, subWindow, + doc = node ? node.ownerDocument || node : preferredDoc; + + // Return early if doc is invalid or already selected + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { + return document; + } + + // Update global variables + document = doc; + docElem = document.documentElement; + documentIsHTML = !isXML( document ); + + // Support: IE 9 - 11+, Edge 12 - 18+ + // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( preferredDoc != document && + ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { + + // Support: IE 11, Edge + if ( subWindow.addEventListener ) { + subWindow.addEventListener( "unload", unloadHandler, false ); + + // Support: IE 9 - 10 only + } else if ( subWindow.attachEvent ) { + subWindow.attachEvent( "onunload", unloadHandler ); + } + } + + // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, + // Safari 4 - 5 only, Opera <=11.6 - 12.x only + // IE/Edge & older browsers don't support the :scope pseudo-class. + // Support: Safari 6.0 only + // Safari 6.0 supports :scope but it's an alias of :root there. + support.scope = assert( function( el ) { + docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); + return typeof el.querySelectorAll !== "undefined" && + !el.querySelectorAll( ":scope fieldset div" ).length; + } ); + + /* Attributes + ---------------------------------------------------------------------- */ + + // Support: IE<8 + // Verify that getAttribute really returns attributes and not properties + // (excepting IE8 booleans) + support.attributes = assert( function( el ) { + el.className = "i"; + return !el.getAttribute( "className" ); + } ); + + /* getElement(s)By* + ---------------------------------------------------------------------- */ + + // Check if getElementsByTagName("*") returns only elements + support.getElementsByTagName = assert( function( el ) { + el.appendChild( document.createComment( "" ) ); + return !el.getElementsByTagName( "*" ).length; + } ); + + // Support: IE<9 + support.getElementsByClassName = rnative.test( document.getElementsByClassName ); + + // Support: IE<10 + // Check if getElementById returns elements by name + // The broken getElementById methods don't pick up programmatically-set names, + // so use a roundabout getElementsByName test + support.getById = assert( function( el ) { + docElem.appendChild( el ).id = expando; + return !document.getElementsByName || !document.getElementsByName( expando ).length; + } ); + + // ID filter and find + if ( support.getById ) { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + return elem.getAttribute( "id" ) === attrId; + }; + }; + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var elem = context.getElementById( id ); + return elem ? [ elem ] : []; + } + }; + } else { + Expr.filter[ "ID" ] = function( id ) { + var attrId = id.replace( runescape, funescape ); + return function( elem ) { + var node = typeof elem.getAttributeNode !== "undefined" && + elem.getAttributeNode( "id" ); + return node && node.value === attrId; + }; + }; + + // Support: IE 6 - 7 only + // getElementById is not reliable as a find shortcut + Expr.find[ "ID" ] = function( id, context ) { + if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { + var node, i, elems, + elem = context.getElementById( id ); + + if ( elem ) { + + // Verify the id attribute + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + + // Fall back on getElementsByName + elems = context.getElementsByName( id ); + i = 0; + while ( ( elem = elems[ i++ ] ) ) { + node = elem.getAttributeNode( "id" ); + if ( node && node.value === id ) { + return [ elem ]; + } + } + } + + return []; + } + }; + } + + // Tag + Expr.find[ "TAG" ] = support.getElementsByTagName ? + function( tag, context ) { + if ( typeof context.getElementsByTagName !== "undefined" ) { + return context.getElementsByTagName( tag ); + + // DocumentFragment nodes don't have gEBTN + } else if ( support.qsa ) { + return context.querySelectorAll( tag ); + } + } : + + function( tag, context ) { + var elem, + tmp = [], + i = 0, + + // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too + results = context.getElementsByTagName( tag ); + + // Filter out possible comments + if ( tag === "*" ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem.nodeType === 1 ) { + tmp.push( elem ); + } + } + + return tmp; + } + return results; + }; + + // Class + Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { + if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { + return context.getElementsByClassName( className ); + } + }; + + /* QSA/matchesSelector + ---------------------------------------------------------------------- */ + + // QSA and matchesSelector support + + // matchesSelector(:active) reports false when true (IE9/Opera 11.5) + rbuggyMatches = []; + + // qSa(:focus) reports false when true (Chrome 21) + // We allow this because of a bug in IE8/9 that throws an error + // whenever `document.activeElement` is accessed on an iframe + // So, we allow :focus to pass through QSA all the time to avoid the IE error + // See https://bugs.jquery.com/ticket/13378 + rbuggyQSA = []; + + if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { + + // Build QSA regex + // Regex strategy adopted from Diego Perini + assert( function( el ) { + + var input; + + // Select is set to empty string on purpose + // This is to test IE's treatment of not explicitly + // setting a boolean content attribute, + // since its presence should be enough + // https://bugs.jquery.com/ticket/12359 + docElem.appendChild( el ).innerHTML = "" + + ""; + + // Support: IE8, Opera 11-12.16 + // Nothing should be selected when empty strings follow ^= or $= or *= + // The test attribute must be unknown in Opera but "safe" for WinRT + // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section + if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { + rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); + } + + // Support: IE8 + // Boolean attributes and "value" are not treated correctly + if ( !el.querySelectorAll( "[selected]" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); + } + + // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ + if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { + rbuggyQSA.push( "~=" ); + } + + // Support: IE 11+, Edge 15 - 18+ + // IE 11/Edge don't find elements on a `[name='']` query in some cases. + // Adding a temporary attribute to the document before the selection works + // around the issue. + // Interestingly, IE 10 & older don't seem to have the issue. + input = document.createElement( "input" ); + input.setAttribute( "name", "" ); + el.appendChild( input ); + if ( !el.querySelectorAll( "[name='']" ).length ) { + rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + + whitespace + "*(?:''|\"\")" ); + } + + // Webkit/Opera - :checked should return selected option elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + // IE8 throws error here and will not see later tests + if ( !el.querySelectorAll( ":checked" ).length ) { + rbuggyQSA.push( ":checked" ); + } + + // Support: Safari 8+, iOS 8+ + // https://bugs.webkit.org/show_bug.cgi?id=136851 + // In-page `selector#id sibling-combinator selector` fails + if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { + rbuggyQSA.push( ".#.+[+~]" ); + } + + // Support: Firefox <=3.6 - 5 only + // Old Firefox doesn't throw on a badly-escaped identifier. + el.querySelectorAll( "\\\f" ); + rbuggyQSA.push( "[\\r\\n\\f]" ); + } ); + + assert( function( el ) { + el.innerHTML = "" + + ""; + + // Support: Windows 8 Native Apps + // The type and name attributes are restricted during .innerHTML assignment + var input = document.createElement( "input" ); + input.setAttribute( "type", "hidden" ); + el.appendChild( input ).setAttribute( "name", "D" ); + + // Support: IE8 + // Enforce case-sensitivity of name attribute + if ( el.querySelectorAll( "[name=d]" ).length ) { + rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); + } + + // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) + // IE8 throws error here and will not see later tests + if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: IE9-11+ + // IE's :disabled selector does not pick up the children of disabled fieldsets + docElem.appendChild( el ).disabled = true; + if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { + rbuggyQSA.push( ":enabled", ":disabled" ); + } + + // Support: Opera 10 - 11 only + // Opera 10-11 does not throw on post-comma invalid pseudos + el.querySelectorAll( "*,:x" ); + rbuggyQSA.push( ",.*:" ); + } ); + } + + if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || + docElem.webkitMatchesSelector || + docElem.mozMatchesSelector || + docElem.oMatchesSelector || + docElem.msMatchesSelector ) ) ) ) { + + assert( function( el ) { + + // Check to see if it's possible to do matchesSelector + // on a disconnected node (IE 9) + support.disconnectedMatch = matches.call( el, "*" ); + + // This should fail with an exception + // Gecko does not error, returns false instead + matches.call( el, "[s!='']:x" ); + rbuggyMatches.push( "!=", pseudos ); + } ); + } + + rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); + rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); + + /* Contains + ---------------------------------------------------------------------- */ + hasCompare = rnative.test( docElem.compareDocumentPosition ); + + // Element contains another + // Purposefully self-exclusive + // As in, an element does not contain itself + contains = hasCompare || rnative.test( docElem.contains ) ? + function( a, b ) { + var adown = a.nodeType === 9 ? a.documentElement : a, + bup = b && b.parentNode; + return a === bup || !!( bup && bup.nodeType === 1 && ( + adown.contains ? + adown.contains( bup ) : + a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 + ) ); + } : + function( a, b ) { + if ( b ) { + while ( ( b = b.parentNode ) ) { + if ( b === a ) { + return true; + } + } + } + return false; + }; + + /* Sorting + ---------------------------------------------------------------------- */ + + // Document order sorting + sortOrder = hasCompare ? + function( a, b ) { + + // Flag for duplicate removal + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + // Sort on method existence if only one input has compareDocumentPosition + var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; + if ( compare ) { + return compare; + } + + // Calculate position if both inputs belong to the same document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? + a.compareDocumentPosition( b ) : + + // Otherwise we know they are disconnected + 1; + + // Disconnected nodes + if ( compare & 1 || + ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { + + // Choose the first element that is related to our preferred document + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( a == document || a.ownerDocument == preferredDoc && + contains( preferredDoc, a ) ) { + return -1; + } + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( b == document || b.ownerDocument == preferredDoc && + contains( preferredDoc, b ) ) { + return 1; + } + + // Maintain original order + return sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + } + + return compare & 4 ? -1 : 1; + } : + function( a, b ) { + + // Exit early if the nodes are identical + if ( a === b ) { + hasDuplicate = true; + return 0; + } + + var cur, + i = 0, + aup = a.parentNode, + bup = b.parentNode, + ap = [ a ], + bp = [ b ]; + + // Parentless nodes are either documents or disconnected + if ( !aup || !bup ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + return a == document ? -1 : + b == document ? 1 : + /* eslint-enable eqeqeq */ + aup ? -1 : + bup ? 1 : + sortInput ? + ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : + 0; + + // If the nodes are siblings, we can do a quick check + } else if ( aup === bup ) { + return siblingCheck( a, b ); + } + + // Otherwise we need full lists of their ancestors for comparison + cur = a; + while ( ( cur = cur.parentNode ) ) { + ap.unshift( cur ); + } + cur = b; + while ( ( cur = cur.parentNode ) ) { + bp.unshift( cur ); + } + + // Walk down the tree looking for a discrepancy + while ( ap[ i ] === bp[ i ] ) { + i++; + } + + return i ? + + // Do a sibling check if the nodes have a common ancestor + siblingCheck( ap[ i ], bp[ i ] ) : + + // Otherwise nodes in our document sort first + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + /* eslint-disable eqeqeq */ + ap[ i ] == preferredDoc ? -1 : + bp[ i ] == preferredDoc ? 1 : + /* eslint-enable eqeqeq */ + 0; + }; + + return document; +}; + +Sizzle.matches = function( expr, elements ) { + return Sizzle( expr, null, null, elements ); +}; + +Sizzle.matchesSelector = function( elem, expr ) { + setDocument( elem ); + + if ( support.matchesSelector && documentIsHTML && + !nonnativeSelectorCache[ expr + " " ] && + ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && + ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { + + try { + var ret = matches.call( elem, expr ); + + // IE 9's matchesSelector returns false on disconnected nodes + if ( ret || support.disconnectedMatch || + + // As well, disconnected nodes are said to be in a document + // fragment in IE 9 + elem.document && elem.document.nodeType !== 11 ) { + return ret; + } + } catch ( e ) { + nonnativeSelectorCache( expr, true ); + } + } + + return Sizzle( expr, document, null, [ elem ] ).length > 0; +}; + +Sizzle.contains = function( context, elem ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( context.ownerDocument || context ) != document ) { + setDocument( context ); + } + return contains( context, elem ); +}; + +Sizzle.attr = function( elem, name ) { + + // Set document vars if needed + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( ( elem.ownerDocument || elem ) != document ) { + setDocument( elem ); + } + + var fn = Expr.attrHandle[ name.toLowerCase() ], + + // Don't get fooled by Object.prototype properties (jQuery #13807) + val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? + fn( elem, name, !documentIsHTML ) : + undefined; + + return val !== undefined ? + val : + support.attributes || !documentIsHTML ? + elem.getAttribute( name ) : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; +}; + +Sizzle.escape = function( sel ) { + return ( sel + "" ).replace( rcssescape, fcssescape ); +}; + +Sizzle.error = function( msg ) { + throw new Error( "Syntax error, unrecognized expression: " + msg ); +}; + +/** + * Document sorting and removing duplicates + * @param {ArrayLike} results + */ +Sizzle.uniqueSort = function( results ) { + var elem, + duplicates = [], + j = 0, + i = 0; + + // Unless we *know* we can detect duplicates, assume their presence + hasDuplicate = !support.detectDuplicates; + sortInput = !support.sortStable && results.slice( 0 ); + results.sort( sortOrder ); + + if ( hasDuplicate ) { + while ( ( elem = results[ i++ ] ) ) { + if ( elem === results[ i ] ) { + j = duplicates.push( i ); + } + } + while ( j-- ) { + results.splice( duplicates[ j ], 1 ); + } + } + + // Clear input after sorting to release objects + // See https://github.com/jquery/sizzle/pull/225 + sortInput = null; + + return results; +}; + +/** + * Utility function for retrieving the text value of an array of DOM nodes + * @param {Array|Element} elem + */ +getText = Sizzle.getText = function( elem ) { + var node, + ret = "", + i = 0, + nodeType = elem.nodeType; + + if ( !nodeType ) { + + // If no nodeType, this is expected to be an array + while ( ( node = elem[ i++ ] ) ) { + + // Do not traverse comment nodes + ret += getText( node ); + } + } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { + + // Use textContent for elements + // innerText usage removed for consistency of new lines (jQuery #11153) + if ( typeof elem.textContent === "string" ) { + return elem.textContent; + } else { + + // Traverse its children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + ret += getText( elem ); + } + } + } else if ( nodeType === 3 || nodeType === 4 ) { + return elem.nodeValue; + } + + // Do not include comment or processing instruction nodes + + return ret; +}; + +Expr = Sizzle.selectors = { + + // Can be adjusted by the user + cacheLength: 50, + + createPseudo: markFunction, + + match: matchExpr, + + attrHandle: {}, + + find: {}, + + relative: { + ">": { dir: "parentNode", first: true }, + " ": { dir: "parentNode" }, + "+": { dir: "previousSibling", first: true }, + "~": { dir: "previousSibling" } + }, + + preFilter: { + "ATTR": function( match ) { + match[ 1 ] = match[ 1 ].replace( runescape, funescape ); + + // Move the given value to match[3] whether quoted or unquoted + match[ 3 ] = ( match[ 3 ] || match[ 4 ] || + match[ 5 ] || "" ).replace( runescape, funescape ); + + if ( match[ 2 ] === "~=" ) { + match[ 3 ] = " " + match[ 3 ] + " "; + } + + return match.slice( 0, 4 ); + }, + + "CHILD": function( match ) { + + /* matches from matchExpr["CHILD"] + 1 type (only|nth|...) + 2 what (child|of-type) + 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) + 4 xn-component of xn+y argument ([+-]?\d*n|) + 5 sign of xn-component + 6 x of xn-component + 7 sign of y-component + 8 y of y-component + */ + match[ 1 ] = match[ 1 ].toLowerCase(); + + if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { + + // nth-* requires argument + if ( !match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + // numeric x and y parameters for Expr.filter.CHILD + // remember that false/true cast respectively to 0/1 + match[ 4 ] = +( match[ 4 ] ? + match[ 5 ] + ( match[ 6 ] || 1 ) : + 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); + match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); + + // other types prohibit arguments + } else if ( match[ 3 ] ) { + Sizzle.error( match[ 0 ] ); + } + + return match; + }, + + "PSEUDO": function( match ) { + var excess, + unquoted = !match[ 6 ] && match[ 2 ]; + + if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { + return null; + } + + // Accept quoted arguments as-is + if ( match[ 3 ] ) { + match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; + + // Strip excess characters from unquoted arguments + } else if ( unquoted && rpseudo.test( unquoted ) && + + // Get excess from tokenize (recursively) + ( excess = tokenize( unquoted, true ) ) && + + // advance to the next closing parenthesis + ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { + + // excess is a negative index + match[ 0 ] = match[ 0 ].slice( 0, excess ); + match[ 2 ] = unquoted.slice( 0, excess ); + } + + // Return only captures needed by the pseudo filter method (type and argument) + return match.slice( 0, 3 ); + } + }, + + filter: { + + "TAG": function( nodeNameSelector ) { + var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); + return nodeNameSelector === "*" ? + function() { + return true; + } : + function( elem ) { + return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; + }; + }, + + "CLASS": function( className ) { + var pattern = classCache[ className + " " ]; + + return pattern || + ( pattern = new RegExp( "(^|" + whitespace + + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( + className, function( elem ) { + return pattern.test( + typeof elem.className === "string" && elem.className || + typeof elem.getAttribute !== "undefined" && + elem.getAttribute( "class" ) || + "" + ); + } ); + }, + + "ATTR": function( name, operator, check ) { + return function( elem ) { + var result = Sizzle.attr( elem, name ); + + if ( result == null ) { + return operator === "!="; + } + if ( !operator ) { + return true; + } + + result += ""; + + /* eslint-disable max-len */ + + return operator === "=" ? result === check : + operator === "!=" ? result !== check : + operator === "^=" ? check && result.indexOf( check ) === 0 : + operator === "*=" ? check && result.indexOf( check ) > -1 : + operator === "$=" ? check && result.slice( -check.length ) === check : + operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : + operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : + false; + /* eslint-enable max-len */ + + }; + }, + + "CHILD": function( type, what, _argument, first, last ) { + var simple = type.slice( 0, 3 ) !== "nth", + forward = type.slice( -4 ) !== "last", + ofType = what === "of-type"; + + return first === 1 && last === 0 ? + + // Shortcut for :nth-*(n) + function( elem ) { + return !!elem.parentNode; + } : + + function( elem, _context, xml ) { + var cache, uniqueCache, outerCache, node, nodeIndex, start, + dir = simple !== forward ? "nextSibling" : "previousSibling", + parent = elem.parentNode, + name = ofType && elem.nodeName.toLowerCase(), + useCache = !xml && !ofType, + diff = false; + + if ( parent ) { + + // :(first|last|only)-(child|of-type) + if ( simple ) { + while ( dir ) { + node = elem; + while ( ( node = node[ dir ] ) ) { + if ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) { + + return false; + } + } + + // Reverse direction for :only-* (if we haven't yet done so) + start = dir = type === "only" && !start && "nextSibling"; + } + return true; + } + + start = [ forward ? parent.firstChild : parent.lastChild ]; + + // non-xml :nth-child(...) stores cache data on `parent` + if ( forward && useCache ) { + + // Seek `elem` from a previously-cached index + + // ...in a gzip-friendly way + node = parent; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex && cache[ 2 ]; + node = nodeIndex && parent.childNodes[ nodeIndex ]; + + while ( ( node = ++nodeIndex && node && node[ dir ] || + + // Fallback to seeking `elem` from the start + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + // When found, cache indexes on `parent` and break + if ( node.nodeType === 1 && ++diff && node === elem ) { + uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; + break; + } + } + + } else { + + // Use previously-cached element index if available + if ( useCache ) { + + // ...in a gzip-friendly way + node = elem; + outerCache = node[ expando ] || ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + cache = uniqueCache[ type ] || []; + nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; + diff = nodeIndex; + } + + // xml :nth-child(...) + // or :nth-last-child(...) or :nth(-last)?-of-type(...) + if ( diff === false ) { + + // Use the same loop as above to seek `elem` from the start + while ( ( node = ++nodeIndex && node && node[ dir ] || + ( diff = nodeIndex = 0 ) || start.pop() ) ) { + + if ( ( ofType ? + node.nodeName.toLowerCase() === name : + node.nodeType === 1 ) && + ++diff ) { + + // Cache the index of each encountered element + if ( useCache ) { + outerCache = node[ expando ] || + ( node[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ node.uniqueID ] || + ( outerCache[ node.uniqueID ] = {} ); + + uniqueCache[ type ] = [ dirruns, diff ]; + } + + if ( node === elem ) { + break; + } + } + } + } + } + + // Incorporate the offset, then check against cycle size + diff -= last; + return diff === first || ( diff % first === 0 && diff / first >= 0 ); + } + }; + }, + + "PSEUDO": function( pseudo, argument ) { + + // pseudo-class names are case-insensitive + // http://www.w3.org/TR/selectors/#pseudo-classes + // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters + // Remember that setFilters inherits from pseudos + var args, + fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || + Sizzle.error( "unsupported pseudo: " + pseudo ); + + // The user may use createPseudo to indicate that + // arguments are needed to create the filter function + // just as Sizzle does + if ( fn[ expando ] ) { + return fn( argument ); + } + + // But maintain support for old signatures + if ( fn.length > 1 ) { + args = [ pseudo, pseudo, "", argument ]; + return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? + markFunction( function( seed, matches ) { + var idx, + matched = fn( seed, argument ), + i = matched.length; + while ( i-- ) { + idx = indexOf( seed, matched[ i ] ); + seed[ idx ] = !( matches[ idx ] = matched[ i ] ); + } + } ) : + function( elem ) { + return fn( elem, 0, args ); + }; + } + + return fn; + } + }, + + pseudos: { + + // Potentially complex pseudos + "not": markFunction( function( selector ) { + + // Trim the selector passed to compile + // to avoid treating leading and trailing + // spaces as combinators + var input = [], + results = [], + matcher = compile( selector.replace( rtrim, "$1" ) ); + + return matcher[ expando ] ? + markFunction( function( seed, matches, _context, xml ) { + var elem, + unmatched = matcher( seed, null, xml, [] ), + i = seed.length; + + // Match elements unmatched by `matcher` + while ( i-- ) { + if ( ( elem = unmatched[ i ] ) ) { + seed[ i ] = !( matches[ i ] = elem ); + } + } + } ) : + function( elem, _context, xml ) { + input[ 0 ] = elem; + matcher( input, null, xml, results ); + + // Don't keep the element (issue #299) + input[ 0 ] = null; + return !results.pop(); + }; + } ), + + "has": markFunction( function( selector ) { + return function( elem ) { + return Sizzle( selector, elem ).length > 0; + }; + } ), + + "contains": markFunction( function( text ) { + text = text.replace( runescape, funescape ); + return function( elem ) { + return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; + }; + } ), + + // "Whether an element is represented by a :lang() selector + // is based solely on the element's language value + // being equal to the identifier C, + // or beginning with the identifier C immediately followed by "-". + // The matching of C against the element's language value is performed case-insensitively. + // The identifier C does not have to be a valid language name." + // http://www.w3.org/TR/selectors/#lang-pseudo + "lang": markFunction( function( lang ) { + + // lang value must be a valid identifier + if ( !ridentifier.test( lang || "" ) ) { + Sizzle.error( "unsupported lang: " + lang ); + } + lang = lang.replace( runescape, funescape ).toLowerCase(); + return function( elem ) { + var elemLang; + do { + if ( ( elemLang = documentIsHTML ? + elem.lang : + elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { + + elemLang = elemLang.toLowerCase(); + return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; + } + } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); + return false; + }; + } ), + + // Miscellaneous + "target": function( elem ) { + var hash = window.location && window.location.hash; + return hash && hash.slice( 1 ) === elem.id; + }, + + "root": function( elem ) { + return elem === docElem; + }, + + "focus": function( elem ) { + return elem === document.activeElement && + ( !document.hasFocus || document.hasFocus() ) && + !!( elem.type || elem.href || ~elem.tabIndex ); + }, + + // Boolean properties + "enabled": createDisabledPseudo( false ), + "disabled": createDisabledPseudo( true ), + + "checked": function( elem ) { + + // In CSS3, :checked should return both checked and selected elements + // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked + var nodeName = elem.nodeName.toLowerCase(); + return ( nodeName === "input" && !!elem.checked ) || + ( nodeName === "option" && !!elem.selected ); + }, + + "selected": function( elem ) { + + // Accessing this property makes selected-by-default + // options in Safari work properly + if ( elem.parentNode ) { + // eslint-disable-next-line no-unused-expressions + elem.parentNode.selectedIndex; + } + + return elem.selected === true; + }, + + // Contents + "empty": function( elem ) { + + // http://www.w3.org/TR/selectors/#empty-pseudo + // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), + // but not by others (comment: 8; processing instruction: 7; etc.) + // nodeType < 6 works because attributes (2) do not appear as children + for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { + if ( elem.nodeType < 6 ) { + return false; + } + } + return true; + }, + + "parent": function( elem ) { + return !Expr.pseudos[ "empty" ]( elem ); + }, + + // Element/input types + "header": function( elem ) { + return rheader.test( elem.nodeName ); + }, + + "input": function( elem ) { + return rinputs.test( elem.nodeName ); + }, + + "button": function( elem ) { + var name = elem.nodeName.toLowerCase(); + return name === "input" && elem.type === "button" || name === "button"; + }, + + "text": function( elem ) { + var attr; + return elem.nodeName.toLowerCase() === "input" && + elem.type === "text" && + + // Support: IE<8 + // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" + ( ( attr = elem.getAttribute( "type" ) ) == null || + attr.toLowerCase() === "text" ); + }, + + // Position-in-collection + "first": createPositionalPseudo( function() { + return [ 0 ]; + } ), + + "last": createPositionalPseudo( function( _matchIndexes, length ) { + return [ length - 1 ]; + } ), + + "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { + return [ argument < 0 ? argument + length : argument ]; + } ), + + "even": createPositionalPseudo( function( matchIndexes, length ) { + var i = 0; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "odd": createPositionalPseudo( function( matchIndexes, length ) { + var i = 1; + for ( ; i < length; i += 2 ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? + argument + length : + argument > length ? + length : + argument; + for ( ; --i >= 0; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ), + + "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { + var i = argument < 0 ? argument + length : argument; + for ( ; ++i < length; ) { + matchIndexes.push( i ); + } + return matchIndexes; + } ) + } +}; + +Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; + +// Add button/input type pseudos +for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { + Expr.pseudos[ i ] = createInputPseudo( i ); +} +for ( i in { submit: true, reset: true } ) { + Expr.pseudos[ i ] = createButtonPseudo( i ); +} + +// Easy API for creating new setFilters +function setFilters() {} +setFilters.prototype = Expr.filters = Expr.pseudos; +Expr.setFilters = new setFilters(); + +tokenize = Sizzle.tokenize = function( selector, parseOnly ) { + var matched, match, tokens, type, + soFar, groups, preFilters, + cached = tokenCache[ selector + " " ]; + + if ( cached ) { + return parseOnly ? 0 : cached.slice( 0 ); + } + + soFar = selector; + groups = []; + preFilters = Expr.preFilter; + + while ( soFar ) { + + // Comma and first run + if ( !matched || ( match = rcomma.exec( soFar ) ) ) { + if ( match ) { + + // Don't consume trailing commas as valid + soFar = soFar.slice( match[ 0 ].length ) || soFar; + } + groups.push( ( tokens = [] ) ); + } + + matched = false; + + // Combinators + if ( ( match = rcombinators.exec( soFar ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + + // Cast descendant combinators to space + type: match[ 0 ].replace( rtrim, " " ) + } ); + soFar = soFar.slice( matched.length ); + } + + // Filters + for ( type in Expr.filter ) { + if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || + ( match = preFilters[ type ]( match ) ) ) ) { + matched = match.shift(); + tokens.push( { + value: matched, + type: type, + matches: match + } ); + soFar = soFar.slice( matched.length ); + } + } + + if ( !matched ) { + break; + } + } + + // Return the length of the invalid excess + // if we're just parsing + // Otherwise, throw an error or return tokens + return parseOnly ? + soFar.length : + soFar ? + Sizzle.error( selector ) : + + // Cache the tokens + tokenCache( selector, groups ).slice( 0 ); +}; + +function toSelector( tokens ) { + var i = 0, + len = tokens.length, + selector = ""; + for ( ; i < len; i++ ) { + selector += tokens[ i ].value; + } + return selector; +} + +function addCombinator( matcher, combinator, base ) { + var dir = combinator.dir, + skip = combinator.next, + key = skip || dir, + checkNonElements = base && key === "parentNode", + doneName = done++; + + return combinator.first ? + + // Check against closest ancestor/preceding element + function( elem, context, xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + return matcher( elem, context, xml ); + } + } + return false; + } : + + // Check against all ancestor/preceding elements + function( elem, context, xml ) { + var oldCache, uniqueCache, outerCache, + newCache = [ dirruns, doneName ]; + + // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching + if ( xml ) { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + if ( matcher( elem, context, xml ) ) { + return true; + } + } + } + } else { + while ( ( elem = elem[ dir ] ) ) { + if ( elem.nodeType === 1 || checkNonElements ) { + outerCache = elem[ expando ] || ( elem[ expando ] = {} ); + + // Support: IE <9 only + // Defend against cloned attroperties (jQuery gh-1709) + uniqueCache = outerCache[ elem.uniqueID ] || + ( outerCache[ elem.uniqueID ] = {} ); + + if ( skip && skip === elem.nodeName.toLowerCase() ) { + elem = elem[ dir ] || elem; + } else if ( ( oldCache = uniqueCache[ key ] ) && + oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { + + // Assign to newCache so results back-propagate to previous elements + return ( newCache[ 2 ] = oldCache[ 2 ] ); + } else { + + // Reuse newcache so results back-propagate to previous elements + uniqueCache[ key ] = newCache; + + // A match means we're done; a fail means we have to keep checking + if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { + return true; + } + } + } + } + } + return false; + }; +} + +function elementMatcher( matchers ) { + return matchers.length > 1 ? + function( elem, context, xml ) { + var i = matchers.length; + while ( i-- ) { + if ( !matchers[ i ]( elem, context, xml ) ) { + return false; + } + } + return true; + } : + matchers[ 0 ]; +} + +function multipleContexts( selector, contexts, results ) { + var i = 0, + len = contexts.length; + for ( ; i < len; i++ ) { + Sizzle( selector, contexts[ i ], results ); + } + return results; +} + +function condense( unmatched, map, filter, context, xml ) { + var elem, + newUnmatched = [], + i = 0, + len = unmatched.length, + mapped = map != null; + + for ( ; i < len; i++ ) { + if ( ( elem = unmatched[ i ] ) ) { + if ( !filter || filter( elem, context, xml ) ) { + newUnmatched.push( elem ); + if ( mapped ) { + map.push( i ); + } + } + } + } + + return newUnmatched; +} + +function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { + if ( postFilter && !postFilter[ expando ] ) { + postFilter = setMatcher( postFilter ); + } + if ( postFinder && !postFinder[ expando ] ) { + postFinder = setMatcher( postFinder, postSelector ); + } + return markFunction( function( seed, results, context, xml ) { + var temp, i, elem, + preMap = [], + postMap = [], + preexisting = results.length, + + // Get initial elements from seed or context + elems = seed || multipleContexts( + selector || "*", + context.nodeType ? [ context ] : context, + [] + ), + + // Prefilter to get matcher input, preserving a map for seed-results synchronization + matcherIn = preFilter && ( seed || !selector ) ? + condense( elems, preMap, preFilter, context, xml ) : + elems, + + matcherOut = matcher ? + + // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, + postFinder || ( seed ? preFilter : preexisting || postFilter ) ? + + // ...intermediate processing is necessary + [] : + + // ...otherwise use results directly + results : + matcherIn; + + // Find primary matches + if ( matcher ) { + matcher( matcherIn, matcherOut, context, xml ); + } + + // Apply postFilter + if ( postFilter ) { + temp = condense( matcherOut, postMap ); + postFilter( temp, [], context, xml ); + + // Un-match failing elements by moving them back to matcherIn + i = temp.length; + while ( i-- ) { + if ( ( elem = temp[ i ] ) ) { + matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); + } + } + } + + if ( seed ) { + if ( postFinder || preFilter ) { + if ( postFinder ) { + + // Get the final matcherOut by condensing this intermediate into postFinder contexts + temp = []; + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) ) { + + // Restore matcherIn since elem is not yet a final match + temp.push( ( matcherIn[ i ] = elem ) ); + } + } + postFinder( null, ( matcherOut = [] ), temp, xml ); + } + + // Move matched elements from seed to results to keep them synchronized + i = matcherOut.length; + while ( i-- ) { + if ( ( elem = matcherOut[ i ] ) && + ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { + + seed[ temp ] = !( results[ temp ] = elem ); + } + } + } + + // Add elements to results, through postFinder if defined + } else { + matcherOut = condense( + matcherOut === results ? + matcherOut.splice( preexisting, matcherOut.length ) : + matcherOut + ); + if ( postFinder ) { + postFinder( null, results, matcherOut, xml ); + } else { + push.apply( results, matcherOut ); + } + } + } ); +} + +function matcherFromTokens( tokens ) { + var checkContext, matcher, j, + len = tokens.length, + leadingRelative = Expr.relative[ tokens[ 0 ].type ], + implicitRelative = leadingRelative || Expr.relative[ " " ], + i = leadingRelative ? 1 : 0, + + // The foundational matcher ensures that elements are reachable from top-level context(s) + matchContext = addCombinator( function( elem ) { + return elem === checkContext; + }, implicitRelative, true ), + matchAnyContext = addCombinator( function( elem ) { + return indexOf( checkContext, elem ) > -1; + }, implicitRelative, true ), + matchers = [ function( elem, context, xml ) { + var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( + ( checkContext = context ).nodeType ? + matchContext( elem, context, xml ) : + matchAnyContext( elem, context, xml ) ); + + // Avoid hanging onto element (issue #299) + checkContext = null; + return ret; + } ]; + + for ( ; i < len; i++ ) { + if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { + matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; + } else { + matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); + + // Return special upon seeing a positional matcher + if ( matcher[ expando ] ) { + + // Find the next relative operator (if any) for proper handling + j = ++i; + for ( ; j < len; j++ ) { + if ( Expr.relative[ tokens[ j ].type ] ) { + break; + } + } + return setMatcher( + i > 1 && elementMatcher( matchers ), + i > 1 && toSelector( + + // If the preceding token was a descendant combinator, insert an implicit any-element `*` + tokens + .slice( 0, i - 1 ) + .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) + ).replace( rtrim, "$1" ), + matcher, + i < j && matcherFromTokens( tokens.slice( i, j ) ), + j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), + j < len && toSelector( tokens ) + ); + } + matchers.push( matcher ); + } + } + + return elementMatcher( matchers ); +} + +function matcherFromGroupMatchers( elementMatchers, setMatchers ) { + var bySet = setMatchers.length > 0, + byElement = elementMatchers.length > 0, + superMatcher = function( seed, context, xml, results, outermost ) { + var elem, j, matcher, + matchedCount = 0, + i = "0", + unmatched = seed && [], + setMatched = [], + contextBackup = outermostContext, + + // We must always have either seed elements or outermost context + elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), + + // Use integer dirruns iff this is the outermost matcher + dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), + len = elems.length; + + if ( outermost ) { + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + outermostContext = context == document || context || outermost; + } + + // Add elements passing elementMatchers directly to results + // Support: IE<9, Safari + // Tolerate NodeList properties (IE: "length"; Safari: ) matching elements by id + for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { + if ( byElement && elem ) { + j = 0; + + // Support: IE 11+, Edge 17 - 18+ + // IE/Edge sometimes throw a "Permission denied" error when strict-comparing + // two documents; shallow comparisons work. + // eslint-disable-next-line eqeqeq + if ( !context && elem.ownerDocument != document ) { + setDocument( elem ); + xml = !documentIsHTML; + } + while ( ( matcher = elementMatchers[ j++ ] ) ) { + if ( matcher( elem, context || document, xml ) ) { + results.push( elem ); + break; + } + } + if ( outermost ) { + dirruns = dirrunsUnique; + } + } + + // Track unmatched elements for set filters + if ( bySet ) { + + // They will have gone through all possible matchers + if ( ( elem = !matcher && elem ) ) { + matchedCount--; + } + + // Lengthen the array for every element, matched or not + if ( seed ) { + unmatched.push( elem ); + } + } + } + + // `i` is now the count of elements visited above, and adding it to `matchedCount` + // makes the latter nonnegative. + matchedCount += i; + + // Apply set filters to unmatched elements + // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` + // equals `i`), unless we didn't visit _any_ elements in the above loop because we have + // no element matchers and no seed. + // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that + // case, which will result in a "00" `matchedCount` that differs from `i` but is also + // numerically zero. + if ( bySet && i !== matchedCount ) { + j = 0; + while ( ( matcher = setMatchers[ j++ ] ) ) { + matcher( unmatched, setMatched, context, xml ); + } + + if ( seed ) { + + // Reintegrate element matches to eliminate the need for sorting + if ( matchedCount > 0 ) { + while ( i-- ) { + if ( !( unmatched[ i ] || setMatched[ i ] ) ) { + setMatched[ i ] = pop.call( results ); + } + } + } + + // Discard index placeholder values to get only actual matches + setMatched = condense( setMatched ); + } + + // Add matches to results + push.apply( results, setMatched ); + + // Seedless set matches succeeding multiple successful matchers stipulate sorting + if ( outermost && !seed && setMatched.length > 0 && + ( matchedCount + setMatchers.length ) > 1 ) { + + Sizzle.uniqueSort( results ); + } + } + + // Override manipulation of globals by nested matchers + if ( outermost ) { + dirruns = dirrunsUnique; + outermostContext = contextBackup; + } + + return unmatched; + }; + + return bySet ? + markFunction( superMatcher ) : + superMatcher; +} + +compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { + var i, + setMatchers = [], + elementMatchers = [], + cached = compilerCache[ selector + " " ]; + + if ( !cached ) { + + // Generate a function of recursive functions that can be used to check each element + if ( !match ) { + match = tokenize( selector ); + } + i = match.length; + while ( i-- ) { + cached = matcherFromTokens( match[ i ] ); + if ( cached[ expando ] ) { + setMatchers.push( cached ); + } else { + elementMatchers.push( cached ); + } + } + + // Cache the compiled function + cached = compilerCache( + selector, + matcherFromGroupMatchers( elementMatchers, setMatchers ) + ); + + // Save selector and tokenization + cached.selector = selector; + } + return cached; +}; + +/** + * A low-level selection function that works with Sizzle's compiled + * selector functions + * @param {String|Function} selector A selector or a pre-compiled + * selector function built with Sizzle.compile + * @param {Element} context + * @param {Array} [results] + * @param {Array} [seed] A set of elements to match against + */ +select = Sizzle.select = function( selector, context, results, seed ) { + var i, tokens, token, type, find, + compiled = typeof selector === "function" && selector, + match = !seed && tokenize( ( selector = compiled.selector || selector ) ); + + results = results || []; + + // Try to minimize operations if there is only one selector in the list and no seed + // (the latter of which guarantees us context) + if ( match.length === 1 ) { + + // Reduce context if the leading compound selector is an ID + tokens = match[ 0 ] = match[ 0 ].slice( 0 ); + if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && + context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { + + context = ( Expr.find[ "ID" ]( token.matches[ 0 ] + .replace( runescape, funescape ), context ) || [] )[ 0 ]; + if ( !context ) { + return results; + + // Precompiled matchers will still verify ancestry, so step up a level + } else if ( compiled ) { + context = context.parentNode; + } + + selector = selector.slice( tokens.shift().value.length ); + } + + // Fetch a seed set for right-to-left matching + i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; + while ( i-- ) { + token = tokens[ i ]; + + // Abort if we hit a combinator + if ( Expr.relative[ ( type = token.type ) ] ) { + break; + } + if ( ( find = Expr.find[ type ] ) ) { + + // Search, expanding context for leading sibling combinators + if ( ( seed = find( + token.matches[ 0 ].replace( runescape, funescape ), + rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || + context + ) ) ) { + + // If seed is empty or no tokens remain, we can return early + tokens.splice( i, 1 ); + selector = seed.length && toSelector( tokens ); + if ( !selector ) { + push.apply( results, seed ); + return results; + } + + break; + } + } + } + } + + // Compile and execute a filtering function if one is not provided + // Provide `match` to avoid retokenization if we modified the selector above + ( compiled || compile( selector, match ) )( + seed, + context, + !documentIsHTML, + results, + !context || rsibling.test( selector ) && testContext( context.parentNode ) || context + ); + return results; +}; + +// One-time assignments + +// Sort stability +support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; + +// Support: Chrome 14-35+ +// Always assume duplicates if they aren't passed to the comparison function +support.detectDuplicates = !!hasDuplicate; + +// Initialize against the default document +setDocument(); + +// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) +// Detached nodes confoundingly follow *each other* +support.sortDetached = assert( function( el ) { + + // Should return 1, but returns 4 (following) + return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; +} ); + +// Support: IE<8 +// Prevent attribute/property "interpolation" +// https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx +if ( !assert( function( el ) { + el.innerHTML = ""; + return el.firstChild.getAttribute( "href" ) === "#"; +} ) ) { + addHandle( "type|href|height|width", function( elem, name, isXML ) { + if ( !isXML ) { + return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); + } + } ); +} + +// Support: IE<9 +// Use defaultValue in place of getAttribute("value") +if ( !support.attributes || !assert( function( el ) { + el.innerHTML = ""; + el.firstChild.setAttribute( "value", "" ); + return el.firstChild.getAttribute( "value" ) === ""; +} ) ) { + addHandle( "value", function( elem, _name, isXML ) { + if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { + return elem.defaultValue; + } + } ); +} + +// Support: IE<9 +// Use getAttributeNode to fetch booleans when getAttribute lies +if ( !assert( function( el ) { + return el.getAttribute( "disabled" ) == null; +} ) ) { + addHandle( booleans, function( elem, name, isXML ) { + var val; + if ( !isXML ) { + return elem[ name ] === true ? name.toLowerCase() : + ( val = elem.getAttributeNode( name ) ) && val.specified ? + val.value : + null; + } + } ); +} + +return Sizzle; + +} )( window ); + + + +jQuery.find = Sizzle; +jQuery.expr = Sizzle.selectors; + +// Deprecated +jQuery.expr[ ":" ] = jQuery.expr.pseudos; +jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; +jQuery.text = Sizzle.getText; +jQuery.isXMLDoc = Sizzle.isXML; +jQuery.contains = Sizzle.contains; +jQuery.escapeSelector = Sizzle.escape; + + + + +var dir = function( elem, dir, until ) { + var matched = [], + truncate = until !== undefined; + + while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { + if ( elem.nodeType === 1 ) { + if ( truncate && jQuery( elem ).is( until ) ) { + break; + } + matched.push( elem ); + } + } + return matched; +}; + + +var siblings = function( n, elem ) { + var matched = []; + + for ( ; n; n = n.nextSibling ) { + if ( n.nodeType === 1 && n !== elem ) { + matched.push( n ); + } + } + + return matched; +}; + + +var rneedsContext = jQuery.expr.match.needsContext; + + + +function nodeName( elem, name ) { + + return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); + +}; +var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); + + + +// Implement the identical functionality for filter and not +function winnow( elements, qualifier, not ) { + if ( isFunction( qualifier ) ) { + return jQuery.grep( elements, function( elem, i ) { + return !!qualifier.call( elem, i, elem ) !== not; + } ); + } + + // Single element + if ( qualifier.nodeType ) { + return jQuery.grep( elements, function( elem ) { + return ( elem === qualifier ) !== not; + } ); + } + + // Arraylike of elements (jQuery, arguments, Array) + if ( typeof qualifier !== "string" ) { + return jQuery.grep( elements, function( elem ) { + return ( indexOf.call( qualifier, elem ) > -1 ) !== not; + } ); + } + + // Filtered directly for both simple and complex selectors + return jQuery.filter( qualifier, elements, not ); +} + +jQuery.filter = function( expr, elems, not ) { + var elem = elems[ 0 ]; + + if ( not ) { + expr = ":not(" + expr + ")"; + } + + if ( elems.length === 1 && elem.nodeType === 1 ) { + return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; + } + + return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { + return elem.nodeType === 1; + } ) ); +}; + +jQuery.fn.extend( { + find: function( selector ) { + var i, ret, + len = this.length, + self = this; + + if ( typeof selector !== "string" ) { + return this.pushStack( jQuery( selector ).filter( function() { + for ( i = 0; i < len; i++ ) { + if ( jQuery.contains( self[ i ], this ) ) { + return true; + } + } + } ) ); + } + + ret = this.pushStack( [] ); + + for ( i = 0; i < len; i++ ) { + jQuery.find( selector, self[ i ], ret ); + } + + return len > 1 ? jQuery.uniqueSort( ret ) : ret; + }, + filter: function( selector ) { + return this.pushStack( winnow( this, selector || [], false ) ); + }, + not: function( selector ) { + return this.pushStack( winnow( this, selector || [], true ) ); + }, + is: function( selector ) { + return !!winnow( + this, + + // If this is a positional/relative selector, check membership in the returned set + // so $("p:first").is("p:last") won't return true for a doc with two "p". + typeof selector === "string" && rneedsContext.test( selector ) ? + jQuery( selector ) : + selector || [], + false + ).length; + } +} ); + + +// Initialize a jQuery object + + +// A central reference to the root jQuery(document) +var rootjQuery, + + // A simple way to check for HTML strings + // Prioritize #id over to avoid XSS via location.hash (#9521) + // Strict HTML recognition (#11290: must start with <) + // Shortcut simple #id case for speed + rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, + + init = jQuery.fn.init = function( selector, context, root ) { + var match, elem; + + // HANDLE: $(""), $(null), $(undefined), $(false) + if ( !selector ) { + return this; + } + + // Method init() accepts an alternate rootjQuery + // so migrate can support jQuery.sub (gh-2101) + root = root || rootjQuery; + + // Handle HTML strings + if ( typeof selector === "string" ) { + if ( selector[ 0 ] === "<" && + selector[ selector.length - 1 ] === ">" && + selector.length >= 3 ) { + + // Assume that strings that start and end with <> are HTML and skip the regex check + match = [ null, selector, null ]; + + } else { + match = rquickExpr.exec( selector ); + } + + // Match html or make sure no context is specified for #id + if ( match && ( match[ 1 ] || !context ) ) { + + // HANDLE: $(html) -> $(array) + if ( match[ 1 ] ) { + context = context instanceof jQuery ? context[ 0 ] : context; + + // Option to run scripts is true for back-compat + // Intentionally let the error be thrown if parseHTML is not present + jQuery.merge( this, jQuery.parseHTML( + match[ 1 ], + context && context.nodeType ? context.ownerDocument || context : document, + true + ) ); + + // HANDLE: $(html, props) + if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { + for ( match in context ) { + + // Properties of context are called as methods if possible + if ( isFunction( this[ match ] ) ) { + this[ match ]( context[ match ] ); + + // ...and otherwise set as attributes + } else { + this.attr( match, context[ match ] ); + } + } + } + + return this; + + // HANDLE: $(#id) + } else { + elem = document.getElementById( match[ 2 ] ); + + if ( elem ) { + + // Inject the element directly into the jQuery object + this[ 0 ] = elem; + this.length = 1; + } + return this; + } + + // HANDLE: $(expr, $(...)) + } else if ( !context || context.jquery ) { + return ( context || root ).find( selector ); + + // HANDLE: $(expr, context) + // (which is just equivalent to: $(context).find(expr) + } else { + return this.constructor( context ).find( selector ); + } + + // HANDLE: $(DOMElement) + } else if ( selector.nodeType ) { + this[ 0 ] = selector; + this.length = 1; + return this; + + // HANDLE: $(function) + // Shortcut for document ready + } else if ( isFunction( selector ) ) { + return root.ready !== undefined ? + root.ready( selector ) : + + // Execute immediately if ready is not present + selector( jQuery ); + } + + return jQuery.makeArray( selector, this ); + }; + +// Give the init function the jQuery prototype for later instantiation +init.prototype = jQuery.fn; + +// Initialize central reference +rootjQuery = jQuery( document ); + + +var rparentsprev = /^(?:parents|prev(?:Until|All))/, + + // Methods guaranteed to produce a unique set when starting from a unique set + guaranteedUnique = { + children: true, + contents: true, + next: true, + prev: true + }; + +jQuery.fn.extend( { + has: function( target ) { + var targets = jQuery( target, this ), + l = targets.length; + + return this.filter( function() { + var i = 0; + for ( ; i < l; i++ ) { + if ( jQuery.contains( this, targets[ i ] ) ) { + return true; + } + } + } ); + }, + + closest: function( selectors, context ) { + var cur, + i = 0, + l = this.length, + matched = [], + targets = typeof selectors !== "string" && jQuery( selectors ); + + // Positional selectors never match, since there's no _selection_ context + if ( !rneedsContext.test( selectors ) ) { + for ( ; i < l; i++ ) { + for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { + + // Always skip document fragments + if ( cur.nodeType < 11 && ( targets ? + targets.index( cur ) > -1 : + + // Don't pass non-elements to Sizzle + cur.nodeType === 1 && + jQuery.find.matchesSelector( cur, selectors ) ) ) { + + matched.push( cur ); + break; + } + } + } + } + + return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); + }, + + // Determine the position of an element within the set + index: function( elem ) { + + // No argument, return index in parent + if ( !elem ) { + return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; + } + + // Index in selector + if ( typeof elem === "string" ) { + return indexOf.call( jQuery( elem ), this[ 0 ] ); + } + + // Locate the position of the desired element + return indexOf.call( this, + + // If it receives a jQuery object, the first element is used + elem.jquery ? elem[ 0 ] : elem + ); + }, + + add: function( selector, context ) { + return this.pushStack( + jQuery.uniqueSort( + jQuery.merge( this.get(), jQuery( selector, context ) ) + ) + ); + }, + + addBack: function( selector ) { + return this.add( selector == null ? + this.prevObject : this.prevObject.filter( selector ) + ); + } +} ); + +function sibling( cur, dir ) { + while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} + return cur; +} + +jQuery.each( { + parent: function( elem ) { + var parent = elem.parentNode; + return parent && parent.nodeType !== 11 ? parent : null; + }, + parents: function( elem ) { + return dir( elem, "parentNode" ); + }, + parentsUntil: function( elem, _i, until ) { + return dir( elem, "parentNode", until ); + }, + next: function( elem ) { + return sibling( elem, "nextSibling" ); + }, + prev: function( elem ) { + return sibling( elem, "previousSibling" ); + }, + nextAll: function( elem ) { + return dir( elem, "nextSibling" ); + }, + prevAll: function( elem ) { + return dir( elem, "previousSibling" ); + }, + nextUntil: function( elem, _i, until ) { + return dir( elem, "nextSibling", until ); + }, + prevUntil: function( elem, _i, until ) { + return dir( elem, "previousSibling", until ); + }, + siblings: function( elem ) { + return siblings( ( elem.parentNode || {} ).firstChild, elem ); + }, + children: function( elem ) { + return siblings( elem.firstChild ); + }, + contents: function( elem ) { + if ( elem.contentDocument != null && + + // Support: IE 11+ + // elements with no `data` attribute has an object + // `contentDocument` with a `null` prototype. + getProto( elem.contentDocument ) ) { + + return elem.contentDocument; + } + + // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only + // Treat the template element as a regular one in browsers that + // don't support it. + if ( nodeName( elem, "template" ) ) { + elem = elem.content || elem; + } + + return jQuery.merge( [], elem.childNodes ); + } +}, function( name, fn ) { + jQuery.fn[ name ] = function( until, selector ) { + var matched = jQuery.map( this, fn, until ); + + if ( name.slice( -5 ) !== "Until" ) { + selector = until; + } + + if ( selector && typeof selector === "string" ) { + matched = jQuery.filter( selector, matched ); + } + + if ( this.length > 1 ) { + + // Remove duplicates + if ( !guaranteedUnique[ name ] ) { + jQuery.uniqueSort( matched ); + } + + // Reverse order for parents* and prev-derivatives + if ( rparentsprev.test( name ) ) { + matched.reverse(); + } + } + + return this.pushStack( matched ); + }; +} ); +var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); + + + +// Convert String-formatted options into Object-formatted ones +function createOptions( options ) { + var object = {}; + jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { + object[ flag ] = true; + } ); + return object; +} + +/* + * Create a callback list using the following parameters: + * + * options: an optional list of space-separated options that will change how + * the callback list behaves or a more traditional option object + * + * By default a callback list will act like an event callback list and can be + * "fired" multiple times. + * + * Possible options: + * + * once: will ensure the callback list can only be fired once (like a Deferred) + * + * memory: will keep track of previous values and will call any callback added + * after the list has been fired right away with the latest "memorized" + * values (like a Deferred) + * + * unique: will ensure a callback can only be added once (no duplicate in the list) + * + * stopOnFalse: interrupt callings when a callback returns false + * + */ +jQuery.Callbacks = function( options ) { + + // Convert options from String-formatted to Object-formatted if needed + // (we check in cache first) + options = typeof options === "string" ? + createOptions( options ) : + jQuery.extend( {}, options ); + + var // Flag to know if list is currently firing + firing, + + // Last fire value for non-forgettable lists + memory, + + // Flag to know if list was already fired + fired, + + // Flag to prevent firing + locked, + + // Actual callback list + list = [], + + // Queue of execution data for repeatable lists + queue = [], + + // Index of currently firing callback (modified by add/remove as needed) + firingIndex = -1, + + // Fire callbacks + fire = function() { + + // Enforce single-firing + locked = locked || options.once; + + // Execute callbacks for all pending executions, + // respecting firingIndex overrides and runtime changes + fired = firing = true; + for ( ; queue.length; firingIndex = -1 ) { + memory = queue.shift(); + while ( ++firingIndex < list.length ) { + + // Run callback and check for early termination + if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && + options.stopOnFalse ) { + + // Jump to end and forget the data so .add doesn't re-fire + firingIndex = list.length; + memory = false; + } + } + } + + // Forget the data if we're done with it + if ( !options.memory ) { + memory = false; + } + + firing = false; + + // Clean up if we're done firing for good + if ( locked ) { + + // Keep an empty list if we have data for future add calls + if ( memory ) { + list = []; + + // Otherwise, this object is spent + } else { + list = ""; + } + } + }, + + // Actual Callbacks object + self = { + + // Add a callback or a collection of callbacks to the list + add: function() { + if ( list ) { + + // If we have memory from a past run, we should fire after adding + if ( memory && !firing ) { + firingIndex = list.length - 1; + queue.push( memory ); + } + + ( function add( args ) { + jQuery.each( args, function( _, arg ) { + if ( isFunction( arg ) ) { + if ( !options.unique || !self.has( arg ) ) { + list.push( arg ); + } + } else if ( arg && arg.length && toType( arg ) !== "string" ) { + + // Inspect recursively + add( arg ); + } + } ); + } )( arguments ); + + if ( memory && !firing ) { + fire(); + } + } + return this; + }, + + // Remove a callback from the list + remove: function() { + jQuery.each( arguments, function( _, arg ) { + var index; + while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { + list.splice( index, 1 ); + + // Handle firing indexes + if ( index <= firingIndex ) { + firingIndex--; + } + } + } ); + return this; + }, + + // Check if a given callback is in the list. + // If no argument is given, return whether or not list has callbacks attached. + has: function( fn ) { + return fn ? + jQuery.inArray( fn, list ) > -1 : + list.length > 0; + }, + + // Remove all callbacks from the list + empty: function() { + if ( list ) { + list = []; + } + return this; + }, + + // Disable .fire and .add + // Abort any current/pending executions + // Clear all callbacks and values + disable: function() { + locked = queue = []; + list = memory = ""; + return this; + }, + disabled: function() { + return !list; + }, + + // Disable .fire + // Also disable .add unless we have memory (since it would have no effect) + // Abort any pending executions + lock: function() { + locked = queue = []; + if ( !memory && !firing ) { + list = memory = ""; + } + return this; + }, + locked: function() { + return !!locked; + }, + + // Call all callbacks with the given context and arguments + fireWith: function( context, args ) { + if ( !locked ) { + args = args || []; + args = [ context, args.slice ? args.slice() : args ]; + queue.push( args ); + if ( !firing ) { + fire(); + } + } + return this; + }, + + // Call all the callbacks with the given arguments + fire: function() { + self.fireWith( this, arguments ); + return this; + }, + + // To know if the callbacks have already been called at least once + fired: function() { + return !!fired; + } + }; + + return self; +}; + + +function Identity( v ) { + return v; +} +function Thrower( ex ) { + throw ex; +} + +function adoptValue( value, resolve, reject, noValue ) { + var method; + + try { + + // Check for promise aspect first to privilege synchronous behavior + if ( value && isFunction( ( method = value.promise ) ) ) { + method.call( value ).done( resolve ).fail( reject ); + + // Other thenables + } else if ( value && isFunction( ( method = value.then ) ) ) { + method.call( value, resolve, reject ); + + // Other non-thenables + } else { + + // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: + // * false: [ value ].slice( 0 ) => resolve( value ) + // * true: [ value ].slice( 1 ) => resolve() + resolve.apply( undefined, [ value ].slice( noValue ) ); + } + + // For Promises/A+, convert exceptions into rejections + // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in + // Deferred#then to conditionally suppress rejection. + } catch ( value ) { + + // Support: Android 4.0 only + // Strict mode functions invoked without .call/.apply get global-object context + reject.apply( undefined, [ value ] ); + } +} + +jQuery.extend( { + + Deferred: function( func ) { + var tuples = [ + + // action, add listener, callbacks, + // ... .then handlers, argument index, [final state] + [ "notify", "progress", jQuery.Callbacks( "memory" ), + jQuery.Callbacks( "memory" ), 2 ], + [ "resolve", "done", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 0, "resolved" ], + [ "reject", "fail", jQuery.Callbacks( "once memory" ), + jQuery.Callbacks( "once memory" ), 1, "rejected" ] + ], + state = "pending", + promise = { + state: function() { + return state; + }, + always: function() { + deferred.done( arguments ).fail( arguments ); + return this; + }, + "catch": function( fn ) { + return promise.then( null, fn ); + }, + + // Keep pipe for back-compat + pipe: function( /* fnDone, fnFail, fnProgress */ ) { + var fns = arguments; + + return jQuery.Deferred( function( newDefer ) { + jQuery.each( tuples, function( _i, tuple ) { + + // Map tuples (progress, done, fail) to arguments (done, fail, progress) + var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; + + // deferred.progress(function() { bind to newDefer or newDefer.notify }) + // deferred.done(function() { bind to newDefer or newDefer.resolve }) + // deferred.fail(function() { bind to newDefer or newDefer.reject }) + deferred[ tuple[ 1 ] ]( function() { + var returned = fn && fn.apply( this, arguments ); + if ( returned && isFunction( returned.promise ) ) { + returned.promise() + .progress( newDefer.notify ) + .done( newDefer.resolve ) + .fail( newDefer.reject ); + } else { + newDefer[ tuple[ 0 ] + "With" ]( + this, + fn ? [ returned ] : arguments + ); + } + } ); + } ); + fns = null; + } ).promise(); + }, + then: function( onFulfilled, onRejected, onProgress ) { + var maxDepth = 0; + function resolve( depth, deferred, handler, special ) { + return function() { + var that = this, + args = arguments, + mightThrow = function() { + var returned, then; + + // Support: Promises/A+ section 2.3.3.3.3 + // https://promisesaplus.com/#point-59 + // Ignore double-resolution attempts + if ( depth < maxDepth ) { + return; + } + + returned = handler.apply( that, args ); + + // Support: Promises/A+ section 2.3.1 + // https://promisesaplus.com/#point-48 + if ( returned === deferred.promise() ) { + throw new TypeError( "Thenable self-resolution" ); + } + + // Support: Promises/A+ sections 2.3.3.1, 3.5 + // https://promisesaplus.com/#point-54 + // https://promisesaplus.com/#point-75 + // Retrieve `then` only once + then = returned && + + // Support: Promises/A+ section 2.3.4 + // https://promisesaplus.com/#point-64 + // Only check objects and functions for thenability + ( typeof returned === "object" || + typeof returned === "function" ) && + returned.then; + + // Handle a returned thenable + if ( isFunction( then ) ) { + + // Special processors (notify) just wait for resolution + if ( special ) { + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ) + ); + + // Normal processors (resolve) also hook into progress + } else { + + // ...and disregard older resolution values + maxDepth++; + + then.call( + returned, + resolve( maxDepth, deferred, Identity, special ), + resolve( maxDepth, deferred, Thrower, special ), + resolve( maxDepth, deferred, Identity, + deferred.notifyWith ) + ); + } + + // Handle all other returned values + } else { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Identity ) { + that = undefined; + args = [ returned ]; + } + + // Process the value(s) + // Default process is resolve + ( special || deferred.resolveWith )( that, args ); + } + }, + + // Only normal processors (resolve) catch and reject exceptions + process = special ? + mightThrow : + function() { + try { + mightThrow(); + } catch ( e ) { + + if ( jQuery.Deferred.exceptionHook ) { + jQuery.Deferred.exceptionHook( e, + process.stackTrace ); + } + + // Support: Promises/A+ section 2.3.3.3.4.1 + // https://promisesaplus.com/#point-61 + // Ignore post-resolution exceptions + if ( depth + 1 >= maxDepth ) { + + // Only substitute handlers pass on context + // and multiple values (non-spec behavior) + if ( handler !== Thrower ) { + that = undefined; + args = [ e ]; + } + + deferred.rejectWith( that, args ); + } + } + }; + + // Support: Promises/A+ section 2.3.3.3.1 + // https://promisesaplus.com/#point-57 + // Re-resolve promises immediately to dodge false rejection from + // subsequent errors + if ( depth ) { + process(); + } else { + + // Call an optional hook to record the stack, in case of exception + // since it's otherwise lost when execution goes async + if ( jQuery.Deferred.getStackHook ) { + process.stackTrace = jQuery.Deferred.getStackHook(); + } + window.setTimeout( process ); + } + }; + } + + return jQuery.Deferred( function( newDefer ) { + + // progress_handlers.add( ... ) + tuples[ 0 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onProgress ) ? + onProgress : + Identity, + newDefer.notifyWith + ) + ); + + // fulfilled_handlers.add( ... ) + tuples[ 1 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onFulfilled ) ? + onFulfilled : + Identity + ) + ); + + // rejected_handlers.add( ... ) + tuples[ 2 ][ 3 ].add( + resolve( + 0, + newDefer, + isFunction( onRejected ) ? + onRejected : + Thrower + ) + ); + } ).promise(); + }, + + // Get a promise for this deferred + // If obj is provided, the promise aspect is added to the object + promise: function( obj ) { + return obj != null ? jQuery.extend( obj, promise ) : promise; + } + }, + deferred = {}; + + // Add list-specific methods + jQuery.each( tuples, function( i, tuple ) { + var list = tuple[ 2 ], + stateString = tuple[ 5 ]; + + // promise.progress = list.add + // promise.done = list.add + // promise.fail = list.add + promise[ tuple[ 1 ] ] = list.add; + + // Handle state + if ( stateString ) { + list.add( + function() { + + // state = "resolved" (i.e., fulfilled) + // state = "rejected" + state = stateString; + }, + + // rejected_callbacks.disable + // fulfilled_callbacks.disable + tuples[ 3 - i ][ 2 ].disable, + + // rejected_handlers.disable + // fulfilled_handlers.disable + tuples[ 3 - i ][ 3 ].disable, + + // progress_callbacks.lock + tuples[ 0 ][ 2 ].lock, + + // progress_handlers.lock + tuples[ 0 ][ 3 ].lock + ); + } + + // progress_handlers.fire + // fulfilled_handlers.fire + // rejected_handlers.fire + list.add( tuple[ 3 ].fire ); + + // deferred.notify = function() { deferred.notifyWith(...) } + // deferred.resolve = function() { deferred.resolveWith(...) } + // deferred.reject = function() { deferred.rejectWith(...) } + deferred[ tuple[ 0 ] ] = function() { + deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); + return this; + }; + + // deferred.notifyWith = list.fireWith + // deferred.resolveWith = list.fireWith + // deferred.rejectWith = list.fireWith + deferred[ tuple[ 0 ] + "With" ] = list.fireWith; + } ); + + // Make the deferred a promise + promise.promise( deferred ); + + // Call given func if any + if ( func ) { + func.call( deferred, deferred ); + } + + // All done! + return deferred; + }, + + // Deferred helper + when: function( singleValue ) { + var + + // count of uncompleted subordinates + remaining = arguments.length, + + // count of unprocessed arguments + i = remaining, + + // subordinate fulfillment data + resolveContexts = Array( i ), + resolveValues = slice.call( arguments ), + + // the master Deferred + master = jQuery.Deferred(), + + // subordinate callback factory + updateFunc = function( i ) { + return function( value ) { + resolveContexts[ i ] = this; + resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; + if ( !( --remaining ) ) { + master.resolveWith( resolveContexts, resolveValues ); + } + }; + }; + + // Single- and empty arguments are adopted like Promise.resolve + if ( remaining <= 1 ) { + adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject, + !remaining ); + + // Use .then() to unwrap secondary thenables (cf. gh-3000) + if ( master.state() === "pending" || + isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { + + return master.then(); + } + } + + // Multiple arguments are aggregated like Promise.all array elements + while ( i-- ) { + adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); + } + + return master.promise(); + } +} ); + + +// These usually indicate a programmer mistake during development, +// warn about them ASAP rather than swallowing them by default. +var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; + +jQuery.Deferred.exceptionHook = function( error, stack ) { + + // Support: IE 8 - 9 only + // Console exists when dev tools are open, which can happen at any time + if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { + window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); + } +}; + + + + +jQuery.readyException = function( error ) { + window.setTimeout( function() { + throw error; + } ); +}; + + + + +// The deferred used on DOM ready +var readyList = jQuery.Deferred(); + +jQuery.fn.ready = function( fn ) { + + readyList + .then( fn ) + + // Wrap jQuery.readyException in a function so that the lookup + // happens at the time of error handling instead of callback + // registration. + .catch( function( error ) { + jQuery.readyException( error ); + } ); + + return this; +}; + +jQuery.extend( { + + // Is the DOM ready to be used? Set to true once it occurs. + isReady: false, + + // A counter to track how many items to wait for before + // the ready event fires. See #6781 + readyWait: 1, + + // Handle when the DOM is ready + ready: function( wait ) { + + // Abort if there are pending holds or we're already ready + if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { + return; + } + + // Remember that the DOM is ready + jQuery.isReady = true; + + // If a normal DOM Ready event fired, decrement, and wait if need be + if ( wait !== true && --jQuery.readyWait > 0 ) { + return; + } + + // If there are functions bound, to execute + readyList.resolveWith( document, [ jQuery ] ); + } +} ); + +jQuery.ready.then = readyList.then; + +// The ready event handler and self cleanup method +function completed() { + document.removeEventListener( "DOMContentLoaded", completed ); + window.removeEventListener( "load", completed ); + jQuery.ready(); +} + +// Catch cases where $(document).ready() is called +// after the browser event has already occurred. +// Support: IE <=9 - 10 only +// Older IE sometimes signals "interactive" too soon +if ( document.readyState === "complete" || + ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { + + // Handle it asynchronously to allow scripts the opportunity to delay ready + window.setTimeout( jQuery.ready ); + +} else { + + // Use the handy event callback + document.addEventListener( "DOMContentLoaded", completed ); + + // A fallback to window.onload, that will always work + window.addEventListener( "load", completed ); +} + + + + +// Multifunctional method to get and set values of a collection +// The value/s can optionally be executed if it's a function +var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { + var i = 0, + len = elems.length, + bulk = key == null; + + // Sets many values + if ( toType( key ) === "object" ) { + chainable = true; + for ( i in key ) { + access( elems, fn, i, key[ i ], true, emptyGet, raw ); + } + + // Sets one value + } else if ( value !== undefined ) { + chainable = true; + + if ( !isFunction( value ) ) { + raw = true; + } + + if ( bulk ) { + + // Bulk operations run against the entire set + if ( raw ) { + fn.call( elems, value ); + fn = null; + + // ...except when executing function values + } else { + bulk = fn; + fn = function( elem, _key, value ) { + return bulk.call( jQuery( elem ), value ); + }; + } + } + + if ( fn ) { + for ( ; i < len; i++ ) { + fn( + elems[ i ], key, raw ? + value : + value.call( elems[ i ], i, fn( elems[ i ], key ) ) + ); + } + } + } + + if ( chainable ) { + return elems; + } + + // Gets + if ( bulk ) { + return fn.call( elems ); + } + + return len ? fn( elems[ 0 ], key ) : emptyGet; +}; + + +// Matches dashed string for camelizing +var rmsPrefix = /^-ms-/, + rdashAlpha = /-([a-z])/g; + +// Used by camelCase as callback to replace() +function fcamelCase( _all, letter ) { + return letter.toUpperCase(); +} + +// Convert dashed to camelCase; used by the css and data modules +// Support: IE <=9 - 11, Edge 12 - 15 +// Microsoft forgot to hump their vendor prefix (#9572) +function camelCase( string ) { + return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); +} +var acceptData = function( owner ) { + + // Accepts only: + // - Node + // - Node.ELEMENT_NODE + // - Node.DOCUMENT_NODE + // - Object + // - Any + return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); +}; + + + + +function Data() { + this.expando = jQuery.expando + Data.uid++; +} + +Data.uid = 1; + +Data.prototype = { + + cache: function( owner ) { + + // Check if the owner object already has a cache + var value = owner[ this.expando ]; + + // If not, create one + if ( !value ) { + value = {}; + + // We can accept data for non-element nodes in modern browsers, + // but we should not, see #8335. + // Always return an empty object. + if ( acceptData( owner ) ) { + + // If it is a node unlikely to be stringify-ed or looped over + // use plain assignment + if ( owner.nodeType ) { + owner[ this.expando ] = value; + + // Otherwise secure it in a non-enumerable property + // configurable must be true to allow the property to be + // deleted when data is removed + } else { + Object.defineProperty( owner, this.expando, { + value: value, + configurable: true + } ); + } + } + } + + return value; + }, + set: function( owner, data, value ) { + var prop, + cache = this.cache( owner ); + + // Handle: [ owner, key, value ] args + // Always use camelCase key (gh-2257) + if ( typeof data === "string" ) { + cache[ camelCase( data ) ] = value; + + // Handle: [ owner, { properties } ] args + } else { + + // Copy the properties one-by-one to the cache object + for ( prop in data ) { + cache[ camelCase( prop ) ] = data[ prop ]; + } + } + return cache; + }, + get: function( owner, key ) { + return key === undefined ? + this.cache( owner ) : + + // Always use camelCase key (gh-2257) + owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; + }, + access: function( owner, key, value ) { + + // In cases where either: + // + // 1. No key was specified + // 2. A string key was specified, but no value provided + // + // Take the "read" path and allow the get method to determine + // which value to return, respectively either: + // + // 1. The entire cache object + // 2. The data stored at the key + // + if ( key === undefined || + ( ( key && typeof key === "string" ) && value === undefined ) ) { + + return this.get( owner, key ); + } + + // When the key is not a string, or both a key and value + // are specified, set or extend (existing objects) with either: + // + // 1. An object of properties + // 2. A key and value + // + this.set( owner, key, value ); + + // Since the "set" path can have two possible entry points + // return the expected data based on which path was taken[*] + return value !== undefined ? value : key; + }, + remove: function( owner, key ) { + var i, + cache = owner[ this.expando ]; + + if ( cache === undefined ) { + return; + } + + if ( key !== undefined ) { + + // Support array or space separated string of keys + if ( Array.isArray( key ) ) { + + // If key is an array of keys... + // We always set camelCase keys, so remove that. + key = key.map( camelCase ); + } else { + key = camelCase( key ); + + // If a key with the spaces exists, use it. + // Otherwise, create an array by matching non-whitespace + key = key in cache ? + [ key ] : + ( key.match( rnothtmlwhite ) || [] ); + } + + i = key.length; + + while ( i-- ) { + delete cache[ key[ i ] ]; + } + } + + // Remove the expando if there's no more data + if ( key === undefined || jQuery.isEmptyObject( cache ) ) { + + // Support: Chrome <=35 - 45 + // Webkit & Blink performance suffers when deleting properties + // from DOM nodes, so set to undefined instead + // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) + if ( owner.nodeType ) { + owner[ this.expando ] = undefined; + } else { + delete owner[ this.expando ]; + } + } + }, + hasData: function( owner ) { + var cache = owner[ this.expando ]; + return cache !== undefined && !jQuery.isEmptyObject( cache ); + } +}; +var dataPriv = new Data(); + +var dataUser = new Data(); + + + +// Implementation Summary +// +// 1. Enforce API surface and semantic compatibility with 1.9.x branch +// 2. Improve the module's maintainability by reducing the storage +// paths to a single mechanism. +// 3. Use the same single mechanism to support "private" and "user" data. +// 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) +// 5. Avoid exposing implementation details on user objects (eg. expando properties) +// 6. Provide a clear path for implementation upgrade to WeakMap in 2014 + +var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, + rmultiDash = /[A-Z]/g; + +function getData( data ) { + if ( data === "true" ) { + return true; + } + + if ( data === "false" ) { + return false; + } + + if ( data === "null" ) { + return null; + } + + // Only convert to a number if it doesn't change the string + if ( data === +data + "" ) { + return +data; + } + + if ( rbrace.test( data ) ) { + return JSON.parse( data ); + } + + return data; +} + +function dataAttr( elem, key, data ) { + var name; + + // If nothing was found internally, try to fetch any + // data from the HTML5 data-* attribute + if ( data === undefined && elem.nodeType === 1 ) { + name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); + data = elem.getAttribute( name ); + + if ( typeof data === "string" ) { + try { + data = getData( data ); + } catch ( e ) {} + + // Make sure we set the data so it isn't changed later + dataUser.set( elem, key, data ); + } else { + data = undefined; + } + } + return data; +} + +jQuery.extend( { + hasData: function( elem ) { + return dataUser.hasData( elem ) || dataPriv.hasData( elem ); + }, + + data: function( elem, name, data ) { + return dataUser.access( elem, name, data ); + }, + + removeData: function( elem, name ) { + dataUser.remove( elem, name ); + }, + + // TODO: Now that all calls to _data and _removeData have been replaced + // with direct calls to dataPriv methods, these can be deprecated. + _data: function( elem, name, data ) { + return dataPriv.access( elem, name, data ); + }, + + _removeData: function( elem, name ) { + dataPriv.remove( elem, name ); + } +} ); + +jQuery.fn.extend( { + data: function( key, value ) { + var i, name, data, + elem = this[ 0 ], + attrs = elem && elem.attributes; + + // Gets all values + if ( key === undefined ) { + if ( this.length ) { + data = dataUser.get( elem ); + + if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { + i = attrs.length; + while ( i-- ) { + + // Support: IE 11 only + // The attrs elements can be null (#14894) + if ( attrs[ i ] ) { + name = attrs[ i ].name; + if ( name.indexOf( "data-" ) === 0 ) { + name = camelCase( name.slice( 5 ) ); + dataAttr( elem, name, data[ name ] ); + } + } + } + dataPriv.set( elem, "hasDataAttrs", true ); + } + } + + return data; + } + + // Sets multiple values + if ( typeof key === "object" ) { + return this.each( function() { + dataUser.set( this, key ); + } ); + } + + return access( this, function( value ) { + var data; + + // The calling jQuery object (element matches) is not empty + // (and therefore has an element appears at this[ 0 ]) and the + // `value` parameter was not undefined. An empty jQuery object + // will result in `undefined` for elem = this[ 0 ] which will + // throw an exception if an attempt to read a data cache is made. + if ( elem && value === undefined ) { + + // Attempt to get data from the cache + // The key will always be camelCased in Data + data = dataUser.get( elem, key ); + if ( data !== undefined ) { + return data; + } + + // Attempt to "discover" the data in + // HTML5 custom data-* attrs + data = dataAttr( elem, key ); + if ( data !== undefined ) { + return data; + } + + // We tried really hard, but the data doesn't exist. + return; + } + + // Set the data... + this.each( function() { + + // We always store the camelCased key + dataUser.set( this, key, value ); + } ); + }, null, value, arguments.length > 1, null, true ); + }, + + removeData: function( key ) { + return this.each( function() { + dataUser.remove( this, key ); + } ); + } +} ); + + +jQuery.extend( { + queue: function( elem, type, data ) { + var queue; + + if ( elem ) { + type = ( type || "fx" ) + "queue"; + queue = dataPriv.get( elem, type ); + + // Speed up dequeue by getting out quickly if this is just a lookup + if ( data ) { + if ( !queue || Array.isArray( data ) ) { + queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); + } else { + queue.push( data ); + } + } + return queue || []; + } + }, + + dequeue: function( elem, type ) { + type = type || "fx"; + + var queue = jQuery.queue( elem, type ), + startLength = queue.length, + fn = queue.shift(), + hooks = jQuery._queueHooks( elem, type ), + next = function() { + jQuery.dequeue( elem, type ); + }; + + // If the fx queue is dequeued, always remove the progress sentinel + if ( fn === "inprogress" ) { + fn = queue.shift(); + startLength--; + } + + if ( fn ) { + + // Add a progress sentinel to prevent the fx queue from being + // automatically dequeued + if ( type === "fx" ) { + queue.unshift( "inprogress" ); + } + + // Clear up the last queue stop function + delete hooks.stop; + fn.call( elem, next, hooks ); + } + + if ( !startLength && hooks ) { + hooks.empty.fire(); + } + }, + + // Not public - generate a queueHooks object, or return the current one + _queueHooks: function( elem, type ) { + var key = type + "queueHooks"; + return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { + empty: jQuery.Callbacks( "once memory" ).add( function() { + dataPriv.remove( elem, [ type + "queue", key ] ); + } ) + } ); + } +} ); + +jQuery.fn.extend( { + queue: function( type, data ) { + var setter = 2; + + if ( typeof type !== "string" ) { + data = type; + type = "fx"; + setter--; + } + + if ( arguments.length < setter ) { + return jQuery.queue( this[ 0 ], type ); + } + + return data === undefined ? + this : + this.each( function() { + var queue = jQuery.queue( this, type, data ); + + // Ensure a hooks for this queue + jQuery._queueHooks( this, type ); + + if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { + jQuery.dequeue( this, type ); + } + } ); + }, + dequeue: function( type ) { + return this.each( function() { + jQuery.dequeue( this, type ); + } ); + }, + clearQueue: function( type ) { + return this.queue( type || "fx", [] ); + }, + + // Get a promise resolved when queues of a certain type + // are emptied (fx is the type by default) + promise: function( type, obj ) { + var tmp, + count = 1, + defer = jQuery.Deferred(), + elements = this, + i = this.length, + resolve = function() { + if ( !( --count ) ) { + defer.resolveWith( elements, [ elements ] ); + } + }; + + if ( typeof type !== "string" ) { + obj = type; + type = undefined; + } + type = type || "fx"; + + while ( i-- ) { + tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); + if ( tmp && tmp.empty ) { + count++; + tmp.empty.add( resolve ); + } + } + resolve(); + return defer.promise( obj ); + } +} ); +var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; + +var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); + + +var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; + +var documentElement = document.documentElement; + + + + var isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ); + }, + composed = { composed: true }; + + // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only + // Check attachment across shadow DOM boundaries when possible (gh-3504) + // Support: iOS 10.0-10.2 only + // Early iOS 10 versions support `attachShadow` but not `getRootNode`, + // leading to errors. We need to check for `getRootNode`. + if ( documentElement.getRootNode ) { + isAttached = function( elem ) { + return jQuery.contains( elem.ownerDocument, elem ) || + elem.getRootNode( composed ) === elem.ownerDocument; + }; + } +var isHiddenWithinTree = function( elem, el ) { + + // isHiddenWithinTree might be called from jQuery#filter function; + // in that case, element will be second argument + elem = el || elem; + + // Inline style trumps all + return elem.style.display === "none" || + elem.style.display === "" && + + // Otherwise, check computed style + // Support: Firefox <=43 - 45 + // Disconnected elements can have computed display: none, so first confirm that elem is + // in the document. + isAttached( elem ) && + + jQuery.css( elem, "display" ) === "none"; + }; + + + +function adjustCSS( elem, prop, valueParts, tween ) { + var adjusted, scale, + maxIterations = 20, + currentValue = tween ? + function() { + return tween.cur(); + } : + function() { + return jQuery.css( elem, prop, "" ); + }, + initial = currentValue(), + unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), + + // Starting value computation is required for potential unit mismatches + initialInUnit = elem.nodeType && + ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && + rcssNum.exec( jQuery.css( elem, prop ) ); + + if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { + + // Support: Firefox <=54 + // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) + initial = initial / 2; + + // Trust units reported by jQuery.css + unit = unit || initialInUnit[ 3 ]; + + // Iteratively approximate from a nonzero starting point + initialInUnit = +initial || 1; + + while ( maxIterations-- ) { + + // Evaluate and update our best guess (doubling guesses that zero out). + // Finish if the scale equals or crosses 1 (making the old*new product non-positive). + jQuery.style( elem, prop, initialInUnit + unit ); + if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { + maxIterations = 0; + } + initialInUnit = initialInUnit / scale; + + } + + initialInUnit = initialInUnit * 2; + jQuery.style( elem, prop, initialInUnit + unit ); + + // Make sure we update the tween properties later on + valueParts = valueParts || []; + } + + if ( valueParts ) { + initialInUnit = +initialInUnit || +initial || 0; + + // Apply relative offset (+=/-=) if specified + adjusted = valueParts[ 1 ] ? + initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : + +valueParts[ 2 ]; + if ( tween ) { + tween.unit = unit; + tween.start = initialInUnit; + tween.end = adjusted; + } + } + return adjusted; +} + + +var defaultDisplayMap = {}; + +function getDefaultDisplay( elem ) { + var temp, + doc = elem.ownerDocument, + nodeName = elem.nodeName, + display = defaultDisplayMap[ nodeName ]; + + if ( display ) { + return display; + } + + temp = doc.body.appendChild( doc.createElement( nodeName ) ); + display = jQuery.css( temp, "display" ); + + temp.parentNode.removeChild( temp ); + + if ( display === "none" ) { + display = "block"; + } + defaultDisplayMap[ nodeName ] = display; + + return display; +} + +function showHide( elements, show ) { + var display, elem, + values = [], + index = 0, + length = elements.length; + + // Determine new display value for elements that need to change + for ( ; index < length; index++ ) { + elem = elements[ index ]; + if ( !elem.style ) { + continue; + } + + display = elem.style.display; + if ( show ) { + + // Since we force visibility upon cascade-hidden elements, an immediate (and slow) + // check is required in this first loop unless we have a nonempty display value (either + // inline or about-to-be-restored) + if ( display === "none" ) { + values[ index ] = dataPriv.get( elem, "display" ) || null; + if ( !values[ index ] ) { + elem.style.display = ""; + } + } + if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { + values[ index ] = getDefaultDisplay( elem ); + } + } else { + if ( display !== "none" ) { + values[ index ] = "none"; + + // Remember what we're overwriting + dataPriv.set( elem, "display", display ); + } + } + } + + // Set the display of the elements in a second loop to avoid constant reflow + for ( index = 0; index < length; index++ ) { + if ( values[ index ] != null ) { + elements[ index ].style.display = values[ index ]; + } + } + + return elements; +} + +jQuery.fn.extend( { + show: function() { + return showHide( this, true ); + }, + hide: function() { + return showHide( this ); + }, + toggle: function( state ) { + if ( typeof state === "boolean" ) { + return state ? this.show() : this.hide(); + } + + return this.each( function() { + if ( isHiddenWithinTree( this ) ) { + jQuery( this ).show(); + } else { + jQuery( this ).hide(); + } + } ); + } +} ); +var rcheckableType = ( /^(?:checkbox|radio)$/i ); + +var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); + +var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); + + + +( function() { + var fragment = document.createDocumentFragment(), + div = fragment.appendChild( document.createElement( "div" ) ), + input = document.createElement( "input" ); + + // Support: Android 4.0 - 4.3 only + // Check state lost if the name is set (#11217) + // Support: Windows Web Apps (WWA) + // `name` and `type` must use .setAttribute for WWA (#14901) + input.setAttribute( "type", "radio" ); + input.setAttribute( "checked", "checked" ); + input.setAttribute( "name", "t" ); + + div.appendChild( input ); + + // Support: Android <=4.1 only + // Older WebKit doesn't clone checked state correctly in fragments + support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; + + // Support: IE <=11 only + // Make sure textarea (and checkbox) defaultValue is properly cloned + div.innerHTML = ""; + support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; + + // Support: IE <=9 only + // IE <=9 replaces "; + support.option = !!div.lastChild; +} )(); + + +// We have to close these tags to support XHTML (#13200) +var wrapMap = { + + // XHTML parsers do not magically insert elements in the + // same way that tag soup parsers do. So we cannot shorten + // this by omitting or other required elements. + thead: [ 1, "", "
    " ], + col: [ 2, "", "
    " ], + tr: [ 2, "", "
    " ], + td: [ 3, "", "
    " ], + + _default: [ 0, "", "" ] +}; + +wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; +wrapMap.th = wrapMap.td; + +// Support: IE <=9 only +if ( !support.option ) { + wrapMap.optgroup = wrapMap.option = [ 1, "" ]; +} + + +function getAll( context, tag ) { + + // Support: IE <=9 - 11 only + // Use typeof to avoid zero-argument method invocation on host objects (#15151) + var ret; + + if ( typeof context.getElementsByTagName !== "undefined" ) { + ret = context.getElementsByTagName( tag || "*" ); + + } else if ( typeof context.querySelectorAll !== "undefined" ) { + ret = context.querySelectorAll( tag || "*" ); + + } else { + ret = []; + } + + if ( tag === undefined || tag && nodeName( context, tag ) ) { + return jQuery.merge( [ context ], ret ); + } + + return ret; +} + + +// Mark scripts as having already been evaluated +function setGlobalEval( elems, refElements ) { + var i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + dataPriv.set( + elems[ i ], + "globalEval", + !refElements || dataPriv.get( refElements[ i ], "globalEval" ) + ); + } +} + + +var rhtml = /<|&#?\w+;/; + +function buildFragment( elems, context, scripts, selection, ignored ) { + var elem, tmp, tag, wrap, attached, j, + fragment = context.createDocumentFragment(), + nodes = [], + i = 0, + l = elems.length; + + for ( ; i < l; i++ ) { + elem = elems[ i ]; + + if ( elem || elem === 0 ) { + + // Add nodes directly + if ( toType( elem ) === "object" ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); + + // Convert non-html into a text node + } else if ( !rhtml.test( elem ) ) { + nodes.push( context.createTextNode( elem ) ); + + // Convert html into DOM nodes + } else { + tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); + + // Deserialize a standard representation + tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); + wrap = wrapMap[ tag ] || wrapMap._default; + tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; + + // Descend through wrappers to the right content + j = wrap[ 0 ]; + while ( j-- ) { + tmp = tmp.lastChild; + } + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( nodes, tmp.childNodes ); + + // Remember the top-level container + tmp = fragment.firstChild; + + // Ensure the created nodes are orphaned (#12392) + tmp.textContent = ""; + } + } + } + + // Remove wrapper from fragment + fragment.textContent = ""; + + i = 0; + while ( ( elem = nodes[ i++ ] ) ) { + + // Skip elements already in the context collection (trac-4087) + if ( selection && jQuery.inArray( elem, selection ) > -1 ) { + if ( ignored ) { + ignored.push( elem ); + } + continue; + } + + attached = isAttached( elem ); + + // Append to fragment + tmp = getAll( fragment.appendChild( elem ), "script" ); + + // Preserve script evaluation history + if ( attached ) { + setGlobalEval( tmp ); + } + + // Capture executables + if ( scripts ) { + j = 0; + while ( ( elem = tmp[ j++ ] ) ) { + if ( rscriptType.test( elem.type || "" ) ) { + scripts.push( elem ); + } + } + } + } + + return fragment; +} + + +var + rkeyEvent = /^key/, + rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, + rtypenamespace = /^([^.]*)(?:\.(.+)|)/; + +function returnTrue() { + return true; +} + +function returnFalse() { + return false; +} + +// Support: IE <=9 - 11+ +// focus() and blur() are asynchronous, except when they are no-op. +// So expect focus to be synchronous when the element is already active, +// and blur to be synchronous when the element is not already active. +// (focus and blur are always synchronous in other supported browsers, +// this just defines when we can count on it). +function expectSync( elem, type ) { + return ( elem === safeActiveElement() ) === ( type === "focus" ); +} + +// Support: IE <=9 only +// Accessing document.activeElement can throw unexpectedly +// https://bugs.jquery.com/ticket/13393 +function safeActiveElement() { + try { + return document.activeElement; + } catch ( err ) { } +} + +function on( elem, types, selector, data, fn, one ) { + var origFn, type; + + // Types can be a map of types/handlers + if ( typeof types === "object" ) { + + // ( types-Object, selector, data ) + if ( typeof selector !== "string" ) { + + // ( types-Object, data ) + data = data || selector; + selector = undefined; + } + for ( type in types ) { + on( elem, type, selector, data, types[ type ], one ); + } + return elem; + } + + if ( data == null && fn == null ) { + + // ( types, fn ) + fn = selector; + data = selector = undefined; + } else if ( fn == null ) { + if ( typeof selector === "string" ) { + + // ( types, selector, fn ) + fn = data; + data = undefined; + } else { + + // ( types, data, fn ) + fn = data; + data = selector; + selector = undefined; + } + } + if ( fn === false ) { + fn = returnFalse; + } else if ( !fn ) { + return elem; + } + + if ( one === 1 ) { + origFn = fn; + fn = function( event ) { + + // Can use an empty set, since event contains the info + jQuery().off( event ); + return origFn.apply( this, arguments ); + }; + + // Use same guid so caller can remove using origFn + fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); + } + return elem.each( function() { + jQuery.event.add( this, types, fn, data, selector ); + } ); +} + +/* + * Helper functions for managing events -- not part of the public interface. + * Props to Dean Edwards' addEvent library for many of the ideas. + */ +jQuery.event = { + + global: {}, + + add: function( elem, types, handler, data, selector ) { + + var handleObjIn, eventHandle, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.get( elem ); + + // Only attach events to objects that accept data + if ( !acceptData( elem ) ) { + return; + } + + // Caller can pass in an object of custom data in lieu of the handler + if ( handler.handler ) { + handleObjIn = handler; + handler = handleObjIn.handler; + selector = handleObjIn.selector; + } + + // Ensure that invalid selectors throw exceptions at attach time + // Evaluate against documentElement in case elem is a non-element node (e.g., document) + if ( selector ) { + jQuery.find.matchesSelector( documentElement, selector ); + } + + // Make sure that the handler has a unique ID, used to find/remove it later + if ( !handler.guid ) { + handler.guid = jQuery.guid++; + } + + // Init the element's event structure and main handler, if this is the first + if ( !( events = elemData.events ) ) { + events = elemData.events = Object.create( null ); + } + if ( !( eventHandle = elemData.handle ) ) { + eventHandle = elemData.handle = function( e ) { + + // Discard the second event of a jQuery.event.trigger() and + // when an event is called after a page has unloaded + return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? + jQuery.event.dispatch.apply( elem, arguments ) : undefined; + }; + } + + // Handle multiple events separated by a space + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // There *must* be a type, no attaching namespace-only handlers + if ( !type ) { + continue; + } + + // If event changes its type, use the special event handlers for the changed type + special = jQuery.event.special[ type ] || {}; + + // If selector defined, determine special event api type, otherwise given type + type = ( selector ? special.delegateType : special.bindType ) || type; + + // Update special based on newly reset type + special = jQuery.event.special[ type ] || {}; + + // handleObj is passed to all event handlers + handleObj = jQuery.extend( { + type: type, + origType: origType, + data: data, + handler: handler, + guid: handler.guid, + selector: selector, + needsContext: selector && jQuery.expr.match.needsContext.test( selector ), + namespace: namespaces.join( "." ) + }, handleObjIn ); + + // Init the event handler queue if we're the first + if ( !( handlers = events[ type ] ) ) { + handlers = events[ type ] = []; + handlers.delegateCount = 0; + + // Only use addEventListener if the special events handler returns false + if ( !special.setup || + special.setup.call( elem, data, namespaces, eventHandle ) === false ) { + + if ( elem.addEventListener ) { + elem.addEventListener( type, eventHandle ); + } + } + } + + if ( special.add ) { + special.add.call( elem, handleObj ); + + if ( !handleObj.handler.guid ) { + handleObj.handler.guid = handler.guid; + } + } + + // Add to the element's handler list, delegates in front + if ( selector ) { + handlers.splice( handlers.delegateCount++, 0, handleObj ); + } else { + handlers.push( handleObj ); + } + + // Keep track of which events have ever been used, for event optimization + jQuery.event.global[ type ] = true; + } + + }, + + // Detach an event or set of events from an element + remove: function( elem, types, handler, selector, mappedTypes ) { + + var j, origCount, tmp, + events, t, handleObj, + special, handlers, type, namespaces, origType, + elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); + + if ( !elemData || !( events = elemData.events ) ) { + return; + } + + // Once for each type.namespace in types; type may be omitted + types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; + t = types.length; + while ( t-- ) { + tmp = rtypenamespace.exec( types[ t ] ) || []; + type = origType = tmp[ 1 ]; + namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); + + // Unbind all events (on this namespace, if provided) for the element + if ( !type ) { + for ( type in events ) { + jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); + } + continue; + } + + special = jQuery.event.special[ type ] || {}; + type = ( selector ? special.delegateType : special.bindType ) || type; + handlers = events[ type ] || []; + tmp = tmp[ 2 ] && + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); + + // Remove matching events + origCount = j = handlers.length; + while ( j-- ) { + handleObj = handlers[ j ]; + + if ( ( mappedTypes || origType === handleObj.origType ) && + ( !handler || handler.guid === handleObj.guid ) && + ( !tmp || tmp.test( handleObj.namespace ) ) && + ( !selector || selector === handleObj.selector || + selector === "**" && handleObj.selector ) ) { + handlers.splice( j, 1 ); + + if ( handleObj.selector ) { + handlers.delegateCount--; + } + if ( special.remove ) { + special.remove.call( elem, handleObj ); + } + } + } + + // Remove generic event handler if we removed something and no more handlers exist + // (avoids potential for endless recursion during removal of special event handlers) + if ( origCount && !handlers.length ) { + if ( !special.teardown || + special.teardown.call( elem, namespaces, elemData.handle ) === false ) { + + jQuery.removeEvent( elem, type, elemData.handle ); + } + + delete events[ type ]; + } + } + + // Remove data and the expando if it's no longer used + if ( jQuery.isEmptyObject( events ) ) { + dataPriv.remove( elem, "handle events" ); + } + }, + + dispatch: function( nativeEvent ) { + + var i, j, ret, matched, handleObj, handlerQueue, + args = new Array( arguments.length ), + + // Make a writable jQuery.Event from the native event object + event = jQuery.event.fix( nativeEvent ), + + handlers = ( + dataPriv.get( this, "events" ) || Object.create( null ) + )[ event.type ] || [], + special = jQuery.event.special[ event.type ] || {}; + + // Use the fix-ed jQuery.Event rather than the (read-only) native event + args[ 0 ] = event; + + for ( i = 1; i < arguments.length; i++ ) { + args[ i ] = arguments[ i ]; + } + + event.delegateTarget = this; + + // Call the preDispatch hook for the mapped type, and let it bail if desired + if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { + return; + } + + // Determine handlers + handlerQueue = jQuery.event.handlers.call( this, event, handlers ); + + // Run delegates first; they may want to stop propagation beneath us + i = 0; + while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { + event.currentTarget = matched.elem; + + j = 0; + while ( ( handleObj = matched.handlers[ j++ ] ) && + !event.isImmediatePropagationStopped() ) { + + // If the event is namespaced, then each handler is only invoked if it is + // specially universal or its namespaces are a superset of the event's. + if ( !event.rnamespace || handleObj.namespace === false || + event.rnamespace.test( handleObj.namespace ) ) { + + event.handleObj = handleObj; + event.data = handleObj.data; + + ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || + handleObj.handler ).apply( matched.elem, args ); + + if ( ret !== undefined ) { + if ( ( event.result = ret ) === false ) { + event.preventDefault(); + event.stopPropagation(); + } + } + } + } + } + + // Call the postDispatch hook for the mapped type + if ( special.postDispatch ) { + special.postDispatch.call( this, event ); + } + + return event.result; + }, + + handlers: function( event, handlers ) { + var i, handleObj, sel, matchedHandlers, matchedSelectors, + handlerQueue = [], + delegateCount = handlers.delegateCount, + cur = event.target; + + // Find delegate handlers + if ( delegateCount && + + // Support: IE <=9 + // Black-hole SVG instance trees (trac-13180) + cur.nodeType && + + // Support: Firefox <=42 + // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) + // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click + // Support: IE 11 only + // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) + !( event.type === "click" && event.button >= 1 ) ) { + + for ( ; cur !== this; cur = cur.parentNode || this ) { + + // Don't check non-elements (#13208) + // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) + if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { + matchedHandlers = []; + matchedSelectors = {}; + for ( i = 0; i < delegateCount; i++ ) { + handleObj = handlers[ i ]; + + // Don't conflict with Object.prototype properties (#13203) + sel = handleObj.selector + " "; + + if ( matchedSelectors[ sel ] === undefined ) { + matchedSelectors[ sel ] = handleObj.needsContext ? + jQuery( sel, this ).index( cur ) > -1 : + jQuery.find( sel, this, null, [ cur ] ).length; + } + if ( matchedSelectors[ sel ] ) { + matchedHandlers.push( handleObj ); + } + } + if ( matchedHandlers.length ) { + handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); + } + } + } + } + + // Add the remaining (directly-bound) handlers + cur = this; + if ( delegateCount < handlers.length ) { + handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); + } + + return handlerQueue; + }, + + addProp: function( name, hook ) { + Object.defineProperty( jQuery.Event.prototype, name, { + enumerable: true, + configurable: true, + + get: isFunction( hook ) ? + function() { + if ( this.originalEvent ) { + return hook( this.originalEvent ); + } + } : + function() { + if ( this.originalEvent ) { + return this.originalEvent[ name ]; + } + }, + + set: function( value ) { + Object.defineProperty( this, name, { + enumerable: true, + configurable: true, + writable: true, + value: value + } ); + } + } ); + }, + + fix: function( originalEvent ) { + return originalEvent[ jQuery.expando ] ? + originalEvent : + new jQuery.Event( originalEvent ); + }, + + special: { + load: { + + // Prevent triggered image.load events from bubbling to window.load + noBubble: true + }, + click: { + + // Utilize native event to ensure correct state for checkable inputs + setup: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Claim the first handler + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + // dataPriv.set( el, "click", ... ) + leverageNative( el, "click", returnTrue ); + } + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function( data ) { + + // For mutual compressibility with _default, replace `this` access with a local var. + // `|| data` is dead code meant only to preserve the variable through minification. + var el = this || data; + + // Force setup before triggering a click + if ( rcheckableType.test( el.type ) && + el.click && nodeName( el, "input" ) ) { + + leverageNative( el, "click" ); + } + + // Return non-false to allow normal event-path propagation + return true; + }, + + // For cross-browser consistency, suppress native .click() on links + // Also prevent it if we're currently inside a leveraged native-event stack + _default: function( event ) { + var target = event.target; + return rcheckableType.test( target.type ) && + target.click && nodeName( target, "input" ) && + dataPriv.get( target, "click" ) || + nodeName( target, "a" ); + } + }, + + beforeunload: { + postDispatch: function( event ) { + + // Support: Firefox 20+ + // Firefox doesn't alert if the returnValue field is not set. + if ( event.result !== undefined && event.originalEvent ) { + event.originalEvent.returnValue = event.result; + } + } + } + } +}; + +// Ensure the presence of an event listener that handles manually-triggered +// synthetic events by interrupting progress until reinvoked in response to +// *native* events that it fires directly, ensuring that state changes have +// already occurred before other listeners are invoked. +function leverageNative( el, type, expectSync ) { + + // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add + if ( !expectSync ) { + if ( dataPriv.get( el, type ) === undefined ) { + jQuery.event.add( el, type, returnTrue ); + } + return; + } + + // Register the controller as a special universal handler for all event namespaces + dataPriv.set( el, type, false ); + jQuery.event.add( el, type, { + namespace: false, + handler: function( event ) { + var notAsync, result, + saved = dataPriv.get( this, type ); + + if ( ( event.isTrigger & 1 ) && this[ type ] ) { + + // Interrupt processing of the outer synthetic .trigger()ed event + // Saved data should be false in such cases, but might be a leftover capture object + // from an async native handler (gh-4350) + if ( !saved.length ) { + + // Store arguments for use when handling the inner native event + // There will always be at least one argument (an event object), so this array + // will not be confused with a leftover capture object. + saved = slice.call( arguments ); + dataPriv.set( this, type, saved ); + + // Trigger the native event and capture its result + // Support: IE <=9 - 11+ + // focus() and blur() are asynchronous + notAsync = expectSync( this, type ); + this[ type ](); + result = dataPriv.get( this, type ); + if ( saved !== result || notAsync ) { + dataPriv.set( this, type, false ); + } else { + result = {}; + } + if ( saved !== result ) { + + // Cancel the outer synthetic event + event.stopImmediatePropagation(); + event.preventDefault(); + return result.value; + } + + // If this is an inner synthetic event for an event with a bubbling surrogate + // (focus or blur), assume that the surrogate already propagated from triggering the + // native event and prevent that from happening again here. + // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the + // bubbling surrogate propagates *after* the non-bubbling base), but that seems + // less bad than duplication. + } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { + event.stopPropagation(); + } + + // If this is a native event triggered above, everything is now in order + // Fire an inner synthetic event with the original arguments + } else if ( saved.length ) { + + // ...and capture the result + dataPriv.set( this, type, { + value: jQuery.event.trigger( + + // Support: IE <=9 - 11+ + // Extend with the prototype to reset the above stopImmediatePropagation() + jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), + saved.slice( 1 ), + this + ) + } ); + + // Abort handling of the native event + event.stopImmediatePropagation(); + } + } + } ); +} + +jQuery.removeEvent = function( elem, type, handle ) { + + // This "if" is needed for plain objects + if ( elem.removeEventListener ) { + elem.removeEventListener( type, handle ); + } +}; + +jQuery.Event = function( src, props ) { + + // Allow instantiation without the 'new' keyword + if ( !( this instanceof jQuery.Event ) ) { + return new jQuery.Event( src, props ); + } + + // Event object + if ( src && src.type ) { + this.originalEvent = src; + this.type = src.type; + + // Events bubbling up the document may have been marked as prevented + // by a handler lower down the tree; reflect the correct value. + this.isDefaultPrevented = src.defaultPrevented || + src.defaultPrevented === undefined && + + // Support: Android <=2.3 only + src.returnValue === false ? + returnTrue : + returnFalse; + + // Create target properties + // Support: Safari <=6 - 7 only + // Target should not be a text node (#504, #13143) + this.target = ( src.target && src.target.nodeType === 3 ) ? + src.target.parentNode : + src.target; + + this.currentTarget = src.currentTarget; + this.relatedTarget = src.relatedTarget; + + // Event type + } else { + this.type = src; + } + + // Put explicitly provided properties onto the event object + if ( props ) { + jQuery.extend( this, props ); + } + + // Create a timestamp if incoming event doesn't have one + this.timeStamp = src && src.timeStamp || Date.now(); + + // Mark it as fixed + this[ jQuery.expando ] = true; +}; + +// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding +// https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html +jQuery.Event.prototype = { + constructor: jQuery.Event, + isDefaultPrevented: returnFalse, + isPropagationStopped: returnFalse, + isImmediatePropagationStopped: returnFalse, + isSimulated: false, + + preventDefault: function() { + var e = this.originalEvent; + + this.isDefaultPrevented = returnTrue; + + if ( e && !this.isSimulated ) { + e.preventDefault(); + } + }, + stopPropagation: function() { + var e = this.originalEvent; + + this.isPropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopPropagation(); + } + }, + stopImmediatePropagation: function() { + var e = this.originalEvent; + + this.isImmediatePropagationStopped = returnTrue; + + if ( e && !this.isSimulated ) { + e.stopImmediatePropagation(); + } + + this.stopPropagation(); + } +}; + +// Includes all common event props including KeyEvent and MouseEvent specific props +jQuery.each( { + altKey: true, + bubbles: true, + cancelable: true, + changedTouches: true, + ctrlKey: true, + detail: true, + eventPhase: true, + metaKey: true, + pageX: true, + pageY: true, + shiftKey: true, + view: true, + "char": true, + code: true, + charCode: true, + key: true, + keyCode: true, + button: true, + buttons: true, + clientX: true, + clientY: true, + offsetX: true, + offsetY: true, + pointerId: true, + pointerType: true, + screenX: true, + screenY: true, + targetTouches: true, + toElement: true, + touches: true, + + which: function( event ) { + var button = event.button; + + // Add which for key events + if ( event.which == null && rkeyEvent.test( event.type ) ) { + return event.charCode != null ? event.charCode : event.keyCode; + } + + // Add which for click: 1 === left; 2 === middle; 3 === right + if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { + if ( button & 1 ) { + return 1; + } + + if ( button & 2 ) { + return 3; + } + + if ( button & 4 ) { + return 2; + } + + return 0; + } + + return event.which; + } +}, jQuery.event.addProp ); + +jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { + jQuery.event.special[ type ] = { + + // Utilize native event if possible so blur/focus sequence is correct + setup: function() { + + // Claim the first handler + // dataPriv.set( this, "focus", ... ) + // dataPriv.set( this, "blur", ... ) + leverageNative( this, type, expectSync ); + + // Return false to allow normal processing in the caller + return false; + }, + trigger: function() { + + // Force setup before trigger + leverageNative( this, type ); + + // Return non-false to allow normal event-path propagation + return true; + }, + + delegateType: delegateType + }; +} ); + +// Create mouseenter/leave events using mouseover/out and event-time checks +// so that event delegation works in jQuery. +// Do the same for pointerenter/pointerleave and pointerover/pointerout +// +// Support: Safari 7 only +// Safari sends mouseenter too often; see: +// https://bugs.chromium.org/p/chromium/issues/detail?id=470258 +// for the description of the bug (it existed in older Chrome versions as well). +jQuery.each( { + mouseenter: "mouseover", + mouseleave: "mouseout", + pointerenter: "pointerover", + pointerleave: "pointerout" +}, function( orig, fix ) { + jQuery.event.special[ orig ] = { + delegateType: fix, + bindType: fix, + + handle: function( event ) { + var ret, + target = this, + related = event.relatedTarget, + handleObj = event.handleObj; + + // For mouseenter/leave call the handler if related is outside the target. + // NB: No relatedTarget if the mouse left/entered the browser window + if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { + event.type = handleObj.origType; + ret = handleObj.handler.apply( this, arguments ); + event.type = fix; + } + return ret; + } + }; +} ); + +jQuery.fn.extend( { + + on: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn ); + }, + one: function( types, selector, data, fn ) { + return on( this, types, selector, data, fn, 1 ); + }, + off: function( types, selector, fn ) { + var handleObj, type; + if ( types && types.preventDefault && types.handleObj ) { + + // ( event ) dispatched jQuery.Event + handleObj = types.handleObj; + jQuery( types.delegateTarget ).off( + handleObj.namespace ? + handleObj.origType + "." + handleObj.namespace : + handleObj.origType, + handleObj.selector, + handleObj.handler + ); + return this; + } + if ( typeof types === "object" ) { + + // ( types-object [, selector] ) + for ( type in types ) { + this.off( type, selector, types[ type ] ); + } + return this; + } + if ( selector === false || typeof selector === "function" ) { + + // ( types [, fn] ) + fn = selector; + selector = undefined; + } + if ( fn === false ) { + fn = returnFalse; + } + return this.each( function() { + jQuery.event.remove( this, types, fn, selector ); + } ); + } +} ); + + +var + + // Support: IE <=10 - 11, Edge 12 - 13 only + // In IE/Edge using regex groups here causes severe slowdowns. + // See https://connect.microsoft.com/IE/feedback/details/1736512/ + rnoInnerhtml = /\s*$/g; + +// Prefer a tbody over its parent table for containing new rows +function manipulationTarget( elem, content ) { + if ( nodeName( elem, "table" ) && + nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { + + return jQuery( elem ).children( "tbody" )[ 0 ] || elem; + } + + return elem; +} + +// Replace/restore the type attribute of script elements for safe DOM manipulation +function disableScript( elem ) { + elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; + return elem; +} +function restoreScript( elem ) { + if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { + elem.type = elem.type.slice( 5 ); + } else { + elem.removeAttribute( "type" ); + } + + return elem; +} + +function cloneCopyEvent( src, dest ) { + var i, l, type, pdataOld, udataOld, udataCur, events; + + if ( dest.nodeType !== 1 ) { + return; + } + + // 1. Copy private data: events, handlers, etc. + if ( dataPriv.hasData( src ) ) { + pdataOld = dataPriv.get( src ); + events = pdataOld.events; + + if ( events ) { + dataPriv.remove( dest, "handle events" ); + + for ( type in events ) { + for ( i = 0, l = events[ type ].length; i < l; i++ ) { + jQuery.event.add( dest, type, events[ type ][ i ] ); + } + } + } + } + + // 2. Copy user data + if ( dataUser.hasData( src ) ) { + udataOld = dataUser.access( src ); + udataCur = jQuery.extend( {}, udataOld ); + + dataUser.set( dest, udataCur ); + } +} + +// Fix IE bugs, see support tests +function fixInput( src, dest ) { + var nodeName = dest.nodeName.toLowerCase(); + + // Fails to persist the checked state of a cloned checkbox or radio button. + if ( nodeName === "input" && rcheckableType.test( src.type ) ) { + dest.checked = src.checked; + + // Fails to return the selected option to the default selected state when cloning options + } else if ( nodeName === "input" || nodeName === "textarea" ) { + dest.defaultValue = src.defaultValue; + } +} + +function domManip( collection, args, callback, ignored ) { + + // Flatten any nested arrays + args = flat( args ); + + var fragment, first, scripts, hasScripts, node, doc, + i = 0, + l = collection.length, + iNoClone = l - 1, + value = args[ 0 ], + valueIsFunction = isFunction( value ); + + // We can't cloneNode fragments that contain checked, in WebKit + if ( valueIsFunction || + ( l > 1 && typeof value === "string" && + !support.checkClone && rchecked.test( value ) ) ) { + return collection.each( function( index ) { + var self = collection.eq( index ); + if ( valueIsFunction ) { + args[ 0 ] = value.call( this, index, self.html() ); + } + domManip( self, args, callback, ignored ); + } ); + } + + if ( l ) { + fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); + first = fragment.firstChild; + + if ( fragment.childNodes.length === 1 ) { + fragment = first; + } + + // Require either new content or an interest in ignored elements to invoke the callback + if ( first || ignored ) { + scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); + hasScripts = scripts.length; + + // Use the original fragment for the last item + // instead of the first because it can end up + // being emptied incorrectly in certain situations (#8070). + for ( ; i < l; i++ ) { + node = fragment; + + if ( i !== iNoClone ) { + node = jQuery.clone( node, true, true ); + + // Keep references to cloned scripts for later restoration + if ( hasScripts ) { + + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit + jQuery.merge( scripts, getAll( node, "script" ) ); + } + } + + callback.call( collection[ i ], node, i ); + } + + if ( hasScripts ) { + doc = scripts[ scripts.length - 1 ].ownerDocument; + + // Reenable scripts + jQuery.map( scripts, restoreScript ); + + // Evaluate executable scripts on first document insertion + for ( i = 0; i < hasScripts; i++ ) { + node = scripts[ i ]; + if ( rscriptType.test( node.type || "" ) && + !dataPriv.access( node, "globalEval" ) && + jQuery.contains( doc, node ) ) { + + if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { + + // Optional AJAX dependency, but won't run scripts if not present + if ( jQuery._evalUrl && !node.noModule ) { + jQuery._evalUrl( node.src, { + nonce: node.nonce || node.getAttribute( "nonce" ) + }, doc ); + } + } else { + DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); + } + } + } + } + } + } + + return collection; +} + +function remove( elem, selector, keepData ) { + var node, + nodes = selector ? jQuery.filter( selector, elem ) : elem, + i = 0; + + for ( ; ( node = nodes[ i ] ) != null; i++ ) { + if ( !keepData && node.nodeType === 1 ) { + jQuery.cleanData( getAll( node ) ); + } + + if ( node.parentNode ) { + if ( keepData && isAttached( node ) ) { + setGlobalEval( getAll( node, "script" ) ); + } + node.parentNode.removeChild( node ); + } + } + + return elem; +} + +jQuery.extend( { + htmlPrefilter: function( html ) { + return html; + }, + + clone: function( elem, dataAndEvents, deepDataAndEvents ) { + var i, l, srcElements, destElements, + clone = elem.cloneNode( true ), + inPage = isAttached( elem ); + + // Fix IE cloning issues + if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && + !jQuery.isXMLDoc( elem ) ) { + + // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 + destElements = getAll( clone ); + srcElements = getAll( elem ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + fixInput( srcElements[ i ], destElements[ i ] ); + } + } + + // Copy the events from the original to the clone + if ( dataAndEvents ) { + if ( deepDataAndEvents ) { + srcElements = srcElements || getAll( elem ); + destElements = destElements || getAll( clone ); + + for ( i = 0, l = srcElements.length; i < l; i++ ) { + cloneCopyEvent( srcElements[ i ], destElements[ i ] ); + } + } else { + cloneCopyEvent( elem, clone ); + } + } + + // Preserve script evaluation history + destElements = getAll( clone, "script" ); + if ( destElements.length > 0 ) { + setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); + } + + // Return the cloned set + return clone; + }, + + cleanData: function( elems ) { + var data, elem, type, + special = jQuery.event.special, + i = 0; + + for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { + if ( acceptData( elem ) ) { + if ( ( data = elem[ dataPriv.expando ] ) ) { + if ( data.events ) { + for ( type in data.events ) { + if ( special[ type ] ) { + jQuery.event.remove( elem, type ); + + // This is a shortcut to avoid jQuery.event.remove's overhead + } else { + jQuery.removeEvent( elem, type, data.handle ); + } + } + } + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataPriv.expando ] = undefined; + } + if ( elem[ dataUser.expando ] ) { + + // Support: Chrome <=35 - 45+ + // Assign undefined instead of using delete, see Data#remove + elem[ dataUser.expando ] = undefined; + } + } + } + } +} ); + +jQuery.fn.extend( { + detach: function( selector ) { + return remove( this, selector, true ); + }, + + remove: function( selector ) { + return remove( this, selector ); + }, + + text: function( value ) { + return access( this, function( value ) { + return value === undefined ? + jQuery.text( this ) : + this.empty().each( function() { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + this.textContent = value; + } + } ); + }, null, value, arguments.length ); + }, + + append: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.appendChild( elem ); + } + } ); + }, + + prepend: function() { + return domManip( this, arguments, function( elem ) { + if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { + var target = manipulationTarget( this, elem ); + target.insertBefore( elem, target.firstChild ); + } + } ); + }, + + before: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this ); + } + } ); + }, + + after: function() { + return domManip( this, arguments, function( elem ) { + if ( this.parentNode ) { + this.parentNode.insertBefore( elem, this.nextSibling ); + } + } ); + }, + + empty: function() { + var elem, + i = 0; + + for ( ; ( elem = this[ i ] ) != null; i++ ) { + if ( elem.nodeType === 1 ) { + + // Prevent memory leaks + jQuery.cleanData( getAll( elem, false ) ); + + // Remove any remaining nodes + elem.textContent = ""; + } + } + + return this; + }, + + clone: function( dataAndEvents, deepDataAndEvents ) { + dataAndEvents = dataAndEvents == null ? false : dataAndEvents; + deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; + + return this.map( function() { + return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); + } ); + }, + + html: function( value ) { + return access( this, function( value ) { + var elem = this[ 0 ] || {}, + i = 0, + l = this.length; + + if ( value === undefined && elem.nodeType === 1 ) { + return elem.innerHTML; + } + + // See if we can take a shortcut and just use innerHTML + if ( typeof value === "string" && !rnoInnerhtml.test( value ) && + !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { + + value = jQuery.htmlPrefilter( value ); + + try { + for ( ; i < l; i++ ) { + elem = this[ i ] || {}; + + // Remove element nodes and prevent memory leaks + if ( elem.nodeType === 1 ) { + jQuery.cleanData( getAll( elem, false ) ); + elem.innerHTML = value; + } + } + + elem = 0; + + // If using innerHTML throws an exception, use the fallback method + } catch ( e ) {} + } + + if ( elem ) { + this.empty().append( value ); + } + }, null, value, arguments.length ); + }, + + replaceWith: function() { + var ignored = []; + + // Make the changes, replacing each non-ignored context element with the new content + return domManip( this, arguments, function( elem ) { + var parent = this.parentNode; + + if ( jQuery.inArray( this, ignored ) < 0 ) { + jQuery.cleanData( getAll( this ) ); + if ( parent ) { + parent.replaceChild( elem, this ); + } + } + + // Force callback invocation + }, ignored ); + } +} ); + +jQuery.each( { + appendTo: "append", + prependTo: "prepend", + insertBefore: "before", + insertAfter: "after", + replaceAll: "replaceWith" +}, function( name, original ) { + jQuery.fn[ name ] = function( selector ) { + var elems, + ret = [], + insert = jQuery( selector ), + last = insert.length - 1, + i = 0; + + for ( ; i <= last; i++ ) { + elems = i === last ? this : this.clone( true ); + jQuery( insert[ i ] )[ original ]( elems ); + + // Support: Android <=4.0 only, PhantomJS 1 only + // .get() because push.apply(_, arraylike) throws on ancient WebKit + push.apply( ret, elems.get() ); + } + + return this.pushStack( ret ); + }; +} ); +var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); + +var getStyles = function( elem ) { + + // Support: IE <=11 only, Firefox <=30 (#15098, #14150) + // IE throws on elements created in popups + // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" + var view = elem.ownerDocument.defaultView; + + if ( !view || !view.opener ) { + view = window; + } + + return view.getComputedStyle( elem ); + }; + +var swap = function( elem, options, callback ) { + var ret, name, + old = {}; + + // Remember the old values, and insert the new ones + for ( name in options ) { + old[ name ] = elem.style[ name ]; + elem.style[ name ] = options[ name ]; + } + + ret = callback.call( elem ); + + // Revert the old values + for ( name in options ) { + elem.style[ name ] = old[ name ]; + } + + return ret; +}; + + +var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); + + + +( function() { + + // Executing both pixelPosition & boxSizingReliable tests require only one layout + // so they're executed at the same time to save the second computation. + function computeStyleTests() { + + // This is a singleton, we need to execute it only once + if ( !div ) { + return; + } + + container.style.cssText = "position:absolute;left:-11111px;width:60px;" + + "margin-top:1px;padding:0;border:0"; + div.style.cssText = + "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + + "margin:auto;border:1px;padding:1px;" + + "width:60%;top:1%"; + documentElement.appendChild( container ).appendChild( div ); + + var divStyle = window.getComputedStyle( div ); + pixelPositionVal = divStyle.top !== "1%"; + + // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 + reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; + + // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 + // Some styles come back with percentage values, even though they shouldn't + div.style.right = "60%"; + pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; + + // Support: IE 9 - 11 only + // Detect misreporting of content dimensions for box-sizing:border-box elements + boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; + + // Support: IE 9 only + // Detect overflow:scroll screwiness (gh-3699) + // Support: Chrome <=64 + // Don't get tricked when zoom affects offsetWidth (gh-4029) + div.style.position = "absolute"; + scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; + + documentElement.removeChild( container ); + + // Nullify the div so it wouldn't be stored in the memory and + // it will also be a sign that checks already performed + div = null; + } + + function roundPixelMeasures( measure ) { + return Math.round( parseFloat( measure ) ); + } + + var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, + reliableTrDimensionsVal, reliableMarginLeftVal, + container = document.createElement( "div" ), + div = document.createElement( "div" ); + + // Finish early in limited (non-browser) environments + if ( !div.style ) { + return; + } + + // Support: IE <=9 - 11 only + // Style of cloned element affects source element cloned (#8908) + div.style.backgroundClip = "content-box"; + div.cloneNode( true ).style.backgroundClip = ""; + support.clearCloneStyle = div.style.backgroundClip === "content-box"; + + jQuery.extend( support, { + boxSizingReliable: function() { + computeStyleTests(); + return boxSizingReliableVal; + }, + pixelBoxStyles: function() { + computeStyleTests(); + return pixelBoxStylesVal; + }, + pixelPosition: function() { + computeStyleTests(); + return pixelPositionVal; + }, + reliableMarginLeft: function() { + computeStyleTests(); + return reliableMarginLeftVal; + }, + scrollboxSize: function() { + computeStyleTests(); + return scrollboxSizeVal; + }, + + // Support: IE 9 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Behavior in IE 9 is more subtle than in newer versions & it passes + // some versions of this test; make sure not to make it pass there! + reliableTrDimensions: function() { + var table, tr, trChild, trStyle; + if ( reliableTrDimensionsVal == null ) { + table = document.createElement( "table" ); + tr = document.createElement( "tr" ); + trChild = document.createElement( "div" ); + + table.style.cssText = "position:absolute;left:-11111px"; + tr.style.height = "1px"; + trChild.style.height = "9px"; + + documentElement + .appendChild( table ) + .appendChild( tr ) + .appendChild( trChild ); + + trStyle = window.getComputedStyle( tr ); + reliableTrDimensionsVal = parseInt( trStyle.height ) > 3; + + documentElement.removeChild( table ); + } + return reliableTrDimensionsVal; + } + } ); +} )(); + + +function curCSS( elem, name, computed ) { + var width, minWidth, maxWidth, ret, + + // Support: Firefox 51+ + // Retrieving style before computed somehow + // fixes an issue with getting wrong values + // on detached elements + style = elem.style; + + computed = computed || getStyles( elem ); + + // getPropertyValue is needed for: + // .css('filter') (IE 9 only, #12537) + // .css('--customProperty) (#3144) + if ( computed ) { + ret = computed.getPropertyValue( name ) || computed[ name ]; + + if ( ret === "" && !isAttached( elem ) ) { + ret = jQuery.style( elem, name ); + } + + // A tribute to the "awesome hack by Dean Edwards" + // Android Browser returns percentage for some values, + // but width seems to be reliably pixels. + // This is against the CSSOM draft spec: + // https://drafts.csswg.org/cssom/#resolved-values + if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { + + // Remember the original values + width = style.width; + minWidth = style.minWidth; + maxWidth = style.maxWidth; + + // Put in the new values to get a computed value out + style.minWidth = style.maxWidth = style.width = ret; + ret = computed.width; + + // Revert the changed values + style.width = width; + style.minWidth = minWidth; + style.maxWidth = maxWidth; + } + } + + return ret !== undefined ? + + // Support: IE <=9 - 11 only + // IE returns zIndex value as an integer. + ret + "" : + ret; +} + + +function addGetHookIf( conditionFn, hookFn ) { + + // Define the hook, we'll check on the first run if it's really needed. + return { + get: function() { + if ( conditionFn() ) { + + // Hook not needed (or it's not possible to use it due + // to missing dependency), remove it. + delete this.get; + return; + } + + // Hook needed; redefine it so that the support test is not executed again. + return ( this.get = hookFn ).apply( this, arguments ); + } + }; +} + + +var cssPrefixes = [ "Webkit", "Moz", "ms" ], + emptyStyle = document.createElement( "div" ).style, + vendorProps = {}; + +// Return a vendor-prefixed property or undefined +function vendorPropName( name ) { + + // Check for vendor prefixed names + var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), + i = cssPrefixes.length; + + while ( i-- ) { + name = cssPrefixes[ i ] + capName; + if ( name in emptyStyle ) { + return name; + } + } +} + +// Return a potentially-mapped jQuery.cssProps or vendor prefixed property +function finalPropName( name ) { + var final = jQuery.cssProps[ name ] || vendorProps[ name ]; + + if ( final ) { + return final; + } + if ( name in emptyStyle ) { + return name; + } + return vendorProps[ name ] = vendorPropName( name ) || name; +} + + +var + + // Swappable if display is none or starts with table + // except "table", "table-cell", or "table-caption" + // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display + rdisplayswap = /^(none|table(?!-c[ea]).+)/, + rcustomProp = /^--/, + cssShow = { position: "absolute", visibility: "hidden", display: "block" }, + cssNormalTransform = { + letterSpacing: "0", + fontWeight: "400" + }; + +function setPositiveNumber( _elem, value, subtract ) { + + // Any relative (+/-) values have already been + // normalized at this point + var matches = rcssNum.exec( value ); + return matches ? + + // Guard against undefined "subtract", e.g., when used as in cssHooks + Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : + value; +} + +function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { + var i = dimension === "width" ? 1 : 0, + extra = 0, + delta = 0; + + // Adjustment may not be necessary + if ( box === ( isBorderBox ? "border" : "content" ) ) { + return 0; + } + + for ( ; i < 4; i += 2 ) { + + // Both box models exclude margin + if ( box === "margin" ) { + delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); + } + + // If we get here with a content-box, we're seeking "padding" or "border" or "margin" + if ( !isBorderBox ) { + + // Add padding + delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + + // For "border" or "margin", add border + if ( box !== "padding" ) { + delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + + // But still keep track of it otherwise + } else { + extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + + // If we get here with a border-box (content + padding + border), we're seeking "content" or + // "padding" or "margin" + } else { + + // For "content", subtract padding + if ( box === "content" ) { + delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); + } + + // For "content" or "padding", subtract border + if ( box !== "margin" ) { + delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); + } + } + } + + // Account for positive content-box scroll gutter when requested by providing computedVal + if ( !isBorderBox && computedVal >= 0 ) { + + // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border + // Assuming integer scroll gutter, subtract the rest and round down + delta += Math.max( 0, Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + computedVal - + delta - + extra - + 0.5 + + // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter + // Use an explicit zero to avoid NaN (gh-3964) + ) ) || 0; + } + + return delta; +} + +function getWidthOrHeight( elem, dimension, extra ) { + + // Start with computed style + var styles = getStyles( elem ), + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). + // Fake content-box until we know it's needed to know the true value. + boxSizingNeeded = !support.boxSizingReliable() || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + valueIsBorderBox = isBorderBox, + + val = curCSS( elem, dimension, styles ), + offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); + + // Support: Firefox <=54 + // Return a confounding non-pixel value or feign ignorance, as appropriate. + if ( rnumnonpx.test( val ) ) { + if ( !extra ) { + return val; + } + val = "auto"; + } + + + // Support: IE 9 - 11 only + // Use offsetWidth/offsetHeight for when box sizing is unreliable. + // In those cases, the computed value can be trusted to be border-box. + if ( ( !support.boxSizingReliable() && isBorderBox || + + // Support: IE 10 - 11+, Edge 15 - 18+ + // IE/Edge misreport `getComputedStyle` of table rows with width/height + // set in CSS while `offset*` properties report correct values. + // Interestingly, in some cases IE 9 doesn't suffer from this issue. + !support.reliableTrDimensions() && nodeName( elem, "tr" ) || + + // Fall back to offsetWidth/offsetHeight when value is "auto" + // This happens for inline elements with no explicit setting (gh-3571) + val === "auto" || + + // Support: Android <=4.1 - 4.3 only + // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) + !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && + + // Make sure the element is visible & connected + elem.getClientRects().length ) { + + isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; + + // Where available, offsetWidth/offsetHeight approximate border box dimensions. + // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the + // retrieved value as a content box dimension. + valueIsBorderBox = offsetProp in elem; + if ( valueIsBorderBox ) { + val = elem[ offsetProp ]; + } + } + + // Normalize "" and auto + val = parseFloat( val ) || 0; + + // Adjust for the element's box model + return ( val + + boxModelAdjustment( + elem, + dimension, + extra || ( isBorderBox ? "border" : "content" ), + valueIsBorderBox, + styles, + + // Provide the current computed size to request scroll gutter calculation (gh-3589) + val + ) + ) + "px"; +} + +jQuery.extend( { + + // Add in style property hooks for overriding the default + // behavior of getting and setting a style property + cssHooks: { + opacity: { + get: function( elem, computed ) { + if ( computed ) { + + // We should always get a number back from opacity + var ret = curCSS( elem, "opacity" ); + return ret === "" ? "1" : ret; + } + } + } + }, + + // Don't automatically add "px" to these possibly-unitless properties + cssNumber: { + "animationIterationCount": true, + "columnCount": true, + "fillOpacity": true, + "flexGrow": true, + "flexShrink": true, + "fontWeight": true, + "gridArea": true, + "gridColumn": true, + "gridColumnEnd": true, + "gridColumnStart": true, + "gridRow": true, + "gridRowEnd": true, + "gridRowStart": true, + "lineHeight": true, + "opacity": true, + "order": true, + "orphans": true, + "widows": true, + "zIndex": true, + "zoom": true + }, + + // Add in properties whose names you wish to fix before + // setting or getting the value + cssProps: {}, + + // Get and set the style property on a DOM Node + style: function( elem, name, value, extra ) { + + // Don't set styles on text and comment nodes + if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { + return; + } + + // Make sure that we're working with the right name + var ret, type, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ), + style = elem.style; + + // Make sure that we're working with the right name. We don't + // want to query the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Gets hook for the prefixed version, then unprefixed version + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // Check if we're setting a value + if ( value !== undefined ) { + type = typeof value; + + // Convert "+=" or "-=" to relative numbers (#7345) + if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { + value = adjustCSS( elem, name, ret ); + + // Fixes bug #9237 + type = "number"; + } + + // Make sure that null and NaN values aren't set (#7116) + if ( value == null || value !== value ) { + return; + } + + // If a number was passed in, add the unit (except for certain CSS properties) + // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append + // "px" to a few hardcoded values. + if ( type === "number" && !isCustomProp ) { + value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); + } + + // background-* props affect original clone's values + if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { + style[ name ] = "inherit"; + } + + // If a hook was provided, use that value, otherwise just set the specified value + if ( !hooks || !( "set" in hooks ) || + ( value = hooks.set( elem, value, extra ) ) !== undefined ) { + + if ( isCustomProp ) { + style.setProperty( name, value ); + } else { + style[ name ] = value; + } + } + + } else { + + // If a hook was provided get the non-computed value from there + if ( hooks && "get" in hooks && + ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { + + return ret; + } + + // Otherwise just get the value from the style object + return style[ name ]; + } + }, + + css: function( elem, name, extra, styles ) { + var val, num, hooks, + origName = camelCase( name ), + isCustomProp = rcustomProp.test( name ); + + // Make sure that we're working with the right name. We don't + // want to modify the value if it is a CSS custom property + // since they are user-defined. + if ( !isCustomProp ) { + name = finalPropName( origName ); + } + + // Try prefixed name followed by the unprefixed name + hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; + + // If a hook was provided get the computed value from there + if ( hooks && "get" in hooks ) { + val = hooks.get( elem, true, extra ); + } + + // Otherwise, if a way to get the computed value exists, use that + if ( val === undefined ) { + val = curCSS( elem, name, styles ); + } + + // Convert "normal" to computed value + if ( val === "normal" && name in cssNormalTransform ) { + val = cssNormalTransform[ name ]; + } + + // Make numeric if forced or a qualifier was provided and val looks numeric + if ( extra === "" || extra ) { + num = parseFloat( val ); + return extra === true || isFinite( num ) ? num || 0 : val; + } + + return val; + } +} ); + +jQuery.each( [ "height", "width" ], function( _i, dimension ) { + jQuery.cssHooks[ dimension ] = { + get: function( elem, computed, extra ) { + if ( computed ) { + + // Certain elements can have dimension info if we invisibly show them + // but it must have a current display style that would benefit + return rdisplayswap.test( jQuery.css( elem, "display" ) ) && + + // Support: Safari 8+ + // Table columns in Safari have non-zero offsetWidth & zero + // getBoundingClientRect().width unless display is changed. + // Support: IE <=11 only + // Running getBoundingClientRect on a disconnected node + // in IE throws an error. + ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? + swap( elem, cssShow, function() { + return getWidthOrHeight( elem, dimension, extra ); + } ) : + getWidthOrHeight( elem, dimension, extra ); + } + }, + + set: function( elem, value, extra ) { + var matches, + styles = getStyles( elem ), + + // Only read styles.position if the test has a chance to fail + // to avoid forcing a reflow. + scrollboxSizeBuggy = !support.scrollboxSize() && + styles.position === "absolute", + + // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) + boxSizingNeeded = scrollboxSizeBuggy || extra, + isBorderBox = boxSizingNeeded && + jQuery.css( elem, "boxSizing", false, styles ) === "border-box", + subtract = extra ? + boxModelAdjustment( + elem, + dimension, + extra, + isBorderBox, + styles + ) : + 0; + + // Account for unreliable border-box dimensions by comparing offset* to computed and + // faking a content-box to get border and padding (gh-3699) + if ( isBorderBox && scrollboxSizeBuggy ) { + subtract -= Math.ceil( + elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - + parseFloat( styles[ dimension ] ) - + boxModelAdjustment( elem, dimension, "border", false, styles ) - + 0.5 + ); + } + + // Convert to pixels if value adjustment is needed + if ( subtract && ( matches = rcssNum.exec( value ) ) && + ( matches[ 3 ] || "px" ) !== "px" ) { + + elem.style[ dimension ] = value; + value = jQuery.css( elem, dimension ); + } + + return setPositiveNumber( elem, value, subtract ); + } + }; +} ); + +jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, + function( elem, computed ) { + if ( computed ) { + return ( parseFloat( curCSS( elem, "marginLeft" ) ) || + elem.getBoundingClientRect().left - + swap( elem, { marginLeft: 0 }, function() { + return elem.getBoundingClientRect().left; + } ) + ) + "px"; + } + } +); + +// These hooks are used by animate to expand properties +jQuery.each( { + margin: "", + padding: "", + border: "Width" +}, function( prefix, suffix ) { + jQuery.cssHooks[ prefix + suffix ] = { + expand: function( value ) { + var i = 0, + expanded = {}, + + // Assumes a single number if not a string + parts = typeof value === "string" ? value.split( " " ) : [ value ]; + + for ( ; i < 4; i++ ) { + expanded[ prefix + cssExpand[ i ] + suffix ] = + parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; + } + + return expanded; + } + }; + + if ( prefix !== "margin" ) { + jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; + } +} ); + +jQuery.fn.extend( { + css: function( name, value ) { + return access( this, function( elem, name, value ) { + var styles, len, + map = {}, + i = 0; + + if ( Array.isArray( name ) ) { + styles = getStyles( elem ); + len = name.length; + + for ( ; i < len; i++ ) { + map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); + } + + return map; + } + + return value !== undefined ? + jQuery.style( elem, name, value ) : + jQuery.css( elem, name ); + }, name, value, arguments.length > 1 ); + } +} ); + + +function Tween( elem, options, prop, end, easing ) { + return new Tween.prototype.init( elem, options, prop, end, easing ); +} +jQuery.Tween = Tween; + +Tween.prototype = { + constructor: Tween, + init: function( elem, options, prop, end, easing, unit ) { + this.elem = elem; + this.prop = prop; + this.easing = easing || jQuery.easing._default; + this.options = options; + this.start = this.now = this.cur(); + this.end = end; + this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); + }, + cur: function() { + var hooks = Tween.propHooks[ this.prop ]; + + return hooks && hooks.get ? + hooks.get( this ) : + Tween.propHooks._default.get( this ); + }, + run: function( percent ) { + var eased, + hooks = Tween.propHooks[ this.prop ]; + + if ( this.options.duration ) { + this.pos = eased = jQuery.easing[ this.easing ]( + percent, this.options.duration * percent, 0, 1, this.options.duration + ); + } else { + this.pos = eased = percent; + } + this.now = ( this.end - this.start ) * eased + this.start; + + if ( this.options.step ) { + this.options.step.call( this.elem, this.now, this ); + } + + if ( hooks && hooks.set ) { + hooks.set( this ); + } else { + Tween.propHooks._default.set( this ); + } + return this; + } +}; + +Tween.prototype.init.prototype = Tween.prototype; + +Tween.propHooks = { + _default: { + get: function( tween ) { + var result; + + // Use a property on the element directly when it is not a DOM element, + // or when there is no matching style property that exists. + if ( tween.elem.nodeType !== 1 || + tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { + return tween.elem[ tween.prop ]; + } + + // Passing an empty string as a 3rd parameter to .css will automatically + // attempt a parseFloat and fallback to a string if the parse fails. + // Simple values such as "10px" are parsed to Float; + // complex values such as "rotate(1rad)" are returned as-is. + result = jQuery.css( tween.elem, tween.prop, "" ); + + // Empty strings, null, undefined and "auto" are converted to 0. + return !result || result === "auto" ? 0 : result; + }, + set: function( tween ) { + + // Use step hook for back compat. + // Use cssHook if its there. + // Use .style if available and use plain properties where available. + if ( jQuery.fx.step[ tween.prop ] ) { + jQuery.fx.step[ tween.prop ]( tween ); + } else if ( tween.elem.nodeType === 1 && ( + jQuery.cssHooks[ tween.prop ] || + tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { + jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); + } else { + tween.elem[ tween.prop ] = tween.now; + } + } + } +}; + +// Support: IE <=9 only +// Panic based approach to setting things on disconnected nodes +Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { + set: function( tween ) { + if ( tween.elem.nodeType && tween.elem.parentNode ) { + tween.elem[ tween.prop ] = tween.now; + } + } +}; + +jQuery.easing = { + linear: function( p ) { + return p; + }, + swing: function( p ) { + return 0.5 - Math.cos( p * Math.PI ) / 2; + }, + _default: "swing" +}; + +jQuery.fx = Tween.prototype.init; + +// Back compat <1.8 extension point +jQuery.fx.step = {}; + + + + +var + fxNow, inProgress, + rfxtypes = /^(?:toggle|show|hide)$/, + rrun = /queueHooks$/; + +function schedule() { + if ( inProgress ) { + if ( document.hidden === false && window.requestAnimationFrame ) { + window.requestAnimationFrame( schedule ); + } else { + window.setTimeout( schedule, jQuery.fx.interval ); + } + + jQuery.fx.tick(); + } +} + +// Animations created synchronously will run synchronously +function createFxNow() { + window.setTimeout( function() { + fxNow = undefined; + } ); + return ( fxNow = Date.now() ); +} + +// Generate parameters to create a standard animation +function genFx( type, includeWidth ) { + var which, + i = 0, + attrs = { height: type }; + + // If we include width, step value is 1 to do all cssExpand values, + // otherwise step value is 2 to skip over Left and Right + includeWidth = includeWidth ? 1 : 0; + for ( ; i < 4; i += 2 - includeWidth ) { + which = cssExpand[ i ]; + attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; + } + + if ( includeWidth ) { + attrs.opacity = attrs.width = type; + } + + return attrs; +} + +function createTween( value, prop, animation ) { + var tween, + collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), + index = 0, + length = collection.length; + for ( ; index < length; index++ ) { + if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { + + // We're done with this property + return tween; + } + } +} + +function defaultPrefilter( elem, props, opts ) { + var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, + isBox = "width" in props || "height" in props, + anim = this, + orig = {}, + style = elem.style, + hidden = elem.nodeType && isHiddenWithinTree( elem ), + dataShow = dataPriv.get( elem, "fxshow" ); + + // Queue-skipping animations hijack the fx hooks + if ( !opts.queue ) { + hooks = jQuery._queueHooks( elem, "fx" ); + if ( hooks.unqueued == null ) { + hooks.unqueued = 0; + oldfire = hooks.empty.fire; + hooks.empty.fire = function() { + if ( !hooks.unqueued ) { + oldfire(); + } + }; + } + hooks.unqueued++; + + anim.always( function() { + + // Ensure the complete handler is called before this completes + anim.always( function() { + hooks.unqueued--; + if ( !jQuery.queue( elem, "fx" ).length ) { + hooks.empty.fire(); + } + } ); + } ); + } + + // Detect show/hide animations + for ( prop in props ) { + value = props[ prop ]; + if ( rfxtypes.test( value ) ) { + delete props[ prop ]; + toggle = toggle || value === "toggle"; + if ( value === ( hidden ? "hide" : "show" ) ) { + + // Pretend to be hidden if this is a "show" and + // there is still data from a stopped show/hide + if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { + hidden = true; + + // Ignore all other no-op show/hide data + } else { + continue; + } + } + orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); + } + } + + // Bail out if this is a no-op like .hide().hide() + propTween = !jQuery.isEmptyObject( props ); + if ( !propTween && jQuery.isEmptyObject( orig ) ) { + return; + } + + // Restrict "overflow" and "display" styles during box animations + if ( isBox && elem.nodeType === 1 ) { + + // Support: IE <=9 - 11, Edge 12 - 15 + // Record all 3 overflow attributes because IE does not infer the shorthand + // from identically-valued overflowX and overflowY and Edge just mirrors + // the overflowX value there. + opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; + + // Identify a display type, preferring old show/hide data over the CSS cascade + restoreDisplay = dataShow && dataShow.display; + if ( restoreDisplay == null ) { + restoreDisplay = dataPriv.get( elem, "display" ); + } + display = jQuery.css( elem, "display" ); + if ( display === "none" ) { + if ( restoreDisplay ) { + display = restoreDisplay; + } else { + + // Get nonempty value(s) by temporarily forcing visibility + showHide( [ elem ], true ); + restoreDisplay = elem.style.display || restoreDisplay; + display = jQuery.css( elem, "display" ); + showHide( [ elem ] ); + } + } + + // Animate inline elements as inline-block + if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { + if ( jQuery.css( elem, "float" ) === "none" ) { + + // Restore the original display value at the end of pure show/hide animations + if ( !propTween ) { + anim.done( function() { + style.display = restoreDisplay; + } ); + if ( restoreDisplay == null ) { + display = style.display; + restoreDisplay = display === "none" ? "" : display; + } + } + style.display = "inline-block"; + } + } + } + + if ( opts.overflow ) { + style.overflow = "hidden"; + anim.always( function() { + style.overflow = opts.overflow[ 0 ]; + style.overflowX = opts.overflow[ 1 ]; + style.overflowY = opts.overflow[ 2 ]; + } ); + } + + // Implement show/hide animations + propTween = false; + for ( prop in orig ) { + + // General show/hide setup for this element animation + if ( !propTween ) { + if ( dataShow ) { + if ( "hidden" in dataShow ) { + hidden = dataShow.hidden; + } + } else { + dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); + } + + // Store hidden/visible for toggle so `.stop().toggle()` "reverses" + if ( toggle ) { + dataShow.hidden = !hidden; + } + + // Show elements before animating them + if ( hidden ) { + showHide( [ elem ], true ); + } + + /* eslint-disable no-loop-func */ + + anim.done( function() { + + /* eslint-enable no-loop-func */ + + // The final step of a "hide" animation is actually hiding the element + if ( !hidden ) { + showHide( [ elem ] ); + } + dataPriv.remove( elem, "fxshow" ); + for ( prop in orig ) { + jQuery.style( elem, prop, orig[ prop ] ); + } + } ); + } + + // Per-property setup + propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); + if ( !( prop in dataShow ) ) { + dataShow[ prop ] = propTween.start; + if ( hidden ) { + propTween.end = propTween.start; + propTween.start = 0; + } + } + } +} + +function propFilter( props, specialEasing ) { + var index, name, easing, value, hooks; + + // camelCase, specialEasing and expand cssHook pass + for ( index in props ) { + name = camelCase( index ); + easing = specialEasing[ name ]; + value = props[ index ]; + if ( Array.isArray( value ) ) { + easing = value[ 1 ]; + value = props[ index ] = value[ 0 ]; + } + + if ( index !== name ) { + props[ name ] = value; + delete props[ index ]; + } + + hooks = jQuery.cssHooks[ name ]; + if ( hooks && "expand" in hooks ) { + value = hooks.expand( value ); + delete props[ name ]; + + // Not quite $.extend, this won't overwrite existing keys. + // Reusing 'index' because we have the correct "name" + for ( index in value ) { + if ( !( index in props ) ) { + props[ index ] = value[ index ]; + specialEasing[ index ] = easing; + } + } + } else { + specialEasing[ name ] = easing; + } + } +} + +function Animation( elem, properties, options ) { + var result, + stopped, + index = 0, + length = Animation.prefilters.length, + deferred = jQuery.Deferred().always( function() { + + // Don't match elem in the :animated selector + delete tick.elem; + } ), + tick = function() { + if ( stopped ) { + return false; + } + var currentTime = fxNow || createFxNow(), + remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), + + // Support: Android 2.3 only + // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) + temp = remaining / animation.duration || 0, + percent = 1 - temp, + index = 0, + length = animation.tweens.length; + + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( percent ); + } + + deferred.notifyWith( elem, [ animation, percent, remaining ] ); + + // If there's more to do, yield + if ( percent < 1 && length ) { + return remaining; + } + + // If this was an empty animation, synthesize a final progress notification + if ( !length ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + } + + // Resolve the animation and report its conclusion + deferred.resolveWith( elem, [ animation ] ); + return false; + }, + animation = deferred.promise( { + elem: elem, + props: jQuery.extend( {}, properties ), + opts: jQuery.extend( true, { + specialEasing: {}, + easing: jQuery.easing._default + }, options ), + originalProperties: properties, + originalOptions: options, + startTime: fxNow || createFxNow(), + duration: options.duration, + tweens: [], + createTween: function( prop, end ) { + var tween = jQuery.Tween( elem, animation.opts, prop, end, + animation.opts.specialEasing[ prop ] || animation.opts.easing ); + animation.tweens.push( tween ); + return tween; + }, + stop: function( gotoEnd ) { + var index = 0, + + // If we are going to the end, we want to run all the tweens + // otherwise we skip this part + length = gotoEnd ? animation.tweens.length : 0; + if ( stopped ) { + return this; + } + stopped = true; + for ( ; index < length; index++ ) { + animation.tweens[ index ].run( 1 ); + } + + // Resolve when we played the last frame; otherwise, reject + if ( gotoEnd ) { + deferred.notifyWith( elem, [ animation, 1, 0 ] ); + deferred.resolveWith( elem, [ animation, gotoEnd ] ); + } else { + deferred.rejectWith( elem, [ animation, gotoEnd ] ); + } + return this; + } + } ), + props = animation.props; + + propFilter( props, animation.opts.specialEasing ); + + for ( ; index < length; index++ ) { + result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); + if ( result ) { + if ( isFunction( result.stop ) ) { + jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = + result.stop.bind( result ); + } + return result; + } + } + + jQuery.map( props, createTween, animation ); + + if ( isFunction( animation.opts.start ) ) { + animation.opts.start.call( elem, animation ); + } + + // Attach callbacks from options + animation + .progress( animation.opts.progress ) + .done( animation.opts.done, animation.opts.complete ) + .fail( animation.opts.fail ) + .always( animation.opts.always ); + + jQuery.fx.timer( + jQuery.extend( tick, { + elem: elem, + anim: animation, + queue: animation.opts.queue + } ) + ); + + return animation; +} + +jQuery.Animation = jQuery.extend( Animation, { + + tweeners: { + "*": [ function( prop, value ) { + var tween = this.createTween( prop, value ); + adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); + return tween; + } ] + }, + + tweener: function( props, callback ) { + if ( isFunction( props ) ) { + callback = props; + props = [ "*" ]; + } else { + props = props.match( rnothtmlwhite ); + } + + var prop, + index = 0, + length = props.length; + + for ( ; index < length; index++ ) { + prop = props[ index ]; + Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; + Animation.tweeners[ prop ].unshift( callback ); + } + }, + + prefilters: [ defaultPrefilter ], + + prefilter: function( callback, prepend ) { + if ( prepend ) { + Animation.prefilters.unshift( callback ); + } else { + Animation.prefilters.push( callback ); + } + } +} ); + +jQuery.speed = function( speed, easing, fn ) { + var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { + complete: fn || !fn && easing || + isFunction( speed ) && speed, + duration: speed, + easing: fn && easing || easing && !isFunction( easing ) && easing + }; + + // Go to the end state if fx are off + if ( jQuery.fx.off ) { + opt.duration = 0; + + } else { + if ( typeof opt.duration !== "number" ) { + if ( opt.duration in jQuery.fx.speeds ) { + opt.duration = jQuery.fx.speeds[ opt.duration ]; + + } else { + opt.duration = jQuery.fx.speeds._default; + } + } + } + + // Normalize opt.queue - true/undefined/null -> "fx" + if ( opt.queue == null || opt.queue === true ) { + opt.queue = "fx"; + } + + // Queueing + opt.old = opt.complete; + + opt.complete = function() { + if ( isFunction( opt.old ) ) { + opt.old.call( this ); + } + + if ( opt.queue ) { + jQuery.dequeue( this, opt.queue ); + } + }; + + return opt; +}; + +jQuery.fn.extend( { + fadeTo: function( speed, to, easing, callback ) { + + // Show any hidden elements after setting opacity to 0 + return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() + + // Animate to the value specified + .end().animate( { opacity: to }, speed, easing, callback ); + }, + animate: function( prop, speed, easing, callback ) { + var empty = jQuery.isEmptyObject( prop ), + optall = jQuery.speed( speed, easing, callback ), + doAnimation = function() { + + // Operate on a copy of prop so per-property easing won't be lost + var anim = Animation( this, jQuery.extend( {}, prop ), optall ); + + // Empty animations, or finishing resolves immediately + if ( empty || dataPriv.get( this, "finish" ) ) { + anim.stop( true ); + } + }; + doAnimation.finish = doAnimation; + + return empty || optall.queue === false ? + this.each( doAnimation ) : + this.queue( optall.queue, doAnimation ); + }, + stop: function( type, clearQueue, gotoEnd ) { + var stopQueue = function( hooks ) { + var stop = hooks.stop; + delete hooks.stop; + stop( gotoEnd ); + }; + + if ( typeof type !== "string" ) { + gotoEnd = clearQueue; + clearQueue = type; + type = undefined; + } + if ( clearQueue ) { + this.queue( type || "fx", [] ); + } + + return this.each( function() { + var dequeue = true, + index = type != null && type + "queueHooks", + timers = jQuery.timers, + data = dataPriv.get( this ); + + if ( index ) { + if ( data[ index ] && data[ index ].stop ) { + stopQueue( data[ index ] ); + } + } else { + for ( index in data ) { + if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { + stopQueue( data[ index ] ); + } + } + } + + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && + ( type == null || timers[ index ].queue === type ) ) { + + timers[ index ].anim.stop( gotoEnd ); + dequeue = false; + timers.splice( index, 1 ); + } + } + + // Start the next in the queue if the last step wasn't forced. + // Timers currently will call their complete callbacks, which + // will dequeue but only if they were gotoEnd. + if ( dequeue || !gotoEnd ) { + jQuery.dequeue( this, type ); + } + } ); + }, + finish: function( type ) { + if ( type !== false ) { + type = type || "fx"; + } + return this.each( function() { + var index, + data = dataPriv.get( this ), + queue = data[ type + "queue" ], + hooks = data[ type + "queueHooks" ], + timers = jQuery.timers, + length = queue ? queue.length : 0; + + // Enable finishing flag on private data + data.finish = true; + + // Empty the queue first + jQuery.queue( this, type, [] ); + + if ( hooks && hooks.stop ) { + hooks.stop.call( this, true ); + } + + // Look for any active animations, and finish them + for ( index = timers.length; index--; ) { + if ( timers[ index ].elem === this && timers[ index ].queue === type ) { + timers[ index ].anim.stop( true ); + timers.splice( index, 1 ); + } + } + + // Look for any animations in the old queue and finish them + for ( index = 0; index < length; index++ ) { + if ( queue[ index ] && queue[ index ].finish ) { + queue[ index ].finish.call( this ); + } + } + + // Turn off finishing flag + delete data.finish; + } ); + } +} ); + +jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { + var cssFn = jQuery.fn[ name ]; + jQuery.fn[ name ] = function( speed, easing, callback ) { + return speed == null || typeof speed === "boolean" ? + cssFn.apply( this, arguments ) : + this.animate( genFx( name, true ), speed, easing, callback ); + }; +} ); + +// Generate shortcuts for custom animations +jQuery.each( { + slideDown: genFx( "show" ), + slideUp: genFx( "hide" ), + slideToggle: genFx( "toggle" ), + fadeIn: { opacity: "show" }, + fadeOut: { opacity: "hide" }, + fadeToggle: { opacity: "toggle" } +}, function( name, props ) { + jQuery.fn[ name ] = function( speed, easing, callback ) { + return this.animate( props, speed, easing, callback ); + }; +} ); + +jQuery.timers = []; +jQuery.fx.tick = function() { + var timer, + i = 0, + timers = jQuery.timers; + + fxNow = Date.now(); + + for ( ; i < timers.length; i++ ) { + timer = timers[ i ]; + + // Run the timer and safely remove it when done (allowing for external removal) + if ( !timer() && timers[ i ] === timer ) { + timers.splice( i--, 1 ); + } + } + + if ( !timers.length ) { + jQuery.fx.stop(); + } + fxNow = undefined; +}; + +jQuery.fx.timer = function( timer ) { + jQuery.timers.push( timer ); + jQuery.fx.start(); +}; + +jQuery.fx.interval = 13; +jQuery.fx.start = function() { + if ( inProgress ) { + return; + } + + inProgress = true; + schedule(); +}; + +jQuery.fx.stop = function() { + inProgress = null; +}; + +jQuery.fx.speeds = { + slow: 600, + fast: 200, + + // Default speed + _default: 400 +}; + + +// Based off of the plugin by Clint Helfers, with permission. +// https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ +jQuery.fn.delay = function( time, type ) { + time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; + type = type || "fx"; + + return this.queue( type, function( next, hooks ) { + var timeout = window.setTimeout( next, time ); + hooks.stop = function() { + window.clearTimeout( timeout ); + }; + } ); +}; + + +( function() { + var input = document.createElement( "input" ), + select = document.createElement( "select" ), + opt = select.appendChild( document.createElement( "option" ) ); + + input.type = "checkbox"; + + // Support: Android <=4.3 only + // Default value for a checkbox should be "on" + support.checkOn = input.value !== ""; + + // Support: IE <=11 only + // Must access selectedIndex to make default options select + support.optSelected = opt.selected; + + // Support: IE <=11 only + // An input loses its value after becoming a radio + input = document.createElement( "input" ); + input.value = "t"; + input.type = "radio"; + support.radioValue = input.value === "t"; +} )(); + + +var boolHook, + attrHandle = jQuery.expr.attrHandle; + +jQuery.fn.extend( { + attr: function( name, value ) { + return access( this, jQuery.attr, name, value, arguments.length > 1 ); + }, + + removeAttr: function( name ) { + return this.each( function() { + jQuery.removeAttr( this, name ); + } ); + } +} ); + +jQuery.extend( { + attr: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set attributes on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + // Fallback to prop when attributes are not supported + if ( typeof elem.getAttribute === "undefined" ) { + return jQuery.prop( elem, name, value ); + } + + // Attribute hooks are determined by the lowercase version + // Grab necessary hook if one is defined + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + hooks = jQuery.attrHooks[ name.toLowerCase() ] || + ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); + } + + if ( value !== undefined ) { + if ( value === null ) { + jQuery.removeAttr( elem, name ); + return; + } + + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + elem.setAttribute( name, value + "" ); + return value; + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + ret = jQuery.find.attr( elem, name ); + + // Non-existent attributes return null, we normalize to undefined + return ret == null ? undefined : ret; + }, + + attrHooks: { + type: { + set: function( elem, value ) { + if ( !support.radioValue && value === "radio" && + nodeName( elem, "input" ) ) { + var val = elem.value; + elem.setAttribute( "type", value ); + if ( val ) { + elem.value = val; + } + return value; + } + } + } + }, + + removeAttr: function( elem, value ) { + var name, + i = 0, + + // Attribute names can contain non-HTML whitespace characters + // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 + attrNames = value && value.match( rnothtmlwhite ); + + if ( attrNames && elem.nodeType === 1 ) { + while ( ( name = attrNames[ i++ ] ) ) { + elem.removeAttribute( name ); + } + } + } +} ); + +// Hooks for boolean attributes +boolHook = { + set: function( elem, value, name ) { + if ( value === false ) { + + // Remove boolean attributes when set to false + jQuery.removeAttr( elem, name ); + } else { + elem.setAttribute( name, name ); + } + return name; + } +}; + +jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { + var getter = attrHandle[ name ] || jQuery.find.attr; + + attrHandle[ name ] = function( elem, name, isXML ) { + var ret, handle, + lowercaseName = name.toLowerCase(); + + if ( !isXML ) { + + // Avoid an infinite loop by temporarily removing this function from the getter + handle = attrHandle[ lowercaseName ]; + attrHandle[ lowercaseName ] = ret; + ret = getter( elem, name, isXML ) != null ? + lowercaseName : + null; + attrHandle[ lowercaseName ] = handle; + } + return ret; + }; +} ); + + + + +var rfocusable = /^(?:input|select|textarea|button)$/i, + rclickable = /^(?:a|area)$/i; + +jQuery.fn.extend( { + prop: function( name, value ) { + return access( this, jQuery.prop, name, value, arguments.length > 1 ); + }, + + removeProp: function( name ) { + return this.each( function() { + delete this[ jQuery.propFix[ name ] || name ]; + } ); + } +} ); + +jQuery.extend( { + prop: function( elem, name, value ) { + var ret, hooks, + nType = elem.nodeType; + + // Don't get/set properties on text, comment and attribute nodes + if ( nType === 3 || nType === 8 || nType === 2 ) { + return; + } + + if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { + + // Fix name and attach hooks + name = jQuery.propFix[ name ] || name; + hooks = jQuery.propHooks[ name ]; + } + + if ( value !== undefined ) { + if ( hooks && "set" in hooks && + ( ret = hooks.set( elem, value, name ) ) !== undefined ) { + return ret; + } + + return ( elem[ name ] = value ); + } + + if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { + return ret; + } + + return elem[ name ]; + }, + + propHooks: { + tabIndex: { + get: function( elem ) { + + // Support: IE <=9 - 11 only + // elem.tabIndex doesn't always return the + // correct value when it hasn't been explicitly set + // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ + // Use proper attribute retrieval(#12072) + var tabindex = jQuery.find.attr( elem, "tabindex" ); + + if ( tabindex ) { + return parseInt( tabindex, 10 ); + } + + if ( + rfocusable.test( elem.nodeName ) || + rclickable.test( elem.nodeName ) && + elem.href + ) { + return 0; + } + + return -1; + } + } + }, + + propFix: { + "for": "htmlFor", + "class": "className" + } +} ); + +// Support: IE <=11 only +// Accessing the selectedIndex property +// forces the browser to respect setting selected +// on the option +// The getter ensures a default option is selected +// when in an optgroup +// eslint rule "no-unused-expressions" is disabled for this code +// since it considers such accessions noop +if ( !support.optSelected ) { + jQuery.propHooks.selected = { + get: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent && parent.parentNode ) { + parent.parentNode.selectedIndex; + } + return null; + }, + set: function( elem ) { + + /* eslint no-unused-expressions: "off" */ + + var parent = elem.parentNode; + if ( parent ) { + parent.selectedIndex; + + if ( parent.parentNode ) { + parent.parentNode.selectedIndex; + } + } + } + }; +} + +jQuery.each( [ + "tabIndex", + "readOnly", + "maxLength", + "cellSpacing", + "cellPadding", + "rowSpan", + "colSpan", + "useMap", + "frameBorder", + "contentEditable" +], function() { + jQuery.propFix[ this.toLowerCase() ] = this; +} ); + + + + + // Strip and collapse whitespace according to HTML spec + // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace + function stripAndCollapse( value ) { + var tokens = value.match( rnothtmlwhite ) || []; + return tokens.join( " " ); + } + + +function getClass( elem ) { + return elem.getAttribute && elem.getAttribute( "class" ) || ""; +} + +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + +jQuery.fn.extend( { + addClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + if ( cur.indexOf( " " + clazz + " " ) < 0 ) { + cur += clazz + " "; + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + removeClass: function( value ) { + var classes, elem, cur, curValue, clazz, j, finalValue, + i = 0; + + if ( isFunction( value ) ) { + return this.each( function( j ) { + jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); + } ); + } + + if ( !arguments.length ) { + return this.attr( "class", "" ); + } + + classes = classesToArray( value ); + + if ( classes.length ) { + while ( ( elem = this[ i++ ] ) ) { + curValue = getClass( elem ); + + // This expression is here for better compressibility (see addClass) + cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); + + if ( cur ) { + j = 0; + while ( ( clazz = classes[ j++ ] ) ) { + + // Remove *all* instances + while ( cur.indexOf( " " + clazz + " " ) > -1 ) { + cur = cur.replace( " " + clazz + " ", " " ); + } + } + + // Only assign if different to avoid unneeded rendering. + finalValue = stripAndCollapse( cur ); + if ( curValue !== finalValue ) { + elem.setAttribute( "class", finalValue ); + } + } + } + } + + return this; + }, + + toggleClass: function( value, stateVal ) { + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); + + if ( typeof stateVal === "boolean" && isValidValue ) { + return stateVal ? this.addClass( value ) : this.removeClass( value ); + } + + if ( isFunction( value ) ) { + return this.each( function( i ) { + jQuery( this ).toggleClass( + value.call( this, i, getClass( this ), stateVal ), + stateVal + ); + } ); + } + + return this.each( function() { + var className, i, self, classNames; + + if ( isValidValue ) { + + // Toggle individual class names + i = 0; + self = jQuery( this ); + classNames = classesToArray( value ); + + while ( ( className = classNames[ i++ ] ) ) { + + // Check each className given, space separated list + if ( self.hasClass( className ) ) { + self.removeClass( className ); + } else { + self.addClass( className ); + } + } + + // Toggle whole class name + } else if ( value === undefined || type === "boolean" ) { + className = getClass( this ); + if ( className ) { + + // Store className if set + dataPriv.set( this, "__className__", className ); + } + + // If the element has a class name or if we're passed `false`, + // then remove the whole classname (if there was one, the above saved it). + // Otherwise bring back whatever was previously saved (if anything), + // falling back to the empty string if nothing was stored. + if ( this.setAttribute ) { + this.setAttribute( "class", + className || value === false ? + "" : + dataPriv.get( this, "__className__" ) || "" + ); + } + } + } ); + }, + + hasClass: function( selector ) { + var className, elem, + i = 0; + + className = " " + selector + " "; + while ( ( elem = this[ i++ ] ) ) { + if ( elem.nodeType === 1 && + ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { + return true; + } + } + + return false; + } +} ); + + + + +var rreturn = /\r/g; + +jQuery.fn.extend( { + val: function( value ) { + var hooks, ret, valueIsFunction, + elem = this[ 0 ]; + + if ( !arguments.length ) { + if ( elem ) { + hooks = jQuery.valHooks[ elem.type ] || + jQuery.valHooks[ elem.nodeName.toLowerCase() ]; + + if ( hooks && + "get" in hooks && + ( ret = hooks.get( elem, "value" ) ) !== undefined + ) { + return ret; + } + + ret = elem.value; + + // Handle most common string cases + if ( typeof ret === "string" ) { + return ret.replace( rreturn, "" ); + } + + // Handle cases where value is null/undef or number + return ret == null ? "" : ret; + } + + return; + } + + valueIsFunction = isFunction( value ); + + return this.each( function( i ) { + var val; + + if ( this.nodeType !== 1 ) { + return; + } + + if ( valueIsFunction ) { + val = value.call( this, i, jQuery( this ).val() ); + } else { + val = value; + } + + // Treat null/undefined as ""; convert numbers to string + if ( val == null ) { + val = ""; + + } else if ( typeof val === "number" ) { + val += ""; + + } else if ( Array.isArray( val ) ) { + val = jQuery.map( val, function( value ) { + return value == null ? "" : value + ""; + } ); + } + + hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; + + // If set returns undefined, fall back to normal setting + if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { + this.value = val; + } + } ); + } +} ); + +jQuery.extend( { + valHooks: { + option: { + get: function( elem ) { + + var val = jQuery.find.attr( elem, "value" ); + return val != null ? + val : + + // Support: IE <=10 - 11 only + // option.text throws exceptions (#14686, #14858) + // Strip and collapse whitespace + // https://html.spec.whatwg.org/#strip-and-collapse-whitespace + stripAndCollapse( jQuery.text( elem ) ); + } + }, + select: { + get: function( elem ) { + var value, option, i, + options = elem.options, + index = elem.selectedIndex, + one = elem.type === "select-one", + values = one ? null : [], + max = one ? index + 1 : options.length; + + if ( index < 0 ) { + i = max; + + } else { + i = one ? index : 0; + } + + // Loop through all the selected options + for ( ; i < max; i++ ) { + option = options[ i ]; + + // Support: IE <=9 only + // IE8-9 doesn't update selected after form reset (#2551) + if ( ( option.selected || i === index ) && + + // Don't return options that are disabled or in a disabled optgroup + !option.disabled && + ( !option.parentNode.disabled || + !nodeName( option.parentNode, "optgroup" ) ) ) { + + // Get the specific value for the option + value = jQuery( option ).val(); + + // We don't need an array for one selects + if ( one ) { + return value; + } + + // Multi-Selects return an array + values.push( value ); + } + } + + return values; + }, + + set: function( elem, value ) { + var optionSet, option, + options = elem.options, + values = jQuery.makeArray( value ), + i = options.length; + + while ( i-- ) { + option = options[ i ]; + + /* eslint-disable no-cond-assign */ + + if ( option.selected = + jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 + ) { + optionSet = true; + } + + /* eslint-enable no-cond-assign */ + } + + // Force browsers to behave consistently when non-matching value is set + if ( !optionSet ) { + elem.selectedIndex = -1; + } + return values; + } + } + } +} ); + +// Radios and checkboxes getter/setter +jQuery.each( [ "radio", "checkbox" ], function() { + jQuery.valHooks[ this ] = { + set: function( elem, value ) { + if ( Array.isArray( value ) ) { + return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); + } + } + }; + if ( !support.checkOn ) { + jQuery.valHooks[ this ].get = function( elem ) { + return elem.getAttribute( "value" ) === null ? "on" : elem.value; + }; + } +} ); + + + + +// Return jQuery for attributes-only inclusion + + +support.focusin = "onfocusin" in window; + + +var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, + stopPropagationCallback = function( e ) { + e.stopPropagation(); + }; + +jQuery.extend( jQuery.event, { + + trigger: function( event, data, elem, onlyHandlers ) { + + var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, + eventPath = [ elem || document ], + type = hasOwn.call( event, "type" ) ? event.type : event, + namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; + + cur = lastElement = tmp = elem = elem || document; + + // Don't do events on text and comment nodes + if ( elem.nodeType === 3 || elem.nodeType === 8 ) { + return; + } + + // focus/blur morphs to focusin/out; ensure we're not firing them right now + if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { + return; + } + + if ( type.indexOf( "." ) > -1 ) { + + // Namespaced trigger; create a regexp to match event type in handle() + namespaces = type.split( "." ); + type = namespaces.shift(); + namespaces.sort(); + } + ontype = type.indexOf( ":" ) < 0 && "on" + type; + + // Caller can pass in a jQuery.Event object, Object, or just an event type string + event = event[ jQuery.expando ] ? + event : + new jQuery.Event( type, typeof event === "object" && event ); + + // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) + event.isTrigger = onlyHandlers ? 2 : 3; + event.namespace = namespaces.join( "." ); + event.rnamespace = event.namespace ? + new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : + null; + + // Clean up the event in case it is being reused + event.result = undefined; + if ( !event.target ) { + event.target = elem; + } + + // Clone any incoming data and prepend the event, creating the handler arg list + data = data == null ? + [ event ] : + jQuery.makeArray( data, [ event ] ); + + // Allow special events to draw outside the lines + special = jQuery.event.special[ type ] || {}; + if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { + return; + } + + // Determine event propagation path in advance, per W3C events spec (#9951) + // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) + if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { + + bubbleType = special.delegateType || type; + if ( !rfocusMorph.test( bubbleType + type ) ) { + cur = cur.parentNode; + } + for ( ; cur; cur = cur.parentNode ) { + eventPath.push( cur ); + tmp = cur; + } + + // Only add window if we got to document (e.g., not plain obj or detached DOM) + if ( tmp === ( elem.ownerDocument || document ) ) { + eventPath.push( tmp.defaultView || tmp.parentWindow || window ); + } + } + + // Fire handlers on the event path + i = 0; + while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { + lastElement = cur; + event.type = i > 1 ? + bubbleType : + special.bindType || type; + + // jQuery handler + handle = ( + dataPriv.get( cur, "events" ) || Object.create( null ) + )[ event.type ] && + dataPriv.get( cur, "handle" ); + if ( handle ) { + handle.apply( cur, data ); + } + + // Native handler + handle = ontype && cur[ ontype ]; + if ( handle && handle.apply && acceptData( cur ) ) { + event.result = handle.apply( cur, data ); + if ( event.result === false ) { + event.preventDefault(); + } + } + } + event.type = type; + + // If nobody prevented the default action, do it now + if ( !onlyHandlers && !event.isDefaultPrevented() ) { + + if ( ( !special._default || + special._default.apply( eventPath.pop(), data ) === false ) && + acceptData( elem ) ) { + + // Call a native DOM method on the target with the same name as the event. + // Don't do default actions on window, that's where global variables be (#6170) + if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { + + // Don't re-trigger an onFOO event when we call its FOO() method + tmp = elem[ ontype ]; + + if ( tmp ) { + elem[ ontype ] = null; + } + + // Prevent re-triggering of the same event, since we already bubbled it above + jQuery.event.triggered = type; + + if ( event.isPropagationStopped() ) { + lastElement.addEventListener( type, stopPropagationCallback ); + } + + elem[ type ](); + + if ( event.isPropagationStopped() ) { + lastElement.removeEventListener( type, stopPropagationCallback ); + } + + jQuery.event.triggered = undefined; + + if ( tmp ) { + elem[ ontype ] = tmp; + } + } + } + } + + return event.result; + }, + + // Piggyback on a donor event to simulate a different one + // Used only for `focus(in | out)` events + simulate: function( type, elem, event ) { + var e = jQuery.extend( + new jQuery.Event(), + event, + { + type: type, + isSimulated: true + } + ); + + jQuery.event.trigger( e, null, elem ); + } + +} ); + +jQuery.fn.extend( { + + trigger: function( type, data ) { + return this.each( function() { + jQuery.event.trigger( type, data, this ); + } ); + }, + triggerHandler: function( type, data ) { + var elem = this[ 0 ]; + if ( elem ) { + return jQuery.event.trigger( type, data, elem, true ); + } + } +} ); + + +// Support: Firefox <=44 +// Firefox doesn't have focus(in | out) events +// Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 +// +// Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 +// focus(in | out) events fire after focus & blur events, +// which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order +// Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 +if ( !support.focusin ) { + jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { + + // Attach a single capturing handler on the document while someone wants focusin/focusout + var handler = function( event ) { + jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); + }; + + jQuery.event.special[ fix ] = { + setup: function() { + + // Handle: regular nodes (via `this.ownerDocument`), window + // (via `this.document`) & document (via `this`). + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ); + + if ( !attaches ) { + doc.addEventListener( orig, handler, true ); + } + dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); + }, + teardown: function() { + var doc = this.ownerDocument || this.document || this, + attaches = dataPriv.access( doc, fix ) - 1; + + if ( !attaches ) { + doc.removeEventListener( orig, handler, true ); + dataPriv.remove( doc, fix ); + + } else { + dataPriv.access( doc, fix, attaches ); + } + } + }; + } ); +} +var location = window.location; + +var nonce = { guid: Date.now() }; + +var rquery = ( /\?/ ); + + + +// Cross-browser xml parsing +jQuery.parseXML = function( data ) { + var xml; + if ( !data || typeof data !== "string" ) { + return null; + } + + // Support: IE 9 - 11 only + // IE throws on parseFromString with invalid input. + try { + xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); + } catch ( e ) { + xml = undefined; + } + + if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { + jQuery.error( "Invalid XML: " + data ); + } + return xml; +}; + + +var + rbracket = /\[\]$/, + rCRLF = /\r?\n/g, + rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, + rsubmittable = /^(?:input|select|textarea|keygen)/i; + +function buildParams( prefix, obj, traditional, add ) { + var name; + + if ( Array.isArray( obj ) ) { + + // Serialize array item. + jQuery.each( obj, function( i, v ) { + if ( traditional || rbracket.test( prefix ) ) { + + // Treat each array item as a scalar. + add( prefix, v ); + + } else { + + // Item is non-scalar (array or object), encode its numeric index. + buildParams( + prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", + v, + traditional, + add + ); + } + } ); + + } else if ( !traditional && toType( obj ) === "object" ) { + + // Serialize object item. + for ( name in obj ) { + buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); + } + + } else { + + // Serialize scalar item. + add( prefix, obj ); + } +} + +// Serialize an array of form elements or a set of +// key/values into a query string +jQuery.param = function( a, traditional ) { + var prefix, + s = [], + add = function( key, valueOrFunction ) { + + // If value is a function, invoke it and use its return value + var value = isFunction( valueOrFunction ) ? + valueOrFunction() : + valueOrFunction; + + s[ s.length ] = encodeURIComponent( key ) + "=" + + encodeURIComponent( value == null ? "" : value ); + }; + + if ( a == null ) { + return ""; + } + + // If an array was passed in, assume that it is an array of form elements. + if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { + + // Serialize the form elements + jQuery.each( a, function() { + add( this.name, this.value ); + } ); + + } else { + + // If traditional, encode the "old" way (the way 1.3.2 or older + // did it), otherwise encode params recursively. + for ( prefix in a ) { + buildParams( prefix, a[ prefix ], traditional, add ); + } + } + + // Return the resulting serialization + return s.join( "&" ); +}; + +jQuery.fn.extend( { + serialize: function() { + return jQuery.param( this.serializeArray() ); + }, + serializeArray: function() { + return this.map( function() { + + // Can add propHook for "elements" to filter or add form elements + var elements = jQuery.prop( this, "elements" ); + return elements ? jQuery.makeArray( elements ) : this; + } ) + .filter( function() { + var type = this.type; + + // Use .is( ":disabled" ) so that fieldset[disabled] works + return this.name && !jQuery( this ).is( ":disabled" ) && + rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && + ( this.checked || !rcheckableType.test( type ) ); + } ) + .map( function( _i, elem ) { + var val = jQuery( this ).val(); + + if ( val == null ) { + return null; + } + + if ( Array.isArray( val ) ) { + return jQuery.map( val, function( val ) { + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ); + } + + return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; + } ).get(); + } +} ); + + +var + r20 = /%20/g, + rhash = /#.*$/, + rantiCache = /([?&])_=[^&]*/, + rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, + + // #7653, #8125, #8152: local protocol detection + rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, + rnoContent = /^(?:GET|HEAD)$/, + rprotocol = /^\/\//, + + /* Prefilters + * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) + * 2) These are called: + * - BEFORE asking for a transport + * - AFTER param serialization (s.data is a string if s.processData is true) + * 3) key is the dataType + * 4) the catchall symbol "*" can be used + * 5) execution will start with transport dataType and THEN continue down to "*" if needed + */ + prefilters = {}, + + /* Transports bindings + * 1) key is the dataType + * 2) the catchall symbol "*" can be used + * 3) selection will start with transport dataType and THEN go to "*" if needed + */ + transports = {}, + + // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression + allTypes = "*/".concat( "*" ), + + // Anchor tag for parsing the document origin + originAnchor = document.createElement( "a" ); + originAnchor.href = location.href; + +// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport +function addToPrefiltersOrTransports( structure ) { + + // dataTypeExpression is optional and defaults to "*" + return function( dataTypeExpression, func ) { + + if ( typeof dataTypeExpression !== "string" ) { + func = dataTypeExpression; + dataTypeExpression = "*"; + } + + var dataType, + i = 0, + dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; + + if ( isFunction( func ) ) { + + // For each dataType in the dataTypeExpression + while ( ( dataType = dataTypes[ i++ ] ) ) { + + // Prepend if requested + if ( dataType[ 0 ] === "+" ) { + dataType = dataType.slice( 1 ) || "*"; + ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); + + // Otherwise append + } else { + ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); + } + } + } + }; +} + +// Base inspection function for prefilters and transports +function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { + + var inspected = {}, + seekingTransport = ( structure === transports ); + + function inspect( dataType ) { + var selected; + inspected[ dataType ] = true; + jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { + var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); + if ( typeof dataTypeOrTransport === "string" && + !seekingTransport && !inspected[ dataTypeOrTransport ] ) { + + options.dataTypes.unshift( dataTypeOrTransport ); + inspect( dataTypeOrTransport ); + return false; + } else if ( seekingTransport ) { + return !( selected = dataTypeOrTransport ); + } + } ); + return selected; + } + + return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); +} + +// A special extend for ajax options +// that takes "flat" options (not to be deep extended) +// Fixes #9887 +function ajaxExtend( target, src ) { + var key, deep, + flatOptions = jQuery.ajaxSettings.flatOptions || {}; + + for ( key in src ) { + if ( src[ key ] !== undefined ) { + ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; + } + } + if ( deep ) { + jQuery.extend( true, target, deep ); + } + + return target; +} + +/* Handles responses to an ajax request: + * - finds the right dataType (mediates between content-type and expected dataType) + * - returns the corresponding response + */ +function ajaxHandleResponses( s, jqXHR, responses ) { + + var ct, type, finalDataType, firstDataType, + contents = s.contents, + dataTypes = s.dataTypes; + + // Remove auto dataType and get content-type in the process + while ( dataTypes[ 0 ] === "*" ) { + dataTypes.shift(); + if ( ct === undefined ) { + ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); + } + } + + // Check if we're dealing with a known content-type + if ( ct ) { + for ( type in contents ) { + if ( contents[ type ] && contents[ type ].test( ct ) ) { + dataTypes.unshift( type ); + break; + } + } + } + + // Check to see if we have a response for the expected dataType + if ( dataTypes[ 0 ] in responses ) { + finalDataType = dataTypes[ 0 ]; + } else { + + // Try convertible dataTypes + for ( type in responses ) { + if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { + finalDataType = type; + break; + } + if ( !firstDataType ) { + firstDataType = type; + } + } + + // Or just use first one + finalDataType = finalDataType || firstDataType; + } + + // If we found a dataType + // We add the dataType to the list if needed + // and return the corresponding response + if ( finalDataType ) { + if ( finalDataType !== dataTypes[ 0 ] ) { + dataTypes.unshift( finalDataType ); + } + return responses[ finalDataType ]; + } +} + +/* Chain conversions given the request and the original response + * Also sets the responseXXX fields on the jqXHR instance + */ +function ajaxConvert( s, response, jqXHR, isSuccess ) { + var conv2, current, conv, tmp, prev, + converters = {}, + + // Work with a copy of dataTypes in case we need to modify it for conversion + dataTypes = s.dataTypes.slice(); + + // Create converters map with lowercased keys + if ( dataTypes[ 1 ] ) { + for ( conv in s.converters ) { + converters[ conv.toLowerCase() ] = s.converters[ conv ]; + } + } + + current = dataTypes.shift(); + + // Convert to each sequential dataType + while ( current ) { + + if ( s.responseFields[ current ] ) { + jqXHR[ s.responseFields[ current ] ] = response; + } + + // Apply the dataFilter if provided + if ( !prev && isSuccess && s.dataFilter ) { + response = s.dataFilter( response, s.dataType ); + } + + prev = current; + current = dataTypes.shift(); + + if ( current ) { + + // There's only work to do if current dataType is non-auto + if ( current === "*" ) { + + current = prev; + + // Convert response if prev dataType is non-auto and differs from current + } else if ( prev !== "*" && prev !== current ) { + + // Seek a direct converter + conv = converters[ prev + " " + current ] || converters[ "* " + current ]; + + // If none found, seek a pair + if ( !conv ) { + for ( conv2 in converters ) { + + // If conv2 outputs current + tmp = conv2.split( " " ); + if ( tmp[ 1 ] === current ) { + + // If prev can be converted to accepted input + conv = converters[ prev + " " + tmp[ 0 ] ] || + converters[ "* " + tmp[ 0 ] ]; + if ( conv ) { + + // Condense equivalence converters + if ( conv === true ) { + conv = converters[ conv2 ]; + + // Otherwise, insert the intermediate dataType + } else if ( converters[ conv2 ] !== true ) { + current = tmp[ 0 ]; + dataTypes.unshift( tmp[ 1 ] ); + } + break; + } + } + } + } + + // Apply converter (if not an equivalence) + if ( conv !== true ) { + + // Unless errors are allowed to bubble, catch and return them + if ( conv && s.throws ) { + response = conv( response ); + } else { + try { + response = conv( response ); + } catch ( e ) { + return { + state: "parsererror", + error: conv ? e : "No conversion from " + prev + " to " + current + }; + } + } + } + } + } + } + + return { state: "success", data: response }; +} + +jQuery.extend( { + + // Counter for holding the number of active queries + active: 0, + + // Last-Modified header cache for next request + lastModified: {}, + etag: {}, + + ajaxSettings: { + url: location.href, + type: "GET", + isLocal: rlocalProtocol.test( location.protocol ), + global: true, + processData: true, + async: true, + contentType: "application/x-www-form-urlencoded; charset=UTF-8", + + /* + timeout: 0, + data: null, + dataType: null, + username: null, + password: null, + cache: null, + throws: false, + traditional: false, + headers: {}, + */ + + accepts: { + "*": allTypes, + text: "text/plain", + html: "text/html", + xml: "application/xml, text/xml", + json: "application/json, text/javascript" + }, + + contents: { + xml: /\bxml\b/, + html: /\bhtml/, + json: /\bjson\b/ + }, + + responseFields: { + xml: "responseXML", + text: "responseText", + json: "responseJSON" + }, + + // Data converters + // Keys separate source (or catchall "*") and destination types with a single space + converters: { + + // Convert anything to text + "* text": String, + + // Text to html (true = no transformation) + "text html": true, + + // Evaluate text as a json expression + "text json": JSON.parse, + + // Parse text as xml + "text xml": jQuery.parseXML + }, + + // For options that shouldn't be deep extended: + // you can add your own custom options here if + // and when you create one that shouldn't be + // deep extended (see ajaxExtend) + flatOptions: { + url: true, + context: true + } + }, + + // Creates a full fledged settings object into target + // with both ajaxSettings and settings fields. + // If target is omitted, writes into ajaxSettings. + ajaxSetup: function( target, settings ) { + return settings ? + + // Building a settings object + ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : + + // Extending ajaxSettings + ajaxExtend( jQuery.ajaxSettings, target ); + }, + + ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), + ajaxTransport: addToPrefiltersOrTransports( transports ), + + // Main method + ajax: function( url, options ) { + + // If url is an object, simulate pre-1.5 signature + if ( typeof url === "object" ) { + options = url; + url = undefined; + } + + // Force options to be an object + options = options || {}; + + var transport, + + // URL without anti-cache param + cacheURL, + + // Response headers + responseHeadersString, + responseHeaders, + + // timeout handle + timeoutTimer, + + // Url cleanup var + urlAnchor, + + // Request state (becomes false upon send and true upon completion) + completed, + + // To know if global events are to be dispatched + fireGlobals, + + // Loop variable + i, + + // uncached part of the url + uncached, + + // Create the final options object + s = jQuery.ajaxSetup( {}, options ), + + // Callbacks context + callbackContext = s.context || s, + + // Context for global events is callbackContext if it is a DOM node or jQuery collection + globalEventContext = s.context && + ( callbackContext.nodeType || callbackContext.jquery ) ? + jQuery( callbackContext ) : + jQuery.event, + + // Deferreds + deferred = jQuery.Deferred(), + completeDeferred = jQuery.Callbacks( "once memory" ), + + // Status-dependent callbacks + statusCode = s.statusCode || {}, + + // Headers (they are sent all at once) + requestHeaders = {}, + requestHeadersNames = {}, + + // Default abort message + strAbort = "canceled", + + // Fake xhr + jqXHR = { + readyState: 0, + + // Builds headers hashtable if needed + getResponseHeader: function( key ) { + var match; + if ( completed ) { + if ( !responseHeaders ) { + responseHeaders = {}; + while ( ( match = rheaders.exec( responseHeadersString ) ) ) { + responseHeaders[ match[ 1 ].toLowerCase() + " " ] = + ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) + .concat( match[ 2 ] ); + } + } + match = responseHeaders[ key.toLowerCase() + " " ]; + } + return match == null ? null : match.join( ", " ); + }, + + // Raw string + getAllResponseHeaders: function() { + return completed ? responseHeadersString : null; + }, + + // Caches the header + setRequestHeader: function( name, value ) { + if ( completed == null ) { + name = requestHeadersNames[ name.toLowerCase() ] = + requestHeadersNames[ name.toLowerCase() ] || name; + requestHeaders[ name ] = value; + } + return this; + }, + + // Overrides response content-type header + overrideMimeType: function( type ) { + if ( completed == null ) { + s.mimeType = type; + } + return this; + }, + + // Status-dependent callbacks + statusCode: function( map ) { + var code; + if ( map ) { + if ( completed ) { + + // Execute the appropriate callbacks + jqXHR.always( map[ jqXHR.status ] ); + } else { + + // Lazy-add the new callbacks in a way that preserves old ones + for ( code in map ) { + statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; + } + } + } + return this; + }, + + // Cancel the request + abort: function( statusText ) { + var finalText = statusText || strAbort; + if ( transport ) { + transport.abort( finalText ); + } + done( 0, finalText ); + return this; + } + }; + + // Attach deferreds + deferred.promise( jqXHR ); + + // Add protocol if not provided (prefilters might expect it) + // Handle falsy url in the settings object (#10093: consistency with old signature) + // We also use the url parameter if available + s.url = ( ( url || s.url || location.href ) + "" ) + .replace( rprotocol, location.protocol + "//" ); + + // Alias method option to type as per ticket #12004 + s.type = options.method || options.type || s.method || s.type; + + // Extract dataTypes list + s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; + + // A cross-domain request is in order when the origin doesn't match the current origin. + if ( s.crossDomain == null ) { + urlAnchor = document.createElement( "a" ); + + // Support: IE <=8 - 11, Edge 12 - 15 + // IE throws exception on accessing the href property if url is malformed, + // e.g. http://example.com:80x/ + try { + urlAnchor.href = s.url; + + // Support: IE <=8 - 11 only + // Anchor's host property isn't correctly set when s.url is relative + urlAnchor.href = urlAnchor.href; + s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== + urlAnchor.protocol + "//" + urlAnchor.host; + } catch ( e ) { + + // If there is an error parsing the URL, assume it is crossDomain, + // it can be rejected by the transport if it is invalid + s.crossDomain = true; + } + } + + // Convert data if not already a string + if ( s.data && s.processData && typeof s.data !== "string" ) { + s.data = jQuery.param( s.data, s.traditional ); + } + + // Apply prefilters + inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); + + // If request was aborted inside a prefilter, stop there + if ( completed ) { + return jqXHR; + } + + // We can fire global events as of now if asked to + // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) + fireGlobals = jQuery.event && s.global; + + // Watch for a new set of requests + if ( fireGlobals && jQuery.active++ === 0 ) { + jQuery.event.trigger( "ajaxStart" ); + } + + // Uppercase the type + s.type = s.type.toUpperCase(); + + // Determine if request has content + s.hasContent = !rnoContent.test( s.type ); + + // Save the URL in case we're toying with the If-Modified-Since + // and/or If-None-Match header later on + // Remove hash to simplify url manipulation + cacheURL = s.url.replace( rhash, "" ); + + // More options handling for requests with no content + if ( !s.hasContent ) { + + // Remember the hash so we can put it back + uncached = s.url.slice( cacheURL.length ); + + // If data is available and should be processed, append data to url + if ( s.data && ( s.processData || typeof s.data === "string" ) ) { + cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; + + // #9682: remove data so that it's not used in an eventual retry + delete s.data; + } + + // Add or update anti-cache param if needed + if ( s.cache === false ) { + cacheURL = cacheURL.replace( rantiCache, "$1" ); + uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + + uncached; + } + + // Put hash and anti-cache on the URL that will be requested (gh-1732) + s.url = cacheURL + uncached; + + // Change '%20' to '+' if this is encoded form body content (gh-2658) + } else if ( s.data && s.processData && + ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { + s.data = s.data.replace( r20, "+" ); + } + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + if ( jQuery.lastModified[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); + } + if ( jQuery.etag[ cacheURL ] ) { + jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); + } + } + + // Set the correct header, if data is being sent + if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { + jqXHR.setRequestHeader( "Content-Type", s.contentType ); + } + + // Set the Accepts header for the server, depending on the dataType + jqXHR.setRequestHeader( + "Accept", + s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? + s.accepts[ s.dataTypes[ 0 ] ] + + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : + s.accepts[ "*" ] + ); + + // Check for headers option + for ( i in s.headers ) { + jqXHR.setRequestHeader( i, s.headers[ i ] ); + } + + // Allow custom headers/mimetypes and early abort + if ( s.beforeSend && + ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { + + // Abort if not done already and return + return jqXHR.abort(); + } + + // Aborting is no longer a cancellation + strAbort = "abort"; + + // Install callbacks on deferreds + completeDeferred.add( s.complete ); + jqXHR.done( s.success ); + jqXHR.fail( s.error ); + + // Get transport + transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); + + // If no transport, we auto-abort + if ( !transport ) { + done( -1, "No Transport" ); + } else { + jqXHR.readyState = 1; + + // Send global event + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); + } + + // If request was aborted inside ajaxSend, stop there + if ( completed ) { + return jqXHR; + } + + // Timeout + if ( s.async && s.timeout > 0 ) { + timeoutTimer = window.setTimeout( function() { + jqXHR.abort( "timeout" ); + }, s.timeout ); + } + + try { + completed = false; + transport.send( requestHeaders, done ); + } catch ( e ) { + + // Rethrow post-completion exceptions + if ( completed ) { + throw e; + } + + // Propagate others as results + done( -1, e ); + } + } + + // Callback for when everything is done + function done( status, nativeStatusText, responses, headers ) { + var isSuccess, success, error, response, modified, + statusText = nativeStatusText; + + // Ignore repeat invocations + if ( completed ) { + return; + } + + completed = true; + + // Clear timeout if it exists + if ( timeoutTimer ) { + window.clearTimeout( timeoutTimer ); + } + + // Dereference transport for early garbage collection + // (no matter how long the jqXHR object will be used) + transport = undefined; + + // Cache response headers + responseHeadersString = headers || ""; + + // Set readyState + jqXHR.readyState = status > 0 ? 4 : 0; + + // Determine if successful + isSuccess = status >= 200 && status < 300 || status === 304; + + // Get response data + if ( responses ) { + response = ajaxHandleResponses( s, jqXHR, responses ); + } + + // Use a noop converter for missing script + if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 ) { + s.converters[ "text script" ] = function() {}; + } + + // Convert no matter what (that way responseXXX fields are always set) + response = ajaxConvert( s, response, jqXHR, isSuccess ); + + // If successful, handle type chaining + if ( isSuccess ) { + + // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. + if ( s.ifModified ) { + modified = jqXHR.getResponseHeader( "Last-Modified" ); + if ( modified ) { + jQuery.lastModified[ cacheURL ] = modified; + } + modified = jqXHR.getResponseHeader( "etag" ); + if ( modified ) { + jQuery.etag[ cacheURL ] = modified; + } + } + + // if no content + if ( status === 204 || s.type === "HEAD" ) { + statusText = "nocontent"; + + // if not modified + } else if ( status === 304 ) { + statusText = "notmodified"; + + // If we have data, let's convert it + } else { + statusText = response.state; + success = response.data; + error = response.error; + isSuccess = !error; + } + } else { + + // Extract error from statusText and normalize for non-aborts + error = statusText; + if ( status || !statusText ) { + statusText = "error"; + if ( status < 0 ) { + status = 0; + } + } + } + + // Set data for the fake xhr object + jqXHR.status = status; + jqXHR.statusText = ( nativeStatusText || statusText ) + ""; + + // Success/Error + if ( isSuccess ) { + deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); + } else { + deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); + } + + // Status-dependent callbacks + jqXHR.statusCode( statusCode ); + statusCode = undefined; + + if ( fireGlobals ) { + globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", + [ jqXHR, s, isSuccess ? success : error ] ); + } + + // Complete + completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); + + if ( fireGlobals ) { + globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); + + // Handle the global AJAX counter + if ( !( --jQuery.active ) ) { + jQuery.event.trigger( "ajaxStop" ); + } + } + } + + return jqXHR; + }, + + getJSON: function( url, data, callback ) { + return jQuery.get( url, data, callback, "json" ); + }, + + getScript: function( url, callback ) { + return jQuery.get( url, undefined, callback, "script" ); + } +} ); + +jQuery.each( [ "get", "post" ], function( _i, method ) { + jQuery[ method ] = function( url, data, callback, type ) { + + // Shift arguments if data argument was omitted + if ( isFunction( data ) ) { + type = type || callback; + callback = data; + data = undefined; + } + + // The url can be an options object (which then must have .url) + return jQuery.ajax( jQuery.extend( { + url: url, + type: method, + dataType: type, + data: data, + success: callback + }, jQuery.isPlainObject( url ) && url ) ); + }; +} ); + +jQuery.ajaxPrefilter( function( s ) { + var i; + for ( i in s.headers ) { + if ( i.toLowerCase() === "content-type" ) { + s.contentType = s.headers[ i ] || ""; + } + } +} ); + + +jQuery._evalUrl = function( url, options, doc ) { + return jQuery.ajax( { + url: url, + + // Make this explicit, since user can override this through ajaxSetup (#11264) + type: "GET", + dataType: "script", + cache: true, + async: false, + global: false, + + // Only evaluate the response if it is successful (gh-4126) + // dataFilter is not invoked for failure responses, so using it instead + // of the default converter is kludgy but it works. + converters: { + "text script": function() {} + }, + dataFilter: function( response ) { + jQuery.globalEval( response, options, doc ); + } + } ); +}; + + +jQuery.fn.extend( { + wrapAll: function( html ) { + var wrap; + + if ( this[ 0 ] ) { + if ( isFunction( html ) ) { + html = html.call( this[ 0 ] ); + } + + // The elements to wrap the target around + wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); + + if ( this[ 0 ].parentNode ) { + wrap.insertBefore( this[ 0 ] ); + } + + wrap.map( function() { + var elem = this; + + while ( elem.firstElementChild ) { + elem = elem.firstElementChild; + } + + return elem; + } ).append( this ); + } + + return this; + }, + + wrapInner: function( html ) { + if ( isFunction( html ) ) { + return this.each( function( i ) { + jQuery( this ).wrapInner( html.call( this, i ) ); + } ); + } + + return this.each( function() { + var self = jQuery( this ), + contents = self.contents(); + + if ( contents.length ) { + contents.wrapAll( html ); + + } else { + self.append( html ); + } + } ); + }, + + wrap: function( html ) { + var htmlIsFunction = isFunction( html ); + + return this.each( function( i ) { + jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); + } ); + }, + + unwrap: function( selector ) { + this.parent( selector ).not( "body" ).each( function() { + jQuery( this ).replaceWith( this.childNodes ); + } ); + return this; + } +} ); + + +jQuery.expr.pseudos.hidden = function( elem ) { + return !jQuery.expr.pseudos.visible( elem ); +}; +jQuery.expr.pseudos.visible = function( elem ) { + return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); +}; + + + + +jQuery.ajaxSettings.xhr = function() { + try { + return new window.XMLHttpRequest(); + } catch ( e ) {} +}; + +var xhrSuccessStatus = { + + // File protocol always yields status code 0, assume 200 + 0: 200, + + // Support: IE <=9 only + // #1450: sometimes IE returns 1223 when it should be 204 + 1223: 204 + }, + xhrSupported = jQuery.ajaxSettings.xhr(); + +support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); +support.ajax = xhrSupported = !!xhrSupported; + +jQuery.ajaxTransport( function( options ) { + var callback, errorCallback; + + // Cross domain only allowed if supported through XMLHttpRequest + if ( support.cors || xhrSupported && !options.crossDomain ) { + return { + send: function( headers, complete ) { + var i, + xhr = options.xhr(); + + xhr.open( + options.type, + options.url, + options.async, + options.username, + options.password + ); + + // Apply custom fields if provided + if ( options.xhrFields ) { + for ( i in options.xhrFields ) { + xhr[ i ] = options.xhrFields[ i ]; + } + } + + // Override mime type if needed + if ( options.mimeType && xhr.overrideMimeType ) { + xhr.overrideMimeType( options.mimeType ); + } + + // X-Requested-With header + // For cross-domain requests, seeing as conditions for a preflight are + // akin to a jigsaw puzzle, we simply never set it to be sure. + // (it can always be set on a per-request basis or even using ajaxSetup) + // For same-domain requests, won't change header if already provided. + if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { + headers[ "X-Requested-With" ] = "XMLHttpRequest"; + } + + // Set headers + for ( i in headers ) { + xhr.setRequestHeader( i, headers[ i ] ); + } + + // Callback + callback = function( type ) { + return function() { + if ( callback ) { + callback = errorCallback = xhr.onload = + xhr.onerror = xhr.onabort = xhr.ontimeout = + xhr.onreadystatechange = null; + + if ( type === "abort" ) { + xhr.abort(); + } else if ( type === "error" ) { + + // Support: IE <=9 only + // On a manual native abort, IE9 throws + // errors on any property access that is not readyState + if ( typeof xhr.status !== "number" ) { + complete( 0, "error" ); + } else { + complete( + + // File: protocol always yields status 0; see #8605, #14207 + xhr.status, + xhr.statusText + ); + } + } else { + complete( + xhrSuccessStatus[ xhr.status ] || xhr.status, + xhr.statusText, + + // Support: IE <=9 only + // IE9 has no XHR2 but throws on binary (trac-11426) + // For XHR2 non-text, let the caller handle it (gh-2498) + ( xhr.responseType || "text" ) !== "text" || + typeof xhr.responseText !== "string" ? + { binary: xhr.response } : + { text: xhr.responseText }, + xhr.getAllResponseHeaders() + ); + } + } + }; + }; + + // Listen to events + xhr.onload = callback(); + errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); + + // Support: IE 9 only + // Use onreadystatechange to replace onabort + // to handle uncaught aborts + if ( xhr.onabort !== undefined ) { + xhr.onabort = errorCallback; + } else { + xhr.onreadystatechange = function() { + + // Check readyState before timeout as it changes + if ( xhr.readyState === 4 ) { + + // Allow onerror to be called first, + // but that will not handle a native abort + // Also, save errorCallback to a variable + // as xhr.onerror cannot be accessed + window.setTimeout( function() { + if ( callback ) { + errorCallback(); + } + } ); + } + }; + } + + // Create the abort callback + callback = callback( "abort" ); + + try { + + // Do send the request (this may raise an exception) + xhr.send( options.hasContent && options.data || null ); + } catch ( e ) { + + // #14683: Only rethrow if this hasn't been notified as an error yet + if ( callback ) { + throw e; + } + } + }, + + abort: function() { + if ( callback ) { + callback(); + } + } + }; + } +} ); + + + + +// Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) +jQuery.ajaxPrefilter( function( s ) { + if ( s.crossDomain ) { + s.contents.script = false; + } +} ); + +// Install script dataType +jQuery.ajaxSetup( { + accepts: { + script: "text/javascript, application/javascript, " + + "application/ecmascript, application/x-ecmascript" + }, + contents: { + script: /\b(?:java|ecma)script\b/ + }, + converters: { + "text script": function( text ) { + jQuery.globalEval( text ); + return text; + } + } +} ); + +// Handle cache's special case and crossDomain +jQuery.ajaxPrefilter( "script", function( s ) { + if ( s.cache === undefined ) { + s.cache = false; + } + if ( s.crossDomain ) { + s.type = "GET"; + } +} ); + +// Bind script tag hack transport +jQuery.ajaxTransport( "script", function( s ) { + + // This transport only deals with cross domain or forced-by-attrs requests + if ( s.crossDomain || s.scriptAttrs ) { + var script, callback; + return { + send: function( _, complete ) { + script = jQuery( " - - - - + + + + + + - - + - +
    @@ -83,98 +46,128 @@

    NBNSProtocol Class

    pysmb has a NBNSProtocol implementation for Twisted framework. This allows you to perform name query asynchronously without having your application to block and wait for the results.

    -
    -
    In your project,
    -
      -
    1. Create a NBNSProtocol instance.
    2. -
    3. Just call queryName method which will return a Deferred instance. Add your callback function to the Deferred instance via addCallback method to receive the results of the name query.
    4. -
    5. When you are done with the NBNSProtocol instance, call its <NBNSProtocol instance>.transport.stopListening method to remove this instance from the reactor.
    6. +
      +
      In your project,
        +
      1. Create a NBNSProtocol instance.

      2. +
      3. Just call queryName method which will return a Deferred instance. Add your callback function to the Deferred instance via addCallback method to receive the results of the name query.

      4. +
      5. When you are done with the NBNSProtocol instance, call its <NBNSProtocol instance>.transport.stopListening method to remove this instance from the reactor.

      -
      +
      -class nmb.NetBIOSProtocol.NBNSProtocol(broadcast=True, listen_port=0)[source]
      -
      +class nmb.NetBIOSProtocol.NBNSProtocol(broadcast=True, listen_port=0)[source] +
      -__init__(broadcast=True, listen_port=0)[source]
      +__init__(broadcast=True, listen_port=0)[source]

      Instantiate a NBNSProtocol instance.

      This automatically calls reactor.listenUDP method to start listening for incoming packets, so you must not call the listenUDP method again.

      - --- - - - -
      Parameters:
        -
      • broadcast (boolean) – A boolean flag to indicate if we should setup the listening UDP port in broadcast mode
      • -
      • listen_port (integer) – Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.
      • +
        +
        Parameters
        +
          +
        • broadcast (boolean) – A boolean flag to indicate if we should setup the listening UDP port in broadcast mode

        • +
        • listen_port (integer) – Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.

        -
      +
      +
      -
      +
      +
      +datagramReceived(data, from_info)[source]
      +

      Called when a datagram is received.

      +

      @param datagram: the string received from the transport. +@param addr: tuple of source of datagram.

      +
      + +
      -queryIPForName(ip, port=137, timeout=30)[source]
      +queryIPForName(ip, port=137, timeout=30)[source]

      Send a query to the machine with ip and hopes that the machine will reply back with its name.

      The implementation of this function is contributed by Jason Anderson.

      - --- - - - - - -
      Parameters:
        -
      • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. -If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.
      • -
      • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.
      • -
      • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None
      • +
        +
        Parameters
        +
          +
        • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. +If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.

        • +
        • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.

        • +
        • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None

        -
      Returns:

      A twisted.internet.defer.Deferred instance. The callback function will be called with a list of names of the machine at ip. + +

      Returns
      +

      A twisted.internet.defer.Deferred instance. The callback function will be called with a list of names of the machine at ip. On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception

      -
      +
      +
      -
      +
      -queryName(name, ip='', port=137, timeout=30)[source]
      +queryName(name, ip='', port=137, timeout=30)[source]

      Send a query on the network and hopes that if machine matching the name will reply with its IP address.

      - --- - - - - - -
      Parameters:
        -
      • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. -If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.
      • -
      • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.
      • -
      • timeout (integer/float) – Number of seconds to wait for a reply, after which the returned Deferred instance will be called with a NetBIOSTimeout exception.
      • +
        +
        Parameters
        +
          +
        • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. +If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.

        • +
        • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.

        • +
        • timeout (integer/float) – Number of seconds to wait for a reply, after which the returned Deferred instance will be called with a NetBIOSTimeout exception.

        -
      Returns:

      A twisted.internet.defer.Deferred instance. The callback function will be called with a list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). + +

      Returns
      +

      A twisted.internet.defer.Deferred instance. The callback function will be called with a list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, the errback function will be called with a Failure instance wrapping around a NetBIOSTimeout exception

      -
      +
      +
      +
    + +
    +
    +stopProtocol()[source]
    +

    Called when the transport is disconnected.

    +

    Will only be called once, after all ports are disconnected.

    -
    +
    -class nmb.NetBIOSProtocol.NetBIOSTimeout[source]
    +class nmb.NetBIOSProtocol.NetBIOSTimeout[source]

    Raised in NBNSProtocol via Deferred.errback method when queryName method has timeout waiting for reply

    +
    + + +
    @@ -186,17 +179,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + + diff --git a/docs/html/api/nmb_NetBIOS.html b/docs/html/api/nmb_NetBIOS.html index 9bf23b5..7cb9e87 100644 --- a/docs/html/api/nmb_NetBIOS.html +++ b/docs/html/api/nmb_NetBIOS.html @@ -1,33 +1,22 @@ - + - + - - - NetBIOS class — pysmb 1.1.18 documentation - + + + NetBIOS class — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + + + +
    +
    +
    +
    + +
    +

    NetBIOS class

    +
    +
    To use the NetBIOS class in your application,
      +
    1. Create a new NetBIOS instance

    2. +
    3. Call queryName method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout.

    4. +
    5. When you are done, call close method to release the underlying resources.

    6. +
    +
    +
    +
    +
    +class nmb.NetBIOS.NetBIOS(broadcast=True, listen_port=0)[source]
    +
    +
    +__init__(broadcast=True, listen_port=0)[source]
    +

    Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets.

    +
    +
    Parameters
    +
      +
    • broadcast (boolean) – A boolean flag to indicate if we should setup the listening UDP port in broadcast mode

    • +
    • listen_port (integer) – Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.

    • +
    +
    +
    +
    + +
    +
    +close()[source]
    +

    Close the underlying and free resources.

    +

    The NetBIOS instance should not be used to perform any operations after this method returns.

    +
    +
    Returns
    +

    None

    +
    +
    +
    + +
    +
    +queryIPForName(ip, port=137, timeout=30)[source]
    +

    Send a query to the machine with ip and hopes that the machine will reply back with its name.

    +

    The implementation of this function is contributed by Jason Anderson.

    +
    +
    Parameters
    +
      +
    • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. +If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.

    • +
    • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.

    • +
    • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None

    • +
    +
    +
    Returns
    +

    A list of string containing the names of the machine at ip. On timeout, returns None.

    +
    +
    +
    + +
    +
    +queryName(name, ip='', port=137, timeout=30)[source]
    +

    Send a query on the network and hopes that if machine matching the name will reply with its IP address.

    +
    +
    Parameters
    +
      +
    • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. +If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.

    • +
    • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.

    • +
    • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None

    • +
    +
    +
    Returns
    +

    A list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, returns None.

    +
    +
    +
    + +
    + +
    + + +
    +
    +
    +
    - -
    -
    -
    -
    - -
    -

    NetBIOS class

    -
    -
    To use the NetBIOS class in your application,
    -
      -
    1. Create a new NetBIOS instance
    2. -
    3. Call queryName method for each name you wish to query. The method will block until a reply is received from the remote SMB/CIFS service, or until timeout.
    4. -
    5. When you are done, call close method to release the underlying resources.
    6. -
    -
    -
    -
    -
    -class nmb.NetBIOS.NetBIOS(broadcast=True, listen_port=0)[source]
    -
    -
    -__init__(broadcast=True, listen_port=0)[source]
    -

    Instantiate a NetBIOS instance, and creates a IPv4 UDP socket to listen/send NBNS packets.

    - --- - - - -
    Parameters:
      -
    • broadcast (boolean) – A boolean flag to indicate if we should setup the listening UDP port in broadcast mode
    • -
    • listen_port (integer) – Specifies the UDP port number to bind to for listening. If zero, OS will automatically select a free port number.
    • -
    -
    -
    - -
    -
    -close()[source]
    -

    Close the underlying and free resources.

    -

    The NetBIOS instance should not be used to perform any operations after this method returns.

    - --- - - - -
    Returns:None
    -
    - -
    -
    -queryIPForName(ip, port=137, timeout=30)[source]
    -

    Send a query to the machine with ip and hopes that the machine will reply back with its name.

    -

    The implementation of this function is contributed by Jason Anderson.

    - --- - - - - - -
    Parameters:
      -
    • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. -If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.
    • -
    • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.
    • -
    • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None
    • -
    -
    Returns:

    A list of string containing the names of the machine at ip. On timeout, returns None.

    -
    -
    - -
    -
    -queryName(name, ip='', port=137, timeout=30)[source]
    -

    Send a query on the network and hopes that if machine matching the name will reply with its IP address.

    - --- - - - - - -
    Parameters:
      -
    • ip (string) – If the NBNSProtocol instance was instianted with broadcast=True, then this parameter can be an empty string. We will leave it to the OS to determine an appropriate broadcast address. -If the NBNSProtocol instance was instianted with broadcast=False, then you should provide a target IP to send the query.
    • -
    • port (integer) – The NetBIOS-NS port (IANA standard defines this port to be 137). You should not touch this parameter unless you know what you are doing.
    • -
    • timeout (integer/float) – Number of seconds to wait for a reply, after which the method will return None
    • -
    -
    Returns:

    A list of IP addresses in dotted notation (aaa.bbb.ccc.ddd). On timeout, returns None.

    -
    -
    - -
    - -
    - - -
    +
    @@ -190,17 +165,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_SMBConnection.html b/docs/html/api/smb_SMBConnection.html index 3caf88c..ef89255 100644 --- a/docs/html/api/smb_SMBConnection.html +++ b/docs/html/api/smb_SMBConnection.html @@ -1,33 +1,22 @@ - - - - + + + + - - - SMBConnection Class — pysmb 1.1.18 documentation - + + + SMBConnection Class — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + - +
    @@ -96,13 +49,13 @@

    Example

    The following illustrates a simple file retrieving implementation.:

    -
    import tempfile
    +
    import tempfile
     from smb.SMBConnection import SMBConnection
     
     # There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
     # client_machine_name can be an arbitary ASCII string
     # server_name should match the remote machine name, or else the connection will be rejected
    -conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
    +conn = SMBConnection(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
     assert conn.connect(server_ip, 139)
     
     file_obj = tempfile.NamedTemporaryFile()
    @@ -122,410 +75,386 @@
     

    Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. Otherwise, it will fallback automatically back to using SMB1 protocol.

    To disable SMB2 protocol in pysmb, set the SUPPORT_SMB2 flag in the smb_structs module to False before creating the SMBConnection instance.:

    -
    from smb import smb_structs
    -smb_structs.SUPPORT_SMB2 = False
    +
    from smb import smb_structs
    +smb_structs.SUPPORT_SMB2 = False
     

    Caveats

      -
    • It is not meant to be used asynchronously.
    • -
    • A single SMBConnection instance should not be used to perform more than one operation concurrently at the same time.
    • -
    • Do not keep a SMBConnection instance “idle” for too long, i.e. keeping a SMBConnection instance but not using it. +
    • It is not meant to be used asynchronously.

    • +
    • A single SMBConnection instance should not be used to perform more than one operation concurrently at the same time.

    • +
    • Do not keep a SMBConnection instance “idle” for too long, i.e. keeping a SMBConnection instance but not using it. Most SMB/CIFS servers have some sort of keepalive mechanism and impose a timeout limit. -If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client.

    • -
    -
    +If the clients fail to respond within the timeout limit, the SMB/CIFS server may disconnect the client.

    + +
    -class smb.SMBConnection.SMBConnection(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)[source]
    -
    +class smb.SMBConnection.SMBConnection(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)[source] +
    -__init__(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)[source]
    +__init__(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)[source]

    Create a new SMBConnection instance.

    username and password are the user credentials required to authenticate the underlying SMB connection with the remote server. +password can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully.

    Note that you need to call connect method to actually establish the SMB connection to the remote server and perform authentication.

    The default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445.

    - --- - - - -
    Parameters:
      -
    • my_name (string) – The local NetBIOS machine name that will identify where this connection is originating from. -You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of \/:*?";|+
    • -
    • remote_name (string) – The NetBIOS machine name of the remote server. -On windows, you can find out the machine name by right-clicking on the “My Computer” and selecting “Properties”. -This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected.
    • -
    • domain (string) – The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string.
    • -
    • use_ntlm_v2 (boolean) – Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. +
      +
      Parameters
      +
        +
      • my_name (string) – The local NetBIOS machine name that will identify where this connection is originating from. +You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of \/:*?";|+

      • +
      • remote_name (string) – The NetBIOS machine name of the remote server. +On windows, you can find out the machine name by right-clicking on the “My Computer” and selecting “Properties”. +This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected.

      • +
      • domain (string) – The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string.

      • +
      • use_ntlm_v2 (boolean) – Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. -Hence, we can only “guess” or try both algorithms. -On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2.

      • -
      • sign_options (int) – Determines whether SMB messages will be signed. Default is SIGN_WHEN_REQUIRED. +Hence, we can only “guess” or try both algorithms. +On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2.

      • +
      • sign_options (int) – Determines whether SMB messages will be signed. Default is SIGN_WHEN_REQUIRED. If SIGN_WHEN_REQUIRED (value=2), SMB messages will only be signed when remote server requires signing. If SIGN_WHEN_SUPPORTED (value=1), SMB messages will be signed when remote server supports signing but not requires signing. -If SIGN_NEVER (value=0), SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

      • -
      • is_direct_tcp (boolean) – Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. -The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139).
      • -
      -
    -
    - -
    +If SIGN_NEVER (value=0), SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

    +
  • is_direct_tcp (boolean) – Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. +The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139).

  • + +
    +
    +
    + +
    -close()[source]
    +close()[source]

    Terminate the SMB connection (if it has been started) and release any sources held by the underlying socket.

    -
    +
    -connect(ip, port=139, sock_family=2, timeout=60)[source]
    +connect(ip, port=139, sock_family=None, timeout=60)[source]

    Establish the SMB connection to the remote SMB/CIFS server.

    You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication.

    - --- - - - -
    Returns:A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise.
    -
    - -
    +
    +
    Parameters
    +
      +
    • port – Defaults to 139. If you are using direct TCP mode (is_direct_tcp=true when creating this SMBConnection instance), use 445.

    • +
    • sock_family – In Python 3.x, use None as we can infer the socket family from the provided ip. In Python 2.x, it must be either socket.AF_INET or socket.AF_INET6.

    • +
    +
    +
    Returns
    +

    A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise.

    +
    +
    +
    + +
    -createDirectory(service_name, path, timeout=30)[source]
    +createDirectory(service_name, path, timeout=30)[source]

    Creates a new directory path on the service_name.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – Contains the name of the shared folder.
    • -
    • path (string/unicode) – The path of the new folder (relative to) the shared folder. -If the path contains non-English characters, an unicode string must be used to pass in the path.
    • -
    -
    Returns:

    None

    -
    -
    - -
    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – Contains the name of the shared folder.

    • +
    • path (string/unicode) – The path of the new folder (relative to) the shared folder. +If the path contains non-English characters, an unicode string must be used to pass in the path.

    • +
    +
    +
    Returns
    +

    None

    +
    +
    +
    + +
    -deleteDirectory(service_name, path, timeout=30)[source]
    +deleteDirectory(service_name, path, timeout=30)[source]

    Delete the empty folder at path on service_name

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – Contains the name of the shared folder.
    • -
    • path (string/unicode) – The path of the to-be-deleted folder (relative to) the shared folder. -If the path contains non-English characters, an unicode string must be used to pass in the path.
    • -
    -
    Returns:

    None

    -
    -
    - -
    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – Contains the name of the shared folder.

    • +
    • path (string/unicode) – The path of the to-be-deleted folder (relative to) the shared folder. +If the path contains non-English characters, an unicode string must be used to pass in the path.

    • +
    +
    +
    Returns
    +

    None

    +
    +
    +
    + +
    -deleteFiles(service_name, path_file_pattern, timeout=30)[source]
    +deleteFiles(service_name, path_file_pattern, delete_matching_folders=False, timeout=30)[source]

    Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – Contains the name of the shared folder.
    • -
    • path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. +

      If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively.

      +
      +
      Parameters
      +
        +
      • service_name (string/unicode) – Contains the name of the shared folder.

      • +
      • path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. -If your path/filename contains non-English characters, you must pass in an unicode string.

      • -
      -
    Returns:

    None

    -
    -
    - -
    +If your path/filename contains non-English characters, you must pass in an unicode string.

    + + +
    Returns
    +

    None

    +
    +
    +
    + +
    -echo(data, timeout=10)[source]
    +echo(data, timeout=10)[source]

    Send an echo command containing data to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same data.

    - --- - - - - - -
    Parameters:data (string) – Data to send to the remote server.
    Returns:The data parameter
    -
    - -
    +
    +
    Parameters
    +

    data (bytes) – Data to send to the remote server. Must be a bytes object.

    +
    +
    Returns
    +

    The data parameter

    +
    +
    +
    + +
    -getAttributes(service_name, path, timeout=30)[source]
    +getAttributes(service_name, path, timeout=30)[source]

    Retrieve information about the file at path on the service_name.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.
    • -
    -
    Returns:

    A smb.base.SharedFile instance containing the attributes of the file.

    -
    -
    - -
    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    • +
    +
    +
    Returns
    +

    A smb.base.SharedFile instance containing the attributes of the file.

    +
    +
    +
    + +
    +
    +getSecurity(service_name, path, timeout=30)[source]
    +

    Retrieve the security descriptor of the file at path on the service_name.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    • +
    +
    +
    Returns
    +

    A smb.security_descriptors.SecurityDescriptor instance containing the security information of the file.

    +
    +
    +
    + +
    -listPath(service_name, path, search=55, pattern='*', timeout=30)[source]
    +listPath(service_name, path, search=65591, pattern='*', timeout=30)[source]

    Retrieve a directory listing of files/folders at path

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – path relative to the service_name where we are interested to learn about its files/sub-folders.
    • -
    • search (integer) – integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py). -The default search value will query for all read-only, hidden, system, archive files and directories.
    • -
    • pattern (string/unicode) – the filter to apply to the results before returning to the client.
    • -
    -
    Returns:

    A list of smb.base.SharedFile instances.

    -
    -
    - -
    +

    For simplicity, pysmb defines a “normal” file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. +It ignores other attributes like compression, indexed, sparse, temporary and encryption.

    +

    Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), +system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files +and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). +If you do not need to include “normal” files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. +SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – path relative to the service_name where we are interested to learn about its files/sub-folders.

    • +
    • search (integer) – integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py).

    • +
    • pattern (string/unicode) – the filter to apply to the results before returning to the client.

    • +
    +
    +
    Returns
    +

    A list of smb.base.SharedFile instances.

    +
    +
    +
    + +
    -listShares(timeout=30)[source]
    +listShares(timeout=30)[source]

    Retrieve a list of shared resources on remote server.

    - --- - - - -
    Returns:A list of smb.base.SharedDevice instances describing the shared resource
    -
    - -
    +
    +
    Returns
    +

    A list of smb.base.SharedDevice instances describing the shared resource

    +
    +
    +
    + +
    -listSnapshots(service_name, path, timeout=30)[source]
    +listSnapshots(service_name, path, timeout=30)[source]

    Retrieve a list of available snapshots (shadow copies) for path.

    Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – path relative to the service_name where we are interested in the list of available snapshots
    • -
    -
    Returns:

    A list of python datetime.DateTime instances in GMT/UTC time zone

    -
    -
    - -
    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – path relative to the service_name where we are interested in the list of available snapshots

    • +
    +
    +
    Returns
    +

    A list of python datetime.DateTime instances in GMT/UTC time zone

    +
    +
    +
    + +
    -rename(service_name, old_path, new_path, timeout=30)[source]
    +rename(service_name, old_path, new_path, timeout=30)[source]

    Rename a file or folder at old_path to new_path shared at service_name. Note that this method cannot be used to rename file/folder across different shared folders

    old_path and new_path are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. If the path contains non-English characters, an unicode string must be used to pass in the path.

    - --- - - - - - -
    Parameters:service_name (string/unicode) – Contains the name of the shared folder.
    Returns:None
    -
    - -
    +
    +
    Parameters
    +

    service_name (string/unicode) – Contains the name of the shared folder.

    +
    +
    Returns
    +

    None

    +
    +
    +
    + +
    -resetFileAttributes(service_name, path_file_pattern, timeout=30)[source]
    +resetFileAttributes(service_name, path_file_pattern, file_attributes=128, timeout=30)[source]

    Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. -Note: this function is currently only implemented for SMB2! Technically, it sets the FILE_ATTRIBUTE_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information)

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – Contains the name of the shared folder.
    • -
    • path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. +By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. +(See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information)

      +

      Note: this function is currently only implemented for SMB2!

      +
      +
      Parameters
      +
        +
      • service_name (string/unicode) – Contains the name of the shared folder.

      • +
      • path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. -If your path/filename contains non-English characters, you must pass in an unicode string.

      • -
      -
    Returns:

    None

    -
    -
    - -
    +If your path/filename contains non-English characters, you must pass in an unicode string.

    +
  • file_attributes (int) – The desired file attributes to set. Defaults to ATTR_NORMAL.

  • + + +
    Returns
    +

    None

    +
    +
    +
    + +
    -retrieveFile(service_name, path, file_obj, timeout=30)[source]
    +retrieveFile(service_name, path, file_obj, timeout=30)[source]

    Retrieve the contents of the file at path on the service_name and write these contents to the provided file_obj.

    Use retrieveFileFromOffset() method if you wish to specify the offset to read from the remote path and/or the number of bytes to write to the file_obj.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.
    • -
    • file_obj – A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service.
    • -
    -
    Returns:

    A 2-element tuple of ( file attributes of the file on server, number of bytes written to file_obj ). +

    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    • +
    • file_obj – A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.

    • +
    +
    +
    Returns
    +

    A 2-element tuple of ( file attributes of the file on server, number of bytes written to file_obj ). The file attributes is an integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py)

    -
    -
    - -
    + +
    + + +
    -retrieveFileFromOffset(service_name, path, file_obj, offset=0L, max_length=-1L, timeout=30)[source]
    +retrieveFileFromOffset(service_name, path, file_obj, offset=0, max_length=- 1, timeout=30)[source]

    Retrieve the contents of the file at path on the service_name and write these contents to the provided file_obj.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.
    • -
    • file_obj – A file-like object that has a write method. Data will be written continuously to file_obj up to max_length number of bytes.
    • -
    • offset (integer/long) – the offset in the remote path where the first byte will be read and written to file_obj. Must be either zero or a positive integer/long value.
    • -
    • max_length (integer/long) – maximum number of bytes to read from the remote path and write to the file_obj. Specify a negative value to read from offset to the EOF. -If zero, the method returns immediately after the file is opened successfully for reading.
    • -
    -
    Returns:

    A 2-element tuple of ( file attributes of the file on server, number of bytes written to file_obj ). +

    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    • +
    • file_obj – A file-like object that has a write method. Data will be written continuously to file_obj up to max_length number of bytes. In Python3, this file-like object must have a write method which accepts a bytes parameter.

    • +
    • offset (integer/long) – the offset in the remote path where the first byte will be read and written to file_obj. Must be either zero or a positive integer/long value.

    • +
    • max_length (integer/long) – maximum number of bytes to read from the remote path and write to the file_obj. Specify a negative value to read from offset to the EOF. +If zero, the method returns immediately after the file is opened successfully for reading.

    • +
    +
    +
    Returns
    +

    A 2-element tuple of ( file attributes of the file on server, number of bytes written to file_obj ). The file attributes is an integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py)

    -
    -
    - -
    + +
    + + +
    -storeFile(service_name, path, file_obj, timeout=30)[source]
    +storeFile(service_name, path, file_obj, timeout=30)[source]

    Store the contents of the file_obj at path on the service_name. If the file already exists on the remote server, it will be truncated and overwritten.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. Otherwise, it will be overwritten. -If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be raised.
    • -
    • file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF.
    • -
    -
    Returns:

    Number of bytes uploaded

    -
    -
    - -
    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. Otherwise, it will be overwritten. +If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be raised.

    • +
    • file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF. In Python3, this file-like object must have a read method which returns a bytes parameter.

    • +
    +
    +
    Returns
    +

    Number of bytes uploaded

    +
    +
    +
    + +
    -storeFileFromOffset(service_name, path, file_obj, offset=0L, truncate=False, timeout=30)[source]
    +storeFileFromOffset(service_name, path, file_obj, offset=0, truncate=False, timeout=30)[source]

    Store the contents of the file_obj at path on the service_name.

    - --- - - - - - -
    Parameters:
      -
    • service_name (string/unicode) – the name of the shared folder for the path
    • -
    • path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. -If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be raised.
    • -
    • file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF.
    • -
    • offset – Long integer value which specifies the offset in the remote server to start writing. First byte of the file is 0.
    • -
    • truncate – Boolean value. If True and the file exists on the remote server, it will be truncated first before writing. Default is False.
    • -
    -
    Returns:

    the file position where the next byte will be written.

    -
    -
    - -
    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. +If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be raised.

    • +
    • file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF.

    • +
    • offset – Long integer value which specifies the offset in the remote server to start writing. First byte of the file is 0.

    • +
    • truncate – Boolean value. If True and the file exists on the remote server, it will be truncated first before writing. Default is False.

    • +
    +
    +
    Returns
    +

    the file position where the next byte will be written.

    +
    +
    +
    + +
    -SIGN_NEVER = 0
    -

    SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

    -
    - -
    +SIGN_NEVER = 0 +

    SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

    +
    + +
    -SIGN_WHEN_REQUIRED = 2
    +SIGN_WHEN_REQUIRED = 2

    SMB messages will only be signed when remote server requires signing.

    -
    +
    -SIGN_WHEN_SUPPORTED = 1
    +SIGN_WHEN_SUPPORTED = 1

    SMB messages will be signed when remote server supports signing but not requires signing.

    -
    +
    -isUsingSMB2
    +property isUsingSMB2

    A convenient property to return True if the underlying SMB connection is using SMB2 protocol.

    @@ -535,7 +464,45 @@
    +
    +
    +
    +
    @@ -547,17 +514,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_SMBHandler.html b/docs/html/api/smb_SMBHandler.html index e4aaf64..6142961 100644 --- a/docs/html/api/smb_SMBHandler.html +++ b/docs/html/api/smb_SMBHandler.html @@ -1,33 +1,22 @@ - + - + - - - SMbHandler Class — pysmb 1.1.18 documentation - + + + SMbHandler Class — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + +
    + +
    +
    +
    +
    + +
    +

    SMbHandler Class

    +

    The SMBHandler class provides support for “smb://” URLs in the urllib2 python package.

    +
    +

    Notes

    +
      +
    • The host component of the URL must be one of the following:

      +
        +
      • A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com

      • +
      • An IP address. Example: 192.168.1.1

      • +
      • A comma-separated string “<NBName>,<IP>” where <NBName> is the Windows/NetBIOS machine name for remote SMB service, and <IP> is the service’s IP address. Example: MYSERVER,192.168.1.1

      • +
      +
    • +
    • The first component of the path in the URL points to the name of the shared folder. +Subsequent path components will point to the directory/folder of the file.

    • +
    • You can retrieve and upload files, but you cannot delete files/folders or create folders. +In uploads, if the parent folders do not exist, an urllib2.URLError will be raised.

    • +
    +
    +
    +

    Example

    +

    The following code snippet illustrates file retrieval with Python 2.:

    +
    # -*- coding: utf-8 -*-
    +import urllib2
    +from smb.SMBHandler import SMBHandler
    +
    +director = urllib2.build_opener(SMBHandler)
    +fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt')
    +
    +# Process fh like a file-like object and then close it.
    +fh.close()
    +
    +# For paths/files with unicode characters, simply pass in the URL as an unicode string
    +fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat')
    +
    +# Process fh2 like a file-like object and then close it.
    +fh2.close()
    +
    +
    +

    The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the data parameter in the open() method:

    +
    import urllib2
    +from smb.SMBHandler import SMBHandler
    +
    +file_fh = open('local_file.dat', 'rb')
    +
    +director = urllib2.build_opener(SMBHandler)
    +fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh)
    +
    +# Reading from fh will only return an empty string
    +fh.close()
    +
    +
    +

    The following code snippet illustrates file retrieval with Python 3.:

    +
    import urllib
    +from smb.SMBHandler import SMBHandler
    +
    +director = urllib.request.build_opener(SMBHandler)
    +fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt')
    +
    +# Process fh like a file-like object and then close it.
    +fh.close()
    +
    +# For paths/files with unicode characters, simply pass in the URL as an unicode string
    +fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat')
    +
    +# Process fh2 like a file-like object and then close it.
    +fh2.close()
    +
    +
    +

    The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the data parameter in the open() method:

    +
    import urllib
    +from smb.SMBHandler import SMBHandler
    +
    +file_fh = open('local_file.dat', 'rb')
    +
    +director = urllib.request.build_opener(SMBHandler)
    +fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh)
    +
    +# Reading from fh will only return an empty string
    +fh.close()
    +
    +
    +
    +
    + + +
    +
    +
    +
    - -
    -
    -
    -
    - -
    -

    SMbHandler Class

    -

    The SMBHandler class provides support for “smb://” URLs in the urllib2 python package.

    -
    -

    Notes

    -
      -
    • Note that you need to pass in a valid hostname or IP address for the host component of the URL. -Do not use the Windows/NetBIOS machine name for the host component.
    • -
    • The first component of the path in the URL points to the name of the shared folder. -Subsequent path components will point to the directory/folder of the file.
    • -
    • You can retrieve and upload files, but you cannot delete files/folders or create folders. -In uploads, if the parent folders do not exist, an urllib2.URLError will be raised.
    • -
    -
    -
    -

    Example

    -

    The following code snippet illustrates file retrieval.:

    -
    # -*- coding: utf-8 -*-
    -import urllib2
    -from smb.SMBHandler import SMBHandler
    -
    -director = urllib2.build_opener(SMBHandler)
    -fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt')
    -
    -# Process fh like a file-like object and then close it.
    -fh.close()
    -
    -# For paths/files with unicode characters, simply pass in the URL as an unicode string
    -fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat')
    -
    -# Process fh2 like a file-like object and then close it.
    -fh2.close()
    -
    -
    -

    The following code snippet illustrates file upload. You need to provide a file-like object for the data parameter in the open() method:

    -
    import urllib2
    -from smb.SMBHandler import SMBHandler
    -
    -file_fh = open('local_file.dat', 'rb')
    -
    -director = urllib2.build_opener(SMBHandler)
    -fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh)
    -
    -# Reading from fh will only return an empty string
    -fh.close()
    -
    -
    -
    -
    - - -
    +
    @@ -151,17 +177,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_SMBProtocolFactory.html b/docs/html/api/smb_SMBProtocolFactory.html index def8ac3..e61f1f7 100644 --- a/docs/html/api/smb_SMBProtocolFactory.html +++ b/docs/html/api/smb_SMBProtocolFactory.html @@ -1,33 +1,22 @@ - - - - + + + + - - - SMBProtocolFactory Class — pysmb 1.1.18 documentation - + + + SMBProtocolFactory Class — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + +
    + +
    +
    +
    +
    + +
    +

    SMBProtocolFactory Class

    +

    For those who want to utilize pysmb in Twisted framework, pysmb has a smb.SMBProtocol.SMBProtocol implementation. +In most cases, you do not need to touch or import the SMBProtocol directly. All the SMB functionalities are exposed in the SMBProtocolFactory.

    +
    +
    In your project,
      +
    1. Create a new class and subclass SMBProtocolFactory.

    2. +
    3. Override the SMBProtocolFactory.onAuthOK and SMBProtocolFactory.onAuthFailed instance methods to provide your own post-authenthentication handling. +Once SMBProtocolFactory.onAuthOK has been called by pymsb internals, your application is ready to communicate with the remote SMB/CIFS service through +the SMBProtocolFactory public methods such as SMBProtocolFactory.storeFile, SMBProtocolFactory.retrieveFile, etc.

    4. +
    5. When you want to disconnect from the remote SMB/CIFS server, just call SMBProtocolFactory.closeConnection method.

    6. +
    +
    +
    +

    All the SMBProtocolFactory public methods that provide file functionlities will return a twisted.internet.defer.Deferred instance. +A NotReadyError exception is raised when the underlying SMB is not authenticated. +If the underlying SMB connection has been terminated, a NotConnectedError exception is raised.

    +

    All the file operation methods in SMBProtocolFactory class accept a timeout parameter. This parameter specifies the time limit where pysmb will wait for the +entire file operation (except storeFile and retrieveFile methods) to complete. If the file operation fails to complete within the timeout period, the returned +Deferred instance’s errback method will be called with a SMBTimeout exception.

    +

    If you are interested in learning the results of the operation or to know when the operation has completed, you should +add a handling method to the returned Deferred instance via Deferred.addCallback. If the file operation fails, the Deferred.errback function will be called +with an OperationFailure; on timeout, it will be called with a SMBTimeout.

    +
    +

    Example

    +

    The following illustrates a simple file retrieving implementation.:

    +
    import tempfile
    +from twisted.internet import reactor
    +from smb.SMBProtocol import SMBProtocolFactory
    +
    +class RetrieveFileFactory(SMBProtocolFactory):
    +
    +    def __init__(self, *args, **kwargs):
    +        SMBProtocolFactory.__init__(self, *args, **kwargs)
    +
    +    def fileRetrieved(self, write_result):
    +        file_obj, file_attributes, file_size = write_result
    +
    +        # Retrieved file contents are inside file_obj
    +        # Do what you need with the file_obj and then close it
    +        # Note that the file obj is positioned at the end-of-file,
    +        # so you might need to perform a file_obj.seek() to if you
    +        # need to read from the beginning
    +        file_obj.close()
    +
    +        self.transport.loseConnection()
    +
    +    def onAuthOK(self):
    +        d = self.retrieveFile(self.service, self.path, tempfile.NamedTemporaryFile())
    +        d.addCallback(self.fileRetrieved)
    +        d.addErrback(self.d.errback)
    +
    +    def onAuthFailed(self):
    +        print 'Auth failed'
    +
    +# There will be some mechanism to capture userID, password, client_machine_name, server_name and server_ip
    +# client_machine_name can be an arbitary ASCII string
    +# server_name should match the remote machine name, or else the connection will be rejected
    +factory = RetrieveFileFactory(userID, password, client_machine_name, server_name, use_ntlm_v2 = True)
    +factory.service = 'smbtest'
    +factory.path = '/rfc1001.txt'
    +reactor.connectTCP(server_ip, 139, factory)
    +
    +
    +
    +
    +

    SMB2 Support

    +

    Starting from pysmb 1.1.0, pysmb will utilize SMB2 protocol for communication if the remote SMB/CIFS service supports SMB2. +Otherwise, it will fallback automatically back to using SMB1 protocol.

    +

    To disable SMB2 protocol in pysmb, set the SUPPORT_SMB2 flag in the smb_structs module to False before creating the SMBProtocolFactory instance.:

    +
    from smb import smb_structs
    +smb_structs.SUPPORT_SMB2 = False
    +
    +
    +
    +
    +

    Caveats

    +
      +
    • A new factory instance must be created for each SMB connection to the remote SMB/CIFS service. Avoid reusing the same factory instance for more than one SMB connection.

    • +
    • The remote SMB/CIFS server usually imposes a limit of the number of concurrent file operations for each client. For example, to transfer a thousand files, you may need to setup a queue in your application and call storeFile or retrieveFile in batches.

    • +
    • The timeout parameter in the file operation methods are not precise; it is accurate to within 1 second interval, i.e. with a timeout of 0.5 sec, pysmb might raise +SMBTimeout exception after 1.5 sec.

    • +
    +
    +
    +class smb.SMBProtocol.SMBProtocolFactory(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)[source]
    +
    +
    +protocol
    +

    alias of smb.SMBProtocol.SMBProtocol

    +
    + +
    +
    +__init__(username, password, my_name, remote_name, domain='', use_ntlm_v2=True, sign_options=2, is_direct_tcp=False)[source]
    +

    Create a new SMBProtocolFactory instance. You will pass this instance to reactor.connectTCP() which will then instantiate the TCP connection to the remote SMB/CIFS server. +Note that the default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139. +Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445.

    +

    username and password are the user credentials required to authenticate the underlying SMB connection with the remote server. +File operations can only be proceeded after the connection has been authenticated successfully.

    +
    +
    Parameters
    +
      +
    • my_name (string) – The local NetBIOS machine name that will identify where this connection is originating from. +You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of \/:*?";|+

    • +
    • remote_name (string) – The NetBIOS machine name of the remote server. +On windows, you can find out the machine name by right-clicking on the “My Computer” and selecting “Properties”. +This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected.

    • +
    • domain (string) – The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string.

    • +
    • use_ntlm_v2 (boolean) – Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication. +The choice of NTLMv1 and NTLMv2 is configured on the remote server, and there is no mechanism to auto-detect which algorithm has been configured. +Hence, we can only “guess” or try both algorithms. +On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2.

    • +
    • sign_options (int) – Determines whether SMB messages will be signed. Default is SIGN_WHEN_REQUIRED. +If SIGN_WHEN_REQUIRED (value=2), SMB messages will only be signed when remote server requires signing. +If SIGN_WHEN_SUPPORTED (value=1), SMB messages will be signed when remote server supports signing but not requires signing. +If SIGN_NEVER (value=0), SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

    • +
    • is_direct_tcp (boolean) – Controls whether the NetBIOS over TCP/IP (is_direct_tcp=False) or the newer Direct hosting of SMB over TCP/IP (is_direct_tcp=True) will be used for the communication. +The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139).

    • +
    +
    +
    +
    + +
    +
    +buildProtocol(addr)[source]
    +

    Create an instance of a subclass of Protocol.

    +

    The returned instance will handle input on an incoming server +connection, and an attribute “factory” pointing to the creating +factory.

    +

    Alternatively, L{None} may be returned to immediately close the +new connection.

    +

    Override this method to alter how Protocol instances get created.

    +

    @param addr: an object implementing L{twisted.internet.interfaces.IAddress}

    +
    + +
    +
    +closeConnection()[source]
    +

    Disconnect from the remote SMB/CIFS server. The TCP connection will be closed at the earliest opportunity after this method returns.

    +
    +
    Returns
    +

    None

    +
    +
    +
    + +
    +
    +createDirectory(service_name, path)[source]
    +

    Creates a new directory path on the service_name.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – Contains the name of the shared folder.

    • +
    • path (string/unicode) – The path of the new folder (relative to) the shared folder. +If the path contains non-English characters, an unicode string must be used to pass in the path.

    • +
    • timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with the path parameter.

    +
    +
    +
    + +
    +
    +deleteDirectory(service_name, path)[source]
    +

    Delete the empty folder at path on service_name

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – Contains the name of the shared folder.

    • +
    • path (string/unicode) – The path of the to-be-deleted folder (relative to) the shared folder. +If the path contains non-English characters, an unicode string must be used to pass in the path.

    • +
    • timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with the path parameter.

    +
    +
    +
    + +
    +
    +deleteFiles(service_name, path_file_pattern, delete_matching_folders=False, timeout=30)[source]
    +

    Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request.

    +

    If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – Contains the name of the shared folder.

    • +
    • path_file_pattern (string/unicode) – The pathname of the file(s) to be deleted, relative to the service_name. +Wildcards may be used in th filename component of the path. +If your path/filename contains non-English characters, you must pass in an unicode string.

    • +
    • timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with the path_file_pattern parameter.

    +
    +
    +
    + +
    +
    +echo(data, timeout=10)[source]
    +

    Send an echo command containing data to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same data.

    +
    +
    Parameters
    +
      +
    • data (bytes) – Data to send to the remote server. Must be a bytes object.

    • +
    • timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with the data parameter.

    +
    +
    +
    + +
    +
    +getAttributes(service_name, path, timeout=30)[source]
    +

    Retrieve information about the file at path on the service_name.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be raised.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a smb.base.SharedFile instance containing the attributes of the file.

    +
    +
    +
    + +
    +
    +listPath(service_name, path, search=65591, pattern='*', timeout=30)[source]
    +

    Retrieve a directory listing of files/folders at path

    +

    For simplicity, pysmb defines a “normal” file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. +It ignores other attributes like compression, indexed, sparse, temporary and encryption.

    +

    Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), +system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files +and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). +If you do not need to include “normal” files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. +SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – path relative to the service_name where we are interested to learn about its files/sub-folders.

    • +
    • search (integer) – integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py).

    • +
    • pattern (string/unicode) – the filter to apply to the results before returning to the client.

    • +
    • timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a list of smb.base.SharedFile instances.

    +
    +
    +
    + +
    +
    +listShares(timeout=30)[source]
    +

    Retrieve a list of shared resources on remote server.

    +
    +
    Parameters
    +

    timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a list of smb.base.SharedDevice instances.

    +
    +
    +
    + +
    +
    +listSnapshots(service_name, path, timeout=30)[source]
    +

    Retrieve a list of available snapshots (a.k.a. shadow copies) for path.

    +

    Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – path relative to the service_name where we are interested in the list of available snapshots

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a list of python datetime.DateTime +instances in GMT/UTC time zone

    +
    +
    +
    + +
    +
    +onAuthFailed()[source]
    +

    Override this method in your SMBProtocolFactory subclass to add in post-authentication handling. +This method will be called when the server has replied that the SMB connection has been successfully authenticated.

    +
    +
    If you want to retry authenticating from this method,
      +
    1. Disconnect the underlying SMB connection (call self.instance.transport.loseConnection())

    2. +
    3. Create a new SMBProtocolFactory subclass instance with different user credientials or different NTLM algorithm flag.

    4. +
    5. Call reactor.connectTCP with the new instance to re-establish the SMB connection

    6. +
    +
    +
    +
    + +
    +
    +onAuthOK()[source]
    +

    Override this method in your SMBProtocolFactory subclass to add in post-authentication handling. +This method will be called when the server has replied that the SMB connection has been successfully authenticated. +File operations can proceed when this method has been called.

    +
    + +
    +
    +rename(service_name, old_path, new_path)[source]
    +

    Rename a file or folder at old_path to new_path shared at service_name. Note that this method cannot be used to rename file/folder across different shared folders

    +

    old_path and new_path are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder. +If the path contains non-English characters, an unicode string must be used to pass in the path.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – Contains the name of the shared folder.

    • +
    • timeout (integer/float) – Number of seconds that pysmb will wait before raising SMBTimeout via the returned Deferred instance’s errback method.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a 2-element tuple of ( old_path, new_path ).

    +
    +
    +
    + +
    +
    +retrieveFile(service_name, path, file_obj, timeout=30)[source]
    +

    Retrieve the contents of the file at path on the service_name and write these contents to the provided file_obj.

    +

    Use retrieveFileFromOffset() method if you need to specify the offset to read from the remote path and/or the maximum number of bytes to write to the file_obj.

    +

    The meaning of the timeout parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size +of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). +The timeout parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be called in the returned Deferred errback.

    • +
    • file_obj – A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a 3-element tuple of ( file_obj, file attributes of the file on server, number of bytes written to file_obj ). +The file attributes is an integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py)

    +
    +
    +
    + +
    +
    +retrieveFileFromOffset(service_name, path, file_obj, offset=0, max_length=- 1, timeout=30)[source]
    +

    Retrieve the contents of the file at path on the service_name and write these contents to the provided file_obj.

    +

    The meaning of the timeout parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size +of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes). +The timeout parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and downloaded from the remote SMB/CIFS server.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file cannot be opened for reading, an OperationFailure will be called in the returned Deferred errback.

    • +
    • file_obj – A file-like object that has a write method. Data will be written continuously to file_obj until EOF is received from the remote service. In Python3, this file-like object must have a write method which accepts a bytes parameter.

    • +
    • offset (integer/long) – the offset in the remote path where the first byte will be read and written to file_obj. Must be either zero or a positive integer/long value.

    • +
    • max_length (integer/long) – maximum number of bytes to read from the remote path and write to the file_obj. Specify a negative value to read from offset to the EOF. +If zero, the Deferred callback is invoked immediately after the file is opened successfully for reading.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a 3-element tuple of ( file_obj, file attributes of the file on server, number of bytes written to file_obj ). +The file attributes is an integer value made up from a bitwise-OR of SMB_FILE_ATTRIBUTE_xxx bits (see smb_constants.py)

    +
    +
    +
    + +
    +
    +storeFile(service_name, path, file_obj, timeout=30)[source]
    +

    Store the contents of the file_obj at path on the service_name.

    +

    The meaning of the timeout parameter will be different from other file operation methods. As the uploaded file usually exceeeds the maximum size +of each SMB/CIFS data message, it will be packetized into a series of messages (usually about 60kBytes). +The timeout parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and acknowledged +by the remote SMB/CIFS server.

    +
    +
    Parameters
    +
      +
    • service_name (string/unicode) – the name of the shared folder for the path

    • +
    • path (string/unicode) – Path of the file on the remote server. If the file at path does not exist, it will be created. Otherwise, it will be overwritten. +If the path refers to a folder or the file cannot be opened for writing, an OperationFailure will be called in the returned Deferred errback.

    • +
    • file_obj – A file-like object that has a read method. Data will read continuously from file_obj until EOF. In Python3, this file-like object must have a read method which returns a bytes parameter.

    • +
    +
    +
    Returns
    +

    A twisted.internet.defer.Deferred instance. The callback function will be called with a 2-element tuple of ( file_obj, number of bytes uploaded ).

    +
    +
    +
    + +
    +
    +SIGN_NEVER = 0
    +

    SMB messages will never be signed regardless of remote server’s configurations; access errors will occur if the remote server requires signing.

    +
    + +
    +
    +SIGN_WHEN_REQUIRED = 2
    +

    SMB messages will only be signed when remote server requires signing.

    +
    + +
    +
    +SIGN_WHEN_SUPPORTED = 1
    +

    SMB messages will be signed when remote server supports signing but not requires signing.

    +
    + +
    +
    +instance
    +

    The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly.

    +
    + +
    +
    +property isReady
    +

    A convenient property to return True if the underlying SMB connection has connected to remote server, has successfully authenticated itself and is ready for file operations.

    +
    + +
    +
    +property isUsingSMB2
    +

    A convenient property to return True if the underlying SMB connection is using SMB2 protocol.

    +
    + +
    + +
    +
    + + +
    +
    +
    +
    @@ -586,17 +548,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_SharedDevice.html b/docs/html/api/smb_SharedDevice.html index c13b6d0..8b1b3f1 100644 --- a/docs/html/api/smb_SharedDevice.html +++ b/docs/html/api/smb_SharedDevice.html @@ -1,33 +1,22 @@ - + - + - - - SharedDevice Class — pysmb 1.1.18 documentation - + + + SharedDevice Class — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + +
    + +
    +
    +
    +
    + +
    +

    SharedDevice Class

    +
    +
    +class smb.base.SharedDevice(type, name, comments)[source]
    +

    Contains information about a single shared device on the remote server.

    +

    The following attributes are available:

    +
      +
    • name : An unicode string containing the name of the shared device

    • +
    • comments : An unicode string containing the user description of the shared device

    • +
    +
    +
    +comments
    +

    An unicode string containing the user description of the shared device

    +
    + +
    +
    +property isSpecial
    +

    Returns True if this shared device is a special share reserved for interprocess communication (IPC$) +or remote administration of the server (ADMIN$). Can also refer to administrative shares such as +C$, D$, E$, and so forth

    +
    + +
    +
    +property isTemporary
    +

    Returns True if this is a temporary share that is not persisted for creation each time the file server initializes.

    +
    + +
    +
    +name
    +

    An unicode string containing the name of the shared device

    +
    + +
    +
    +property type
    +
    +
    Returns one of the following integral constants.
      +
    • SharedDevice.DISK_TREE

    • +
    • SharedDevice.PRINT_QUEUE

    • +
    • SharedDevice.COMM_DEVICE

    • +
    • SharedDevice.IPC

    • +
    +
    +
    +
    + +
    + +
    + + +
    +
    +
    +
    - -
    -
    -
    -
    - -
    -

    SharedDevice Class

    -
    -
    -class smb.base.SharedDevice(type, name, comments)[source]
    -

    Contains information about a single shared device on the remote server.

    -
    -
    -comments = None
    -

    An unicode string containing the user description of the shared device

    -
    - -
    -
    -isSpecial
    -

    Returns True if this shared device is a special share reserved for interprocess communication (IPC$) -or remote administration of the server (ADMIN$). Can also refer to administrative shares such as -C$, D$, E$, and so forth

    -
    - -
    -
    -isTemporary
    -

    Returns True if this is a temporary share that is not persisted for creation each time the file server initializes.

    -
    - -
    -
    -name = None
    -

    An unicode string containing the name of the shared device

    -
    - -
    -
    -type
    -
    -
    Returns one of the following integral constants.
    -
      -
    • SharedDevice.DISK_TREE
    • -
    • SharedDevice.PRINT_QUEUE
    • -
    • SharedDevice.COMM_DEVICE
    • -
    • SharedDevice.IPC
    • -
    -
    -
    -
    - -
    - -
    - - -
    +
    @@ -143,17 +138,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_SharedFile.html b/docs/html/api/smb_SharedFile.html index 7b4e37c..ea3cbc1 100644 --- a/docs/html/api/smb_SharedFile.html +++ b/docs/html/api/smb_SharedFile.html @@ -1,33 +1,22 @@ - - - - + + + + - - - SharedFile Class — pysmb 1.1.18 documentation - + + + SharedFile Class — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + +
    + +
    +
    +
    +
    + +
    +

    SharedFile Class

    +
    +
    +class smb.base.SharedFile(create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None)[source]
    +

    Contain information about a file/folder entry that is shared on the shared device.

    +

    As an application developer, you should not need to instantiate a SharedFile instance directly in your application. +These SharedFile instances are usually returned via a call to listPath method in smb.SMBProtocol.SMBProtocolFactory.

    +

    If you encounter SharedFile instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond +to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains +one of these prohibited characters: “/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details).

    +

    The following attributes are available:

    +
      +
    • create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server

    • +
    • last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server

    • +
    • last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server

    • +
    • last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server

    • +
    • file_size : File size in number of bytes

    • +
    • alloc_size : Total number of bytes allocated to store this file

    • +
    • file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py.

    • +
    • short_name : Unicode string containing the short name of this file (usually in 8.3 notation)

    • +
    • filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters.

    • +
    • file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17

    • +
    +
    +
    +alloc_size
    +

    Total number of bytes allocated to store this file

    +
    + +
    +
    +create_time
    +

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server

    +
    + +
    +
    +file_attributes
    +

    A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py.

    +
    + +
    +
    +file_id
    +

    Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17

    +
    + +
    +
    +file_size
    +

    File size in number of bytes

    +
    + +
    +
    +filename
    +

    Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters.

    +
    + +
    +
    +property isDirectory
    +

    A convenience property to return True if this file resource is a directory on the remote server

    +
    + +
    +
    +property isNormal
    +

    A convenient property to return True if this is a normal file.

    +

    Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. +It ignores other attributes like compression, indexed, sparse, temporary and encryption.

    +
    + +
    +
    +property isReadOnly
    +

    A convenient property to return True if this file resource is read-only on the remote server

    +
    + +
    +
    +last_access_time
    +

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server

    +
    + +
    +
    +last_attr_change_time
    +

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server

    +
    + +
    +
    +last_write_time
    +

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server

    +
    + +
    +
    +short_name
    +

    Unicode string containing the short name of this file (usually in 8.3 notation)

    +
    + +
    + +
    + + +
    +
    +
    +
    - -
    -
    -
    -
    - -
    -

    SharedFile Class

    -
    -
    -class smb.base.SharedFile(create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename)[source]
    -

    Contain information about a file/folder entry that is shared on the shared device.

    -

    As an application developer, you should not need to instantiate a SharedFile instance directly in your application. -These SharedFile instances are usually returned via a call to listPath method in smb.SMBProtocol.SMBProtocolFactory.

    -

    If you encounter SharedFile instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond -to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains -one of these prohibited characters: “/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details).

    -
    -
    -alloc_size = None
    -

    Total number of bytes allocated to store this file

    -
    - -
    -
    -create_time = None
    -

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server

    -
    - -
    -
    -file_attributes = None
    -

    A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3

    -
    - -
    -
    -file_size = None
    -

    File size in number of bytes

    -
    - -
    -
    -filename = None
    -

    Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters.

    -
    - -
    -
    -isDirectory
    -

    A convenient property to return True if this file resource is a directory on the remote server

    -
    - -
    -
    -isReadOnly
    -

    A convenient property to return True if this file resource is read-only on the remote server

    -
    - -
    -
    -last_access_time = None
    -

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server

    -
    - -
    -
    -last_attr_change_time = None
    -

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server

    -
    - -
    -
    -last_write_time = None
    -

    Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server

    -
    - -
    -
    -short_name = None
    -

    Unicode string containing the short name of this file (usually in 8.3 notation)

    -
    - -
    - -
    - - -
    +
    @@ -173,17 +191,21 @@ index
  • + modules |
  • +
  • next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_exceptions.html b/docs/html/api/smb_exceptions.html index aac3042..a23dea1 100644 --- a/docs/html/api/smb_exceptions.html +++ b/docs/html/api/smb_exceptions.html @@ -1,33 +1,22 @@ - + - + - - - SMB Exceptions — pysmb 1.1.18 documentation - + + + SMB Exceptions — pysmb 1.2.7 documentation + - - - - - - - - + + + + + + + - - + - +
    @@ -81,45 +44,73 @@

    SMB Exceptions

    -
    +
    -class smb.base.SMBTimeout[source]
    +class smb.base.SMBTimeout[source]

    Raised when a timeout has occurred while waiting for a response or for a SMB/CIFS operation to complete.

    -
    +
    -class smb.base.NotReadyError[source]
    +class smb.base.NotReadyError[source]

    Raised when SMB connection is not ready (i.e. not authenticated or authentication failed)

    -
    +
    -class smb.base.NotConnectedError[source]
    +class smb.base.NotConnectedError[source]

    Raised when underlying SMB connection has been disconnected or not connected yet

    -
    +
    -class smb.smb_structs.UnsupportedFeature[source]
    +class smb.smb_structs.UnsupportedFeature[source]

    Raised when an supported feature is present/required in the protocol but is not currently supported by pysmb

    -
    +
    -class smb.smb_structs.ProtocolError(message, data_buf=None, smb_message=None)[source]
    +class smb.smb_structs.ProtocolError(message, data_buf=None, smb_message=None)[source]
    -
    +
    -class smb.smb_structs.OperationFailure(message, smb_messages)[source]
    +class smb.smb_structs.OperationFailure(message, smb_messages)[source]
    +
    +
    +
    +
    @@ -131,17 +122,21 @@ index
  • - modules |
  • +
  • + next |
  • previous |
  • - + +
    diff --git a/docs/html/api/smb_security_descriptors.html b/docs/html/api/smb_security_descriptors.html new file mode 100644 index 0000000..8350674 --- /dev/null +++ b/docs/html/api/smb_security_descriptors.html @@ -0,0 +1,252 @@ + + + + + + + + Security Descriptors — pysmb 1.2.7 documentation + + + + + + + + + + + + + +
    +
    +
    +
    + +
    +

    Security Descriptors

    +

    This module implements security descriptors, and associated data +structures, as specified in [MS-DTYP].

    +
    +
    +class smb.security_descriptors.SID(revision, identifier_authority, subauthorities)[source]
    +

    A Windows security identifier. Represents a single principal, such a +user or a group, as a sequence of numbers consisting of the revision, +identifier authority, and a variable-length list of subauthorities.

    +

    See [MS-DTYP]: 2.4.2

    +
    +
    +identifier_authority
    +

    An integer representing the identifier authority.

    +
    + +
    +
    +revision
    +

    Revision, should always be 1.

    +
    + +
    +
    +subauthorities
    +

    A list of integers representing all subauthorities.

    +
    + +
    + +
    +
    +class smb.security_descriptors.ACE(type_, flags, mask, sid, additional_data)[source]
    +

    Represents a single access control entry.

    +

    See [MS-DTYP]: 2.4.4

    +
    +
    +additional_data
    +

    A dictionary of additional fields present in the ACE, depending +on the type. The following fields can be present:

    +
      +
    • flags

    • +
    • object_type

    • +
    • inherited_object_type

    • +
    • application_data

    • +
    • attribute_data

    • +
    +
    + +
    +
    +flags
    +

    An integer bitmask with ACE flags, corresponds to the +AceFlags field.

    +
    + +
    +
    +property isInheritOnly
    +

    Convenience property which indicates if this ACE is inherit +only, meaning that it doesn’t apply to the object itself.

    +
    + +
    +
    +mask
    +

    An integer representing the ACCESS_MASK as specified in +[MS-DTYP] 2.4.3.

    +
    + +
    +
    +sid
    +

    The SID of a trustee.

    +
    + +
    +
    +type
    +

    An integer representing the type of the ACE. One of the +ACE_TYPE_* constants. Corresponds to the AceType field +from [MS-DTYP] 2.4.4.1.

    +
    + +
    + +
    +
    +class smb.security_descriptors.ACL(revision, aces)[source]
    +

    Access control list, encapsulating a sequence of access control +entries.

    +

    See [MS-DTYP]: 2.4.5

    +
    +
    +aces
    +

    List of ACE instances.

    +
    + +
    +
    +revision
    +

    Integer value of the revision.

    +
    + +
    + +
    +
    +class smb.security_descriptors.SecurityDescriptor(flags, owner, group, dacl, sacl)[source]
    +

    Represents a security descriptor.

    +

    See [MS-DTYP]: 2.4.6

    +
    +
    +dacl
    +

    Instance of ACL representing the discretionary access +control list, which specifies access restrictions of an object.

    +
    + +
    +
    +flags
    +

    Integer bitmask of control flags. Corresponds to the +Control field in [MS-DTYP] 2.4.6.

    +
    + +
    +
    +group
    +

    Instance of SID representing the owner group.

    +
    + +
    +
    +owner
    +

    Instance of SID representing the owner user.

    +
    + +
    +
    +sacl
    +

    Instance of ACL representing the system access control +list, which specifies audit logging of an object.

    +
    + +
    + +
    + + +
    +
    +
    +
    + +
    +
    + + + + \ No newline at end of file diff --git a/docs/html/extending.html b/docs/html/extending.html index 14881f4..b7c5226 100644 --- a/docs/html/extending.html +++ b/docs/html/extending.html @@ -1,32 +1,22 @@ - + - + - - - Extending pysmb For Other Frameworks — pysmb 1.1.18 documentation - + + + Extending pysmb For Other Frameworks — pysmb 1.2.7 documentation + - - - - - - - - - - + + + + + + + + + - +
    @@ -78,20 +48,19 @@

    In general, you need to take care of the SMB TCP connection setup, i.e. finding the IP address of the remote server and connect to the SMB/CIFS service. Then you need to read/write synchronously or asynchronously from and to the SMB socket. And you need to handle post-authentication callback methods, and from these methods, initiate file operations with the remote SMB/CIFS server.

    -
    -
    Now the above steps in more technical details:
    -
      -
    1. Create a new class which subclasses the smb.base.SMB class. Most often, the connection setup will be part of the __init__ method.
    2. -
    3. Override the write(self, data) method to provide an implementation which will write data to the socket.
    4. -
    5. Write your own loop handling method to read data from the socket. Once data have been read, call feedData method with the parameter. -The feedData method has its own internal buffer, so it can accept incomplete NetBIOS session packet data.
    6. -
    7. Override
    8. +
      +
      Now the above steps in more technical details:
        +
      1. Create a new class which subclasses the smb.base.SMB class. Most often, the connection setup will be part of the __init__ method.

      2. +
      3. Override the write(self, data) method to provide an implementation which will write data to the socket.

      4. +
      5. Write your own loop handling method to read data from the socket. Once data have been read, call feedData method with the parameter. +The feedData method has its own internal buffer, so it can accept incomplete NetBIOS session packet data.

      6. +
      7. Override

      -
      +
        -
      • onAuthOK method to include your own operations to perform when authentication is successful. You can initiate file operations in this method.
      • -
      • onAuthFailed method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (use_ntlm_v2 parameter in the constructor).
      • -
      • onNMBSessionFailed method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong remote_name parameter in the constructor.
      • +
      • onAuthOK method to include your own operations to perform when authentication is successful. You can initiate file operations in this method.

      • +
      • onAuthFailed method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (use_ntlm_v2 parameter in the constructor).

      • +
      • onNMBSessionFailed method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong remote_name parameter in the constructor.

      @@ -99,7 +68,35 @@
    +
    + + +
    @@ -111,14 +108,21 @@ index
  • - modules |
  • +
  • + next |
  • +
  • + previous |
  • - + + diff --git a/docs/html/genindex.html b/docs/html/genindex.html index 1e2852b..fc8ee25 100644 --- a/docs/html/genindex.html +++ b/docs/html/genindex.html @@ -1,61 +1,33 @@ - - - - + + + - - - Index — pysmb 1.1.18 documentation - + + + Index — pysmb 1.2.7 documentation + - - - - - - - - - + + + + + + + - +
    @@ -68,6 +40,7 @@
    _ | A + | B | C | D | E @@ -75,6 +48,7 @@ | G | I | L + | M | N | O | P @@ -87,485 +61,436 @@

    _

    - +
    - -
    __init__() (nmb.NetBIOS.NetBIOS method) -
    - -
    - -
    (nmb.NetBIOSProtocol.NBNSProtocol method) -
    - - -
    (smb.SMBConnection.SMBConnection method) -
    - - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -

    A

    - + + +
    - -
    alloc_size (smb.base.SharedFile attribute) -
    - -
    + +

    B

    + +

    C

    - - + +
    - -
    close() (nmb.NetBIOS.NetBIOS method) -
    - -
    - -
    (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    closeConnection() (smb.SMBProtocol.SMBProtocolFactory method) -
    - - -
    comments (smb.base.SharedDevice attribute) -
    - -
    - -
    connect() (smb.SMBConnection.SMBConnection method) -
    - - -
    create_time (smb.base.SharedFile attribute) -
    - - -
    createDirectory() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -

    D

    - - + +
    - -
    deleteDirectory() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -
    - -
    deleteFiles() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -

    E

    - +
    - -
    echo() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -

    F

    - - + +
    - -
    file_attributes (smb.base.SharedFile attribute) -
    - - -
    file_size (smb.base.SharedFile attribute) -
    - -
    - -
    filename (smb.base.SharedFile attribute) -
    - -

    G

    - + +
    - -
    getAttributes() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -

    I

    - - + +
    - -
    instance (smb.SMBProtocol.SMBProtocolFactory attribute) -
    - - -
    isDirectory (smb.base.SharedFile attribute) -
    - - -
    isReadOnly (smb.base.SharedFile attribute) -
    - - -
    isReady (smb.SMBProtocol.SMBProtocolFactory attribute) -
    - -
    - -
    isSpecial (smb.base.SharedDevice attribute) -
    - - -
    isTemporary (smb.base.SharedDevice attribute) -
    - - -
    isUsingSMB2 (smb.SMBConnection.SMBConnection attribute) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory attribute) -
    - -
    -

    L

    - - + + +
    - -
    last_access_time (smb.base.SharedFile attribute) -
    - - -
    last_attr_change_time (smb.base.SharedFile attribute) -
    - - -
    last_write_time (smb.base.SharedFile attribute) -
    - -
    - -
    listPath() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    - -
    listShares() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    - -
    listSnapshots() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -
    + +

    M

    + + +

    N

    - - + +
    - -
    name (smb.base.SharedDevice attribute) -
    - - -
    NBNSProtocol (class in nmb.NetBIOSProtocol) -
    - - -
    NetBIOS (class in nmb.NetBIOS) -
    - -
    - -
    NetBIOSTimeout (class in nmb.NetBIOSProtocol) -
    - - -
    NotConnectedError (class in smb.base) -
    - - -
    NotReadyError (class in smb.base) -
    - -

    O

    - - + +
    - -
    onAuthFailed() (smb.SMBProtocol.SMBProtocolFactory method) -
    - - -
    onAuthOK() (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    - -
    OperationFailure (class in smb.smb_structs) -
    - -

    P

    - + +
    - -
    ProtocolError (class in smb.smb_structs) -
    - -

    Q

    - - + +
    - -
    queryIPForName() (nmb.NetBIOS.NetBIOS method) -
    - -
    - -
    (nmb.NetBIOSProtocol.NBNSProtocol method) -
    - -
    -
    - -
    queryName() (nmb.NetBIOS.NetBIOS method) -
    - -
    - -
    (nmb.NetBIOSProtocol.NBNSProtocol method) -
    - -
    -

    R

    - - + +
    - -
    rename() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    - -
    resetFileAttributes() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    retrieveFile() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    - -
    retrieveFileFromOffset() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    -

    S

    - - + +
    - -
    SharedDevice (class in smb.base) -
    - - -
    SharedFile (class in smb.base) -
    - - -
    short_name (smb.base.SharedFile attribute) -
    - - -
    SIGN_NEVER (smb.SMBConnection.SMBConnection attribute) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory attribute) -
    - -
    - -
    SIGN_WHEN_REQUIRED (smb.SMBConnection.SMBConnection attribute) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory attribute) -
    - -
    - -
    SIGN_WHEN_SUPPORTED (smb.SMBConnection.SMBConnection attribute) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory attribute) -
    - -
    -
    - -
    SMBConnection (class in smb.SMBConnection) -
    - - -
    SMBProtocolFactory (class in smb.SMBProtocol) -
    - - -
    SMBTimeout (class in smb.base) -
    - - -
    storeFile() (smb.SMBConnection.SMBConnection method) -
    - -
    - -
    (smb.SMBProtocol.SMBProtocolFactory method) -
    - -
    - -
    storeFileFromOffset() (smb.SMBConnection.SMBConnection method) -
    - -

    T

    - + +
    - -
    type (smb.base.SharedDevice attribute) -
    - -

    U

    - -
    - -
    UnsupportedFeature (class in smb.smb_structs) -
    - -
    - - - + + + + + +
    +
    + +
    @@ -576,12 +501,16 @@
  • index
  • - +
  • + modules |
  • + + diff --git a/docs/html/index.html b/docs/html/index.html index 614879b..3e546ee 100644 --- a/docs/html/index.html +++ b/docs/html/index.html @@ -1,32 +1,21 @@ - - - - + + + + - - - Welcome to pysmb’s documentation! — pysmb 1.1.18 documentation - + + + Welcome to pysmb’s documentation! — pysmb 1.2.7 documentation + - - - - - - - + + + + + + - - + - +
    @@ -85,11 +39,11 @@
    -

    Welcome to pysmb’s documentation!

    +

    Welcome to pysmb’s documentation!

    pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. -pysmb is developed in Python 2.4.6, Python 2.7.1 and Python 3.2.3 and has been tested against shared folders on Windows XP SP3, Windows Vista, Windows 7 and Samba 3.x.

    -

    The latest version of pysmb is always available at the pysmb project page at miketeo.net.

    +pysmb is developed in Python 2.7.x and Python 3.8.x and has been tested against shared folders on Windows 7, Windows 10 and Samba 4.x.

    +

    The latest version of pysmb is always available at the pysmb project page at miketeo.net.

    License

    pysmb itself is licensed under an opensource license. @@ -103,15 +57,15 @@

    Credits

    pysmb is not alone. It is made possible with support from other modules.

      -
    • pyasn1 : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately)
    • -
    • md4 and U32 : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb.
    • -
    • pyDes : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb.
    • -
    • sha256 : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when -the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm.
    • +
    • pyasn1 : Pure Python implementation of ASN.1 parsing and encoding (not included together with pysmb; needs to be installed separately)

    • +
    • md4 and U32 : Pure Python implementation of MD4 hashing algorithm and 32-bit unsigned integer by Dmitry Rozmanov. Licensed under LGPL and included together with pysmb.

    • +
    • pyDes : Pure Python implementation of the DES encryption algorithm by Todd Whiteman. Free domain and included together with pysmb.

    • +
    • sha256 : Pure Python implementation of SHA-256 message digest by Thomas Dixon. Licensed under MIT and included together with pysmb. This module is imported only when +the Python standard library (usually Python 2.4) does not provide the SHA-256 hash algorithm.

    In various places, there are references to different specifications. Most of these referenced specifications -can be downloaded from Microsoft web site under Microsoft’s “Open Specification Promise”. If you need to download -a copy of these specifications, please google for it. For example, google for “MS-CIFS” to download the CIFS specification for NT LM dialect.

    +can be downloaded from Microsoft web site under Microsoft’s “Open Specification Promise”. If you need to download +a copy of these specifications, please google for it. For example, google for “MS-CIFS” to download the CIFS specification for NT LM dialect.

    @@ -121,56 +75,57 @@ As an application developer, you will be importing this module into your application. Hence, please take some time to familiarize yourself with the smb package contents.

      -
    • nmb/base.py : +
    • nmb/base.py : Contains the NetBIOSSession and NBNS abstract class which implements NetBIOS session and NetBIOS Name Service communication -without any network transport specifics.

    • -
    • nmb/NetBIOS.py: -Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O.
    • -
    • nmb/NetBIOSProtocol.py : -Provides the NBNS protocol implementation for use in Twisted framework.
    • -
    • smb/base.py : -Contains the SMB abstract class which implements the SMB communication without any network transport specifics.
    • -
    • smb/ntlm.py : -Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages.
    • -
    • smb/securityblob.py : -Provides routines to encode/decode the NTLMSSP security blob in the SMB messages.
    • -
    • smb/smb_constants.py : -All the constants used in the smb package for SMB1 protocol
    • -
    • smb/smb_structs.py : -Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message.
    • -
    • smb/smb2_constants.py : -All the constants used in the smb package for SMB2 protocol
    • -
    • smb/smb2_structs.py : -Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message.
    • -
    • smb/SMBConnection.py : -Contains a SMB protocol implementation. All operations are blocking I/O.
    • -
    • smb/SMBProtocol.py : -Contains the SMB protocol implementation for use in the Twisted framework.
    • -
    • smb/SMBHandler.py : -Provides support for “smb://” URL in the urllib2 python package.
    • +without any network transport specifics.

      +
    • nmb/NetBIOS.py: +Provides a NBNS implementation to query IP addresses for machine names. All operations are blocking I/O.

    • +
    • nmb/NetBIOSProtocol.py : +Provides the NBNS protocol implementation for use in Twisted framework.

    • +
    • smb/base.py : +Contains the SMB abstract class which implements the SMB communication without any network transport specifics.

    • +
    • smb/ntlm.py : +Contains the NTLMv1 and NTLMv2 authentication routines and the decoding/encoding of NTLM authentication messages within SMB messages.

    • +
    • smb/securityblob.py : +Provides routines to encode/decode the NTLMSSP security blob in the SMB messages.

    • +
    • smb/smb_constants.py : +All the constants used in the smb package for SMB1 protocol

    • +
    • smb/smb_structs.py : +Contains the internal classes used in the SMB package for SMB1 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB1 message.

    • +
    • smb/smb2_constants.py : +All the constants used in the smb package for SMB2 protocol

    • +
    • smb/smb2_structs.py : +Contains the internal classes used in the SMB package for SMB2 protocol. These classes are usually used to encode/decode the parameter and data blocks of specific SMB2 message.

    • +
    • smb/SMBConnection.py : +Contains a SMB protocol implementation. All operations are blocking I/O.

    • +
    • smb/SMBProtocol.py : +Contains the SMB protocol implementation for use in the Twisted framework.

    • +
    • smb/SMBHandler.py : +Provides support for “smb://” URL in the urllib2 python package.

    Using pysmb

    -
    -
    As an application developer who is looking to use pysmb to translate NetBIOS names to IP addresses,
    -
      -
    • To use pysmb in applications where you want the file operations to return after they have completed (synchronous style), please read -nmb.NetBIOS.NetBIOS documentation.
    • -
    • To use pysmb in Twisted, please read nmb.NetBIOSProtocol.NBNSProtocol documentation.
    • -
    -
    -
    As an application developer who is looking to use pysmb to implement file transfer or authentication over SMB:
    -
    -
    -
    As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks:
    -
    -
    - - +
  • Index

  • +
  • Search Page

  • + +
    + + +
    + + +
    @@ -209,14 +203,18 @@ index
  • + modules |
  • +
  • next |
  • - + + diff --git a/docs/html/objects.inv b/docs/html/objects.inv index 86b3538..1a30b4d 100644 Binary files a/docs/html/objects.inv and b/docs/html/objects.inv differ diff --git a/docs/html/py-modindex.html b/docs/html/py-modindex.html new file mode 100644 index 0000000..6125b80 --- /dev/null +++ b/docs/html/py-modindex.html @@ -0,0 +1,103 @@ + + + + + + + + Python Module Index — pysmb 1.2.7 documentation + + + + + + + + + + + + + + +
    +
    +
    +
    + + +

    Python Module Index

    + +
    + s +
    + + + + + + + + + + +
     
    + s
    + smb +
        + smb.security_descriptors + Data structures used in Windows security descriptors.
    + + +
    +
    +
    +
    + +
    +
    + + + + \ No newline at end of file diff --git a/docs/html/search.html b/docs/html/search.html index 1e29df4..808404c 100644 --- a/docs/html/search.html +++ b/docs/html/search.html @@ -1,52 +1,39 @@ - + - + - + + + Search — pysmb 1.2.7 documentation + + - Search — pysmb 1.1.18 documentation - - - - - - - - - - - - - + + + + + + + + + - - + - +
    @@ -55,20 +42,18 @@

    Search

    - +

    Please activate JavaScript to enable the search functionality.

    - From here you can search these documents. Enter your search - words into the box below and click "search". Note that the search - function will automatically search for all of the words. Pages - containing fewer words won't appear in the result list. + Searching for multiple words only shows matches that contain + all words.

    - +
    @@ -77,7 +62,12 @@
    +
    + + +
    @@ -88,12 +78,16 @@
  • index
  • - +
  • + modules |
  • + + diff --git a/docs/html/searchindex.js b/docs/html/searchindex.js index 0cbc511..19d7824 100644 --- a/docs/html/searchindex.js +++ b/docs/html/searchindex.js @@ -1 +1 @@ -Search.setIndex({envversion:46,filenames:["api/nmb_NBNSProtocol","api/nmb_NetBIOS","api/smb_SMBConnection","api/smb_SMBHandler","api/smb_SMBProtocolFactory","api/smb_SharedDevice","api/smb_SharedFile","api/smb_exceptions","extending","index"],objects:{"nmb.NetBIOS":{NetBIOS:[1,0,1,""]},"nmb.NetBIOS.NetBIOS":{"__init__":[1,1,1,""],close:[1,1,1,""],queryIPForName:[1,1,1,""],queryName:[1,1,1,""]},"nmb.NetBIOSProtocol":{NBNSProtocol:[0,0,1,""],NetBIOSTimeout:[0,0,1,""]},"nmb.NetBIOSProtocol.NBNSProtocol":{"__init__":[0,1,1,""],queryIPForName:[0,1,1,""],queryName:[0,1,1,""]},"smb.SMBConnection":{SMBConnection:[2,0,1,""]},"smb.SMBConnection.SMBConnection":{"__init__":[2,1,1,""],SIGN_NEVER:[2,2,1,""],SIGN_WHEN_REQUIRED:[2,2,1,""],SIGN_WHEN_SUPPORTED:[2,2,1,""],close:[2,1,1,""],connect:[2,1,1,""],createDirectory:[2,1,1,""],deleteDirectory:[2,1,1,""],deleteFiles:[2,1,1,""],echo:[2,1,1,""],getAttributes:[2,1,1,""],isUsingSMB2:[2,2,1,""],listPath:[2,1,1,""],listShares:[2,1,1,""],listSnapshots:[2,1,1,""],rename:[2,1,1,""],resetFileAttributes:[2,1,1,""],retrieveFile:[2,1,1,""],retrieveFileFromOffset:[2,1,1,""],storeFile:[2,1,1,""],storeFileFromOffset:[2,1,1,""]},"smb.SMBProtocol":{SMBProtocolFactory:[4,0,1,""]},"smb.SMBProtocol.SMBProtocolFactory":{"__init__":[4,1,1,""],SIGN_NEVER:[4,2,1,""],SIGN_WHEN_REQUIRED:[4,2,1,""],SIGN_WHEN_SUPPORTED:[4,2,1,""],closeConnection:[4,1,1,""],createDirectory:[4,1,1,""],deleteDirectory:[4,1,1,""],deleteFiles:[4,1,1,""],echo:[4,1,1,""],getAttributes:[4,1,1,""],instance:[4,2,1,""],isReady:[4,2,1,""],isUsingSMB2:[4,2,1,""],listPath:[4,1,1,""],listShares:[4,1,1,""],listSnapshots:[4,1,1,""],onAuthFailed:[4,1,1,""],onAuthOK:[4,1,1,""],rename:[4,1,1,""],retrieveFile:[4,1,1,""],retrieveFileFromOffset:[4,1,1,""],storeFile:[4,1,1,""]},"smb.base":{NotConnectedError:[7,0,1,""],NotReadyError:[7,0,1,""],SMBTimeout:[7,0,1,""],SharedDevice:[5,0,1,""],SharedFile:[6,0,1,""]},"smb.base.SharedDevice":{comments:[5,2,1,""],isSpecial:[5,2,1,""],isTemporary:[5,2,1,""],name:[5,2,1,""],type:[5,2,1,""]},"smb.base.SharedFile":{alloc_size:[6,2,1,""],create_time:[6,2,1,""],file_attributes:[6,2,1,""],file_size:[6,2,1,""],filename:[6,2,1,""],isDirectory:[6,2,1,""],isReadOnly:[6,2,1,""],last_access_time:[6,2,1,""],last_attr_change_time:[6,2,1,""],last_write_time:[6,2,1,""],short_name:[6,2,1,""]},"smb.smb_structs":{OperationFailure:[7,0,1,""],ProtocolError:[7,0,1,""],UnsupportedFeature:[7,0,1,""]}},objnames:{"0":["py","class","Python class"],"1":["py","method","Python method"],"2":["py","attribute","Python attribute"]},objtypes:{"0":"py:class","1":"py:method","2":"py:attribute"},terms:{"3rd":9,"60kbyte":4,"\u5783\u573e\u6587\u4ef6":3,"\u6d4b\u8bd5\u6587\u4ef6\u5939":3,"__init__":[0,1,2,4,8],"abstract":9,"boolean":[0,1,2,4],"byte":[2,4,6],"case":4,"default":[2,4],"float":[0,1,4,6],"function":[0,1,2,4,9],"import":[2,3,4,9],"int":[2,4],"long":[2,4,6],"new":[1,2,4,8],"public":4,"return":[0,1,2,3,4,5,6,9],"short":6,"true":[0,1,2,4,5,6],"try":[2,4,8],"while":7,aaa:[0,1],about:[2,4,5,6],abov:8,accept:[4,8],access:[2,4,6],accur:4,acknowledg:4,across:[2,4],actual:2,add:[0,4],addcallback:[0,4],adderrback:4,address:[0,1,3,8,9],admin:5,administr:5,after:[0,1,2,4,9],again:0,against:9,algorithm:[2,4,8,9],all:[2,4,9],alloc:6,alloc_s:6,allow:[0,2,4],alon:9,alphanumer:[2,4],alreadi:2,also:[2,4,5],alwai:9,anderson:[0,1],ani:[1,2,4,6,9],appli:[2,4],applic:[0,1,4,6,9],appropri:[0,1],arbitari:[2,4],archiv:[2,4],arg:4,around:0,ascii:[2,4],asn:9,aspx:2,assert:2,asynchron:[0,2,8],attempt:2,attribut:[2,4,6],atttempt:2,auth:4,authent:[2,4,7,8,9],authenthent:4,auto:[2,4],automat:[0,1,2,4],avail:[2,4,9],avoid:4,back:[0,1,2,4],base:[2,4,5,6,7,8,9],batch:4,bbb:[0,1],been:[2,4,7,8,9],befor:[2,4],begin:[2,4],between:9,bind:[0,1],bit:[2,4,9],bitwis:[2,4],blob:9,block:[0,1,2,9],both:[2,4],briefli:8,broadcast:[0,1],buffer:8,build_open:3,busi:[2,4],call:[0,1,2,4,6,8],callback:[0,4,8],can:[0,1,2,3,4,5,8,9],cannot:[2,3,4],captur:[2,4],care:8,cc232110:2,ccc:[0,1],chang:6,charact:[2,3,4,6],choic:[2,4],choos:[2,4],cif:[1,2,4,6,7,8,9],clear:2,click:[2,4],client:[2,4,9],client_machine_nam:[2,4],close:[1,2,3,4],closeconnect:4,code:3,com:2,come:9,comm_devic:5,command:[2,4],comment:5,commerci:9,commun:[2,4,5,9],compat:[2,4],complet:[2,4,7,9],compon:[2,3,4],comput:[2,4],concurr:[2,4],configur:[2,4],conflict:9,conn:2,connect:[2,4,7,8],connecttcp:4,constant:[5,9],constructor:8,contain:[1,2,4,5,6,9],content:[2,4],continu:[2,4],contribut:[0,1],control:[2,4],conveni:[2,4,6],copi:[2,4,9],correspond:6,could:[6,9],cover:9,creat:[0,1,2,3,4,8],create_tim:6,createdirectori:[2,4],creation:[5,6],credenti:[2,4],credienti:4,current:[2,7],dat:3,data:[2,3,4,8,9],data_buf:7,datetim:[2,4],ddd:[0,1],decod:9,def:4,defer:[0,4],defin:[0,1],delet:[2,3,4],deletedirectori:[2,4],deletefil:[2,4],depend:9,describ:[2,8],descript:5,detail:[6,8,9],detect:[2,4],determin:[0,1,2,4,9],develop:[2,6,9],devic:[5,6],dialect:9,differ:[2,4,8,9],digest:9,direct:[2,4],directli:[4,6],director:3,directori:[2,3,4,6],disabl:[2,4],disconnect:[2,4,7],discret:9,disk_tre:5,dixon:9,dmitri:9,doe:[2,4,6,9],domain:[2,4,9],done:[0,1],dot:[0,1],download:[4,9],due:8,each:[1,2,4,5,6],earliest:4,echo:[2,4],edit:[2,4],either:[2,4],element:[2,4],els:[2,4],empti:[0,1,2,3,4,6],enabl:[2,4],encod:9,encount:[2,6],encrypt:9,end:[2,4],english:[2,4],enterpris:[2,4],entir:4,entri:6,eof:[2,4],errback:[0,4],error:[2,4,8],establish:[2,4],etc:4,excee:4,except:[0,4],exercis:9,exist:[2,3,4],expos:4,facilit:9,factori:4,fail:[2,4,7,8],failur:0,fallback:[2,4],fals:[0,1,2,4],familiar:9,featur:[2,4,7],feeddata:8,fh2:3,file:[2,3,4,5,6,8,9],file_attribut:[2,4,6],file_attribute_norm:2,file_fh:3,file_obj:[2,4],file_s:[4,6],filenam:[2,4,6],fileretriev:4,files:2,filter:[2,4],find:[2,4,8],first:[2,3,4],flag:[0,1,2,4],folder:[2,3,4,6,9],follow:[2,3,4,5,9],forth:5,framework:[0,4],free:[0,1,9],freeli:[2,4],from:[0,1,2,3,4,8,9],functionl:4,further:2,gener:8,getattribut:[2,4],gmt:[2,4],googl:9,guess:[2,4],handl:[4,8],hash:9,have:[0,2,8,9],held:2,help:2,henc:[2,4,9],hidden:[2,4],hope:[0,1],host:[2,3,4],hostnam:3,http:2,iana:[0,1],identifi:[2,4],idl:2,illustr:[2,3,4],immedi:[2,4],implement:[0,1,2,4,8,9],impos:[2,4],includ:[8,9],incom:0,incomplet:8,index:9,indic:[0,1,2,4],individu:4,inform:[2,4,5,6],initi:[5,8],insid:[2,4],instal:[2,4,9],instanc:[0,1,2,4,6],instanti:[0,1,4,6],instiant:[0,1],integ:[0,1,2,4,6,9],integr:[5,9],interest:[2,4],intern:[4,8,9],internet:[0,4],interprocess:5,interv:4,invok:[2,4],involv:8,ipc:5,ipv4:1,is_direct_tcp:[2,4],isdirectori:6,isreadi:4,isreadonli:6,isspeci:5,istemporari:5,isusingsmb2:[2,4],itself:[4,9],jason:[0,1],just:[0,4],keep:2,keepal:2,know:[0,1,4],known:[2,4],kwarg:4,last:6,last_access_tim:6,last_attr_change_tim:6,last_write_tim:6,latest:9,learn:[2,4],least:2,leav:[0,1,2,4],length:6,lgpl:9,librari:[2,9],like:[2,3,4],limit:[2,4,6],linux:9,list:[0,1,2,4,9],listen:[0,1],listen_port:[0,1],listenudp:0,listpath:[2,4,6],listshar:[2,4],listsnapshot:[2,4],local:[2,4],local_fil:3,look:9,loop:8,loseconnect:4,machin:[0,1,2,3,4,9],made:[2,4,9],mai:[2,4],main:9,match:[0,1,2,4],max_length:[2,4],maximum:[2,4],md4:9,mean:4,meant:2,mechan:[2,4],messag:[2,4,7,9],method:[0,1,2,3,4,6,8],microsoft:[2,9],might:[2,4],miketeo:9,mit:9,mode:[0,1],modif:6,modifi:9,modul:[2,4,9],more:[2,4,6,8,9],most:[2,4,8,9],msdn:2,multipl:[2,4],must:[0,2,4],my_nam:[2,4],mypassword:3,myuserid:3,name:[0,1,2,3,4,5,6,9],namedtemporaryfil:[2,4],nbn:[1,9],need:[2,3,4,6,8,9],neg:[2,4],net:9,netbio:0,netbiosprotocol:[0,9],netbiossess:9,netbiostimeout:0,network:[0,1,2,4,9],never:[2,4],new_path:[2,4],newer:[2,4],next:2,nmb:[0,1,9],non:[2,4],none:[0,1,2,4,5,6,7],notat:[0,1,6],notconnectederror:[4,7],note:2,notreadyerror:[4,7],now:8,ntlm:[4,8,9],ntlmssp:9,ntlmv1:[2,4,9],ntlmv2:[2,4,9],number:[0,1,2,4,6],obj:[2,4],object:[2,3,4],occur:[2,4,7],offset:[2,4],often:8,old:[2,4],old_path:[2,4],onauthfail:[4,8],onauthok:[4,8],onc:[4,8],onli:[2,3,4,6,9],onnmbsessionfail:8,open:[2,3,4,9],opensourc:9,oper:[1,2,4,7,8,9],operationfailur:[2,4,7],opportun:4,organ:9,origin:[2,4,6],other:[2,4],otherwis:[2,4],out:[2,4],over:[2,4,9],overrid:[4,8],overwritten:[2,4],own:[4,8,9],packag:3,packet:[0,1,4,8],page:[8,9],paramet:[0,1,2,3,4,8,9],parent:3,pars:9,part:8,parti:9,pass:[2,3,4],password:[2,4],path:[2,3,4],path_file_pattern:[2,4],pathnam:[2,4],pattern:[2,4],perform:[0,1,2,4,8],period:4,persist:5,place:9,pleas:9,point:3,port:[0,1,2,4],posit:[2,4],possibl:9,post:[4,8],precis:4,present:7,print:[4,9],print_queu:5,proce:4,proceed:[2,4],process:[3,8],prohibit:6,project:[0,4,9],promis:9,properti:[2,4,6],protocol:[2,4,7,9],protocolerror:7,provid:[0,1,2,3,4,8,9],pure:9,purpos:9,pyasn1:9,pyde:9,pymsb:4,pysmb:[0,2,4,7],python:[2,3,4,9],queri:[0,1,2,4,9],queryipfornam:[0,1],querynam:[0,1],queue:4,rais:[0,2,3,4,7],reactor:[0,4],read:[2,3,4,6,8,9],readi:[4,7],receiv:[0,1,2,4],refer:[2,4,5,9],referenc:9,regardless:[2,4],regular:[2,4],reject:[2,4],rel:[2,4],relat:9,releas:[1,2],remot:[1,2,4,5,6,8],remote_nam:[2,4,8],remov:0,renam:[2,4],repli:[0,1,2,4],report:8,request:[2,4],requir:[2,4,7],reserv:5,reset:2,resetfileattribut:2,resourc:[1,2,4,6],respond:2,respons:7,result:[0,2,4],retri:4,retriev:[2,3,4],retrievefil:[2,4],retrievefilefactori:4,retrievefilefromoffset:[2,4],reus:4,rfc1001:[2,3,4],right:[2,4],routin:9,rozmanov:9,safe:[2,4],samba:9,sambda:[2,4],same:[2,4],search:[2,4,9],sec:4,second:[0,1,4,6],section:9,secur:9,securityblob:9,see:[2,4,6],seek:[2,4],select:[0,1,2,4],self:[4,8],send:[0,1,2,4],separ:9,sequenti:2,seri:4,server:[2,4,5,6,8,9],server_ip:[2,4],server_nam:[2,4],servic:[1,2,4,8,9],service_nam:[2,4],session:[8,9],set:[2,4],setup:[0,1,4,8],sha256:9,sha:9,shadow:[2,4],share:[2,3,4,5,6,9],shareddevic:[2,4],sharedfil:[2,4],sharedfold:3,short_nam:6,should:[0,1,2,4,6],side:9,sign:[2,4],sign_nev:[2,4],sign_opt:[2,4],sign_when_requir:[2,4],sign_when_support:[2,4],simpl:[2,4],simpli:3,sinc:6,singl:[2,4,5],site:9,size:[4,6],smb1:[2,4,9],smb2_constant:9,smb2_struct:9,smb:[1,2,3,4,5,6],smb_constant:[2,4,9],smb_ext_file_attr:6,smb_file_attribute_xxx:[2,4],smb_messag:7,smb_struct:[2,4,7,9],smbprotocol:[4,6,9],smbtest:[2,4],smbtimeout:[4,7],snapshot:[2,4],snippet:3,sock_famili:2,socket:[1,2,8],softwar:9,some:[2,4,9],sort:2,sourc:[0,1,2,4,5,6,7,9],sp3:9,space:[2,4],special:5,specif:9,specifi:[0,1,2,4],standard:[0,1,9],start:[0,2,4],step:8,stoplisten:0,store:[2,4,6],storefil:[2,4],storefilefromoffset:2,string:[0,1,2,3,4,5,6],style:9,sub:[2,4],subclass:[4,8],subsequ:3,success:[2,8],successfulli:[2,4],suitabl:[2,9],support_smb2:[2,4],synchron:[8,9],system:[2,4],take:[8,9],target:[0,1],tcp:[2,4,8],technic:[2,8],tempfil:[2,4],temporari:5,term:9,termin:[2,4],test:9,than:[2,4],thei:9,therefor:2,thi:[0,1,2,4,5,6,8,9],thoma:9,those:4,thousand:4,through:4,time:[2,4,5,6,9],timeout:[0,1,2,4,7],todd:9,togeth:9,too:2,total:6,touch:[0,1,4],transfer:[4,9],translat:9,transmit:4,transport:[0,4,9],truncat:2,tupl:[2,4],twist:[0,4,9],txt:[2,3,4],type:5,u32:9,udp:[0,1],ultim:[2,4],under:9,underli:[1,2,4,7,9],unicod:[2,3,4,5,6],unless:[0,1],unlock:2,unsign:9,unsupportedfeatur:7,until:[1,2,4],upload:[2,3,4],upload_fil:3,url:[3,9],urlerror:3,urllib2:[3,9],use_ntlm_v2:[2,4,8],user:[2,4,5],userid:[2,4],usernam:[2,4],usual:[2,4,6,8,9],utc:[2,4],utf:3,util:[2,4],valid:3,valu:[2,4,6],variou:9,veri:2,version:9,via:[0,4,6,9],vista:[2,4,9],wait:[0,1,4,7],want:[4,9],web:9,well:9,what:[0,1,2,4,8],when:[0,1,2,4,7,8,9],where:[2,4,6,9],whether:[2,4],which:[0,1,2,4,6,8,9],whiteman:9,who:[2,4,9],whose:9,wider:[2,4],wildcard:[2,4],window:[2,3,4,6,9],wish:[1,2],within:[2,4,9],without:[0,9],workgroup:[2,4],wrap:0,write:[2,4,8],write_result:4,written:[2,4],wrong:8,yet:7,you:[0,1,2,3,4,6,8,9],your:[0,1,2,4,6,8,9],yourself:9,zero:[0,1,2,4],zone:[2,4]},titles:["NBNSProtocol Class","NetBIOS class","SMBConnection Class","SMbHandler Class","SMBProtocolFactory Class","SharedDevice Class","SharedFile Class","SMB Exceptions","Extending pysmb For Other Frameworks","Welcome to pysmb’s documentation!"],titleterms:{"class":[0,1,2,3,4,5,6],caveat:[2,4],content:9,credit:9,descript:9,document:9,exampl:[2,3,4],except:7,extend:8,framework:8,indic:9,licens:9,nbnsprotocol:0,netbio:1,note:3,other:8,packag:9,pysmb:[8,9],shareddevic:5,sharedfil:6,smb2:[2,4],smb:7,smbconnect:2,smbhandler:3,smbprotocolfactori:4,support:[2,4],tabl:9,welcom:9}}) \ No newline at end of file +Search.setIndex({docnames:["api/nmb_NBNSProtocol","api/nmb_NetBIOS","api/smb_SMBConnection","api/smb_SMBHandler","api/smb_SMBProtocolFactory","api/smb_SharedDevice","api/smb_SharedFile","api/smb_exceptions","api/smb_security_descriptors","extending","index","upgrading"],envversion:{"sphinx.domains.c":2,"sphinx.domains.changeset":1,"sphinx.domains.citation":1,"sphinx.domains.cpp":3,"sphinx.domains.index":1,"sphinx.domains.javascript":2,"sphinx.domains.math":2,"sphinx.domains.python":2,"sphinx.domains.rst":2,"sphinx.domains.std":1,"sphinx.ext.todo":2,"sphinx.ext.viewcode":1,sphinx:56},filenames:["api/nmb_NBNSProtocol.rst","api/nmb_NetBIOS.rst","api/smb_SMBConnection.rst","api/smb_SMBHandler.rst","api/smb_SMBProtocolFactory.rst","api/smb_SharedDevice.rst","api/smb_SharedFile.rst","api/smb_exceptions.rst","api/smb_security_descriptors.rst","extending.rst","index.rst","upgrading.rst"],objects:{"nmb.NetBIOS":{NetBIOS:[1,0,1,""]},"nmb.NetBIOS.NetBIOS":{__init__:[1,1,1,""],close:[1,1,1,""],queryIPForName:[1,1,1,""],queryName:[1,1,1,""]},"nmb.NetBIOSProtocol":{NBNSProtocol:[0,0,1,""],NetBIOSTimeout:[0,0,1,""]},"nmb.NetBIOSProtocol.NBNSProtocol":{__init__:[0,1,1,""],datagramReceived:[0,1,1,""],queryIPForName:[0,1,1,""],queryName:[0,1,1,""],stopProtocol:[0,1,1,""]},"smb.SMBConnection":{SMBConnection:[2,0,1,""]},"smb.SMBConnection.SMBConnection":{SIGN_NEVER:[2,2,1,""],SIGN_WHEN_REQUIRED:[2,2,1,""],SIGN_WHEN_SUPPORTED:[2,2,1,""],__init__:[2,1,1,""],close:[2,1,1,""],connect:[2,1,1,""],createDirectory:[2,1,1,""],deleteDirectory:[2,1,1,""],deleteFiles:[2,1,1,""],echo:[2,1,1,""],getAttributes:[2,1,1,""],getSecurity:[2,1,1,""],isUsingSMB2:[2,1,1,""],listPath:[2,1,1,""],listShares:[2,1,1,""],listSnapshots:[2,1,1,""],rename:[2,1,1,""],resetFileAttributes:[2,1,1,""],retrieveFile:[2,1,1,""],retrieveFileFromOffset:[2,1,1,""],storeFile:[2,1,1,""],storeFileFromOffset:[2,1,1,""]},"smb.SMBProtocol":{SMBProtocolFactory:[4,0,1,""]},"smb.SMBProtocol.SMBProtocolFactory":{SIGN_NEVER:[4,2,1,""],SIGN_WHEN_REQUIRED:[4,2,1,""],SIGN_WHEN_SUPPORTED:[4,2,1,""],__init__:[4,1,1,""],buildProtocol:[4,1,1,""],closeConnection:[4,1,1,""],createDirectory:[4,1,1,""],deleteDirectory:[4,1,1,""],deleteFiles:[4,1,1,""],echo:[4,1,1,""],getAttributes:[4,1,1,""],instance:[4,2,1,""],isReady:[4,1,1,""],isUsingSMB2:[4,1,1,""],listPath:[4,1,1,""],listShares:[4,1,1,""],listSnapshots:[4,1,1,""],onAuthFailed:[4,1,1,""],onAuthOK:[4,1,1,""],protocol:[4,2,1,""],rename:[4,1,1,""],retrieveFile:[4,1,1,""],retrieveFileFromOffset:[4,1,1,""],storeFile:[4,1,1,""]},"smb.base":{NotConnectedError:[7,0,1,""],NotReadyError:[7,0,1,""],SMBTimeout:[7,0,1,""],SharedDevice:[5,0,1,""],SharedFile:[6,0,1,""]},"smb.base.SharedDevice":{comments:[5,2,1,""],isSpecial:[5,1,1,""],isTemporary:[5,1,1,""],name:[5,2,1,""],type:[5,1,1,""]},"smb.base.SharedFile":{alloc_size:[6,2,1,""],create_time:[6,2,1,""],file_attributes:[6,2,1,""],file_id:[6,2,1,""],file_size:[6,2,1,""],filename:[6,2,1,""],isDirectory:[6,1,1,""],isNormal:[6,1,1,""],isReadOnly:[6,1,1,""],last_access_time:[6,2,1,""],last_attr_change_time:[6,2,1,""],last_write_time:[6,2,1,""],short_name:[6,2,1,""]},"smb.security_descriptors":{ACE:[8,0,1,""],ACL:[8,0,1,""],SID:[8,0,1,""],SecurityDescriptor:[8,0,1,""]},"smb.security_descriptors.ACE":{additional_data:[8,2,1,""],flags:[8,2,1,""],isInheritOnly:[8,1,1,""],mask:[8,2,1,""],sid:[8,2,1,""],type:[8,2,1,""]},"smb.security_descriptors.ACL":{aces:[8,2,1,""],revision:[8,2,1,""]},"smb.security_descriptors.SID":{identifier_authority:[8,2,1,""],revision:[8,2,1,""],subauthorities:[8,2,1,""]},"smb.security_descriptors.SecurityDescriptor":{dacl:[8,2,1,""],flags:[8,2,1,""],group:[8,2,1,""],owner:[8,2,1,""],sacl:[8,2,1,""]},"smb.smb_structs":{OperationFailure:[7,0,1,""],ProtocolError:[7,0,1,""],UnsupportedFeature:[7,0,1,""]},smb:{security_descriptors:[8,3,0,"-"]}},objnames:{"0":["py","class","Python class"],"1":["py","method","Python method"],"2":["py","attribute","Python attribute"],"3":["py","module","Python module"]},objtypes:{"0":"py:class","1":"py:method","2":"py:attribute","3":"py:module"},terms:{"128":2,"137":[0,1],"139":[2,4],"168":3,"192":3,"1970":6,"256":[6,10],"3rd":10,"445":[2,4],"60kbyte":4,"65591":[2,4],"\u5783\u573e\u6587\u4ef6":3,"\u6d4b\u8bd5\u6587\u4ef6\u5939":3,"abstract":10,"boolean":[0,1,2,4],"byte":[2,4,6],"case":4,"class":[7,8,9,10,11],"default":[2,4,11],"float":[0,1,4,6],"function":[0,1,2,4,10],"import":[2,3,4,10],"int":[2,4],"long":[2,4,6],"new":[1,2,4,9,11],"public":4,"return":[0,1,2,3,4,5,6,10,11],"short":6,"switch":11,"true":[0,1,2,4,5,6,11],"try":[2,4,9],"while":7,ACE:8,And:9,DES:10,DNS:3,For:[2,3,4,10],One:8,The:[0,1,2,3,4,5,6,8,9,10],Then:9,There:[2,4],These:[6,10],Use:[2,4,10],Will:0,__init__:[0,1,2,4,9],aaa:[0,1],about:[2,4,5,6],abov:9,accept:[2,4,9],access:[2,4,6,8],access_mask:8,accur:4,ace_type_:8,aceflag:8,aces:8,acetyp:8,acknowledg:4,acl:8,across:[2,4],actual:2,add:[0,4,11],addcallback:[0,4],added:11,adderrback:4,addit:8,additional_data:8,addr:[0,4],address:[0,1,3,9,10,11],admin:5,administr:5,af_inet6:2,af_inet:2,after:[0,1,2,4,10],again:0,against:10,algorithm:[2,4,9,10],alia:4,all:[0,2,4,8,10],alloc:6,alloc_s:6,allow:[0,2,4],alon:10,alphanumer:[2,4],alreadi:2,also:[2,4,5],alter:4,altern:4,alwai:[8,10],anderson:[0,1],ani:[1,2,4,6,10],api:11,appli:[2,4,8],applic:[0,1,4,6,10,11],application_data:8,appropri:[0,1],arbitari:[2,4],archiv:[2,4,6,11],arg:4,around:0,ascii:[2,4],asn:10,aspx:2,assert:2,associ:8,asynchron:[0,2,9],attempt:2,attr_norm:2,attr_xxx:6,attribut:[2,4,5,6,11],attribute_data:8,atttempt:2,audit:8,auth:4,authent:[2,4,7,9,10],authenthent:4,author:8,auto:[2,4],automat:[0,1,2,4],avail:[2,4,5,6,10],avoid:4,back:[0,1,2,4],base:[2,4,5,6,7,9,10],batch:4,bbb:[0,1],been:[2,4,7,9,10],befor:[2,4,11],begin:[2,4],between:10,bind:[0,1],bit:[2,4,6,10],bitmask:8,bitwis:[2,4],blob:10,block:[0,1,2,10],both:[2,4],briefli:9,broadcast:[0,1],buffer:9,build_open:3,buildprotocol:4,busi:[2,4],call:[0,1,2,4,6,9],callabl:2,callback:[0,4,9],can:[0,1,2,3,4,5,6,8,9,10,11],cannot:[2,3,4],captur:[2,4],care:9,cc232110:2,ccc:[0,1],chang:[6,11],charact:[2,3,4,6],choic:[2,4],choos:[2,4],cif:[1,2,4,6,7,9,10],clear:2,click:[2,4],client:[2,4,10],client_machine_nam:[2,4],close:[1,2,3,4],closeconnect:4,code:3,com:[2,3],come:10,comm_devic:5,comma:3,command:[2,4],comment:5,commerci:10,commun:[2,4,5,10],compat:[2,4],complet:[2,4,7,10,11],compon:[2,3,4],compress:[2,4,6,11],comput:[2,4],concurr:[2,4],configur:[2,4],conflict:10,conn:2,connect:[2,4,7,9],connecttcp:4,consist:8,constant:[2,4,5,6,8,10],constructor:9,contain:[1,2,4,5,6,10],content:[2,4],context:11,continu:[2,4],contribut:[0,1],control:[2,4,8,11],conveni:[2,4,6,8],copi:[2,4,10],correspond:[6,8],could:[6,10,11],cover:10,creat:[0,1,2,3,4,9],create_tim:6,createdirectori:[2,4],creation:[5,6],credenti:[2,4],credienti:4,current:[2,7],dacl:8,dat:3,data:[0,2,3,4,8,9,10],data_buf:7,datagram:0,datagramreceiv:0,datetim:[2,4],ddd:[0,1],decod:10,def:4,defer:[0,4],defin:[0,1,2,4,6,11],delet:[2,3,4,11],delete_matching_fold:[2,4,11],deletedirectori:[2,4],deletefil:[2,4,11],depend:[8,10],describ:[2,9],descript:5,descriptor:[2,10],desir:2,detail:[6,9,10],detect:[2,4],determin:[0,1,2,4,6,10],develop:[2,6,10],devic:[5,6],dialect:10,dictionari:8,differ:[2,4,9,10],digest:10,direct:[2,4],directli:[4,6],director:3,directori:[2,3,4,6,11],disabl:[2,4],disconnect:[0,2,4,7],discret:10,discretionari:8,disk_tre:5,dixon:10,dmitri:10,document:11,doe:[2,4,6,10],doesn:8,doing:[0,1],domain:[2,4,10],done:[0,1],dot:[0,1],download:[4,10],dtyp:8,due:9,each:[1,2,4,5,6],earliest:4,echo:[2,4],edit:[2,4],either:[2,4],element:[2,4],els:[2,4],empti:[0,1,2,3,4,6],enabl:[2,4],encapsul:8,encod:10,encount:[2,6],encrypt:[2,4,6,10,11],end:[2,4],english:[2,4],enterpris:[2,4],entir:4,entri:[2,4,6,8,11],eof:[2,4],errback:[0,4],error:[2,4,9],establish:[2,4],etc:4,exampl:10,excee:4,except:[0,4,10],exercis:10,exist:[2,3,4],expos:4,extend:10,facilit:10,factori:4,fail:[2,4,7,9],failur:0,fallback:[2,4],fals:[0,1,2,4],famili:2,familiar:10,featur:[2,4,7],feeddata:9,fh2:3,field:[6,8],file:[2,3,4,5,6,9,10,11],file_attribut:[2,4,6],file_fh:3,file_id:[6,11],file_obj:[2,4],file_s:[4,6],filenam:[2,4,6],fileretriev:4,files:2,filesystem:11,filter:[2,4],find:[2,4,9],finer:11,first:[2,3,4],flag:[0,1,2,4,8],folder:[2,3,4,6,10,11],follow:[2,3,4,5,6,8,10],forth:5,framework:[0,4,10],free:[0,1,10],freeli:[2,4],from:[0,1,2,3,4,8,9,10],from_info:0,fscc:6,fulli:3,functionl:4,further:2,gener:9,get:4,getattribut:[2,4,11],getsecur:[2,11],given:11,gmt:[2,4],googl:10,group:8,guess:[2,4],handl:[4,9],has:[0,2,4,6,7,9,10,11],hash:10,have:[0,2,4,9,10,11],held:2,help:2,henc:[2,4,10],hidden:[2,4,6,11],hope:[0,1],host:[2,3,4],hostnam:3,how:4,http:2,iaddress:4,iana:[0,1],identifi:[2,4,8],identifier_author:8,idl:2,ignor:[2,4,6,11],illustr:[2,3,4],immedi:[2,4],implement:[0,1,2,4,8,9,10],impos:[2,4],improv:11,includ:[2,4,9,10,11],incom:[0,4],incompat:11,incomplet:9,index:[2,4,6,10,11],indic:[0,1,2,4,8,11],individu:4,infer:2,inform:[2,4,5,6],inherit:8,inherited_object_typ:8,initi:[5,9],input:4,insid:[2,4],instal:[2,4,10],instanc:[0,1,2,4,6,8,11],instanti:[0,1,4,6],instiant:[0,1],integ:[0,1,2,4,6,8,10],integr:[5,10],interest:[2,4],interfac:4,intern:[4,9,10],internet:[0,4],interprocess:5,interv:4,invok:[2,4],involv:9,ipc:5,ipv4:1,is_direct_tcp:[2,4],isdirectori:6,isinheritonli:8,isnorm:[6,11],isreadi:4,isreadonli:[6,11],isspeci:5,istemporari:5,isusingsmb2:[2,4],its:[0,1,2,4,6,9],itself:[2,4,8,10],jason:[0,1],just:[0,4],keep:2,keepal:2,know:[0,1,4],known:[2,4],kwarg:4,last:6,last_access_tim:6,last_attr_change_tim:6,last_write_tim:6,latest:10,learn:[2,4],least:2,leav:[0,1,2,4],length:[6,8],lgpl:10,librari:[2,10],like:[2,3,4,6,11],limit:[2,4,6],linux:10,list:[0,1,2,4,8,10],listen:[0,1],listen_port:[0,1],listenudp:0,listpath:[2,4,6,11],listshar:[2,4],listsnapshot:[2,4],local:[2,3,4],local_fil:3,log:8,look:10,loop:9,loseconnect:4,machin:[0,1,2,3,4,10,11],made:[2,4,10],mai:[2,4],main:10,manag:11,mask:8,match:[0,1,2,4],max_length:[2,4],maximum:[2,4],md4:10,mean:[4,8],meant:2,mechan:[2,4],messag:[2,4,7,10],method:[0,1,2,3,4,6,9,11],microsoft:[2,10],might:[2,4],miketeo:10,mit:10,mode:[0,1,2],modif:6,modifi:10,modul:[2,4,8,10],more:[2,4,6,9,10],most:[2,4,9,10,11],msdn:2,multipl:[2,4],must:[0,2,3,4],my_nam:[2,4],mypassword:3,myserv:3,myuserid:3,name:[0,1,2,3,4,5,6,10,11],namedtemporaryfil:[2,4],nbn:[1,10],nbname:3,nbnsprotocol:[1,10,11],need:[2,3,4,6,9,10],neg:[2,4],net:10,netbio:[0,2,3,4,9,10,11],netbiosprotocol:[0,10],netbiossess:10,netbiostimeout:0,network:[0,1,2,4,10],never:[2,4],new_path:[2,4],newer:[2,4],next:2,nmb:[0,1,10,11],non:[2,4],none:[0,1,2,4,6,7],normal:[2,4,6,11],notat:[0,1,6],notconnectederror:[4,7],note:[2,4,6],notreadyerror:[4,7],now:[9,11],ntlm:[4,9,10],ntlmssp:10,ntlmv1:[2,4,10],ntlmv2:[2,4,10],number:[0,1,2,4,6,8,11],obj:[2,4],object:[2,3,4,8],object_typ:8,occur:[2,4,7],offset:[2,4],often:9,old:[2,4],old_path:[2,4],older:10,onauthfail:[4,9],onauthok:[4,9],onc:[0,4,9],one:[2,3,4,5,6],onli:[0,2,3,4,6,8,10,11],onnmbsessionfail:9,open:[2,3,4,10],opensourc:10,oper:[1,2,4,7,9,10,11],operationfailur:[2,4,7],opportun:4,organ:10,origin:[2,4,6],other:[2,4,6,10,11],otherwis:[2,4],out:[2,4],over:[2,4,10],overrid:[4,9],overwritten:[2,4],own:[2,4,9,10],owner:8,packag:3,packet:[0,1,4,9],page:[9,10,11],param:[0,4],paramet:[0,1,2,3,4,9,10,11],parent:3,pars:10,part:9,parti:10,pass:[2,3,4,11],password:[2,4],path:[2,3,4],path_file_pattern:[2,4],pathnam:[2,4],pattern:[2,4],perform:[0,1,2,4,6,9],period:4,persist:5,place:10,pleas:[10,11],point:[3,4],port:[0,1,2,4],posit:[2,4],possibl:10,post:[4,9],precis:4,present:[7,8],previou:11,princip:8,print:[4,10],print_queu:5,proce:4,proceed:[2,4],process:[3,9],prohibit:6,project:[0,4,10],promis:10,properti:[2,4,5,6,8,11],protocol:[2,4,7,10],protocolerror:7,provid:[0,1,2,3,4,9,10],pure:10,purpos:10,pyasn1:10,pyde:10,pymsb:4,pysmb:[0,2,4,6,7],python3:[2,4],python:[2,3,4,10],qualifi:3,queri:[0,1,2,4,10,11],queryipfornam:[0,1,11],querynam:[0,1],queue:4,rais:[0,2,3,4,7],reactor:[0,4],read:[2,3,4,6,9,10,11],readi:[4,7],receiv:[0,1,2,4],recurs:[2,4],refer:[2,4,5,6,10,11],referenc:10,regardless:[2,4],regular:[2,4],reject:[2,4],rel:[2,4],relat:10,releas:[1,2,11],remot:[1,2,3,4,5,6,9,11],remote_nam:[2,4,9],remov:0,renam:[2,4],repli:[0,1,2,4],report:9,repres:[6,8,11],request:[2,3,4],requir:[2,4,7],reserv:5,reset:2,resetfileattribut:2,resolv:3,resourc:[1,2,4,6],respond:2,respons:7,restrict:8,result:[0,2,4],retri:4,retriev:[2,3,4,11],retrievefil:[2,4],retrievefilefactori:4,retrievefilefromoffset:[2,4,11],reus:4,revis:8,rewrit:11,rewritten:11,rfc1001:[2,3,4],right:[2,4],routin:10,rozmanov:10,sacl:8,safe:[2,4],samba:10,sambda:[2,4],same:[2,4],search:[2,4,10,11],sec:4,second:[0,1,4,6],section:10,secur:[2,10],security_descriptor:[2,8],securityblob:10,securitydescriptor:[2,8],see:[2,4,6,8],seek:[2,4],select:[0,1,2,4],self:[4,9],send:[0,1,2,4],separ:[3,10],sequenc:8,sequenti:2,seri:4,server:[2,4,5,6,9,10,11],server_ip:[2,4],server_nam:[2,4],servic:[1,2,3,4,9,10],service_nam:[2,4],session:[9,10],set:[2,4],setup:[0,1,4,9],sha256:10,sha:10,shadow:[2,4],share:[2,3,4,5,6,10],shareddevic:[2,4,10],sharedfil:[2,4,10,11],sharedfold:3,short_nam:6,should:[0,1,2,4,6,8],sid:8,side:10,sign:[2,4],sign_nev:[2,4],sign_opt:[2,4],sign_when_requir:[2,4],sign_when_support:[2,4],simpl:[2,4],simpli:3,simplic:[2,4],sinc:6,singl:[2,4,5,8],site:10,size:[4,6],smb1:[2,4,10],smb2:10,smb2_constant:10,smb2_struct:10,smb:[1,2,3,4,5,6,8,9,10,11],smb_constant:[2,4,6,10],smb_ext_file_attr:6,smb_file_attribute_arch:[2,4],smb_file_attribute_directori:[2,4],smb_file_attribute_hidden:[2,4],smb_file_attribute_incl_norm:[2,4],smb_file_attribute_norm:[2,4],smb_file_attribute_readonli:[2,4],smb_file_attribute_system:[2,4],smb_file_attribute_xxx:[2,4],smb_messag:7,smb_struct:[2,4,7,10],smbconnect:[10,11],smbhandler:10,smbprotocol:[4,6,10],smbprotocolfactori:[6,10,11],smbtest:[2,4],smbtimeout:[4,7],snapshot:[2,4],snippet:3,sock_famili:2,socket:[1,2,9],softwar:10,some:[2,4,10],sort:2,sourc:[0,1,2,4,5,6,7,8,10],space:[2,4],spars:[2,4,6,11],special:5,specif:10,specifi:[0,1,2,4,8,11],standard:[0,1,10],start:[0,2,4],statu:6,step:9,stoplisten:0,stopprotocol:0,store:[2,4,6],storefil:[2,4],storefilefromoffset:[2,11],string:[0,1,2,3,4,5,6],structur:8,style:10,sub:[2,4,11],subauthor:8,subclass:[4,9],subsequ:3,success:[2,9],successfulli:[2,4],suitabl:[2,10],support:[3,6,7,10,11],support_smb2:[2,4],synchron:[9,10],system:[2,4,6,8,11],take:[9,10],target:[0,1],tcp:[2,4,9],technic:9,tempfil:[2,4],temporari:[2,4,5,6,11],term:10,termin:[2,4],test:[3,6,10],than:[2,4],thei:10,therefor:2,thi:[0,1,2,4,5,6,8,9,10,11],thoma:10,those:4,thousand:4,through:4,time:[2,4,5,6,10],timeout:[0,1,2,4,7,11],todd:10,togeth:10,too:2,total:6,touch:[0,1,4],transfer:[4,10],translat:10,transmit:4,transport:[0,4,10],truncat:[2,11],truste:8,tupl:[0,2,4],twist:[0,4,10],two:11,txt:[2,3,4],type:[5,8],type_:8,u32:10,udp:[0,1],ultim:[2,4],under:10,underli:[1,2,4,7,10],unicod:[2,3,4,5,6],unless:[0,1],unlock:2,unsign:10,unsupportedfeatur:7,until:[1,2,4],upgrad:10,upload:[2,3,4],upload_fil:3,url:[3,10],urlerror:3,urllib2:[3,10],urllib:3,use:[1,2,4,10],use_ntlm_v2:[2,4,9],used:[1,2,4,10,11],user:[2,4,5,8],userid:[2,4],usernam:[2,4],using:[2,4,6,11],usual:[2,4,6,9,10],utc:[2,4],utf:3,util:[2,4],valu:[2,4,6,8],variabl:8,variou:10,veri:2,version:10,via:[0,4,6,10],vista:[2,4],wait:[0,1,4,7],want:[4,10],web:10,well:10,were:11,what:[0,1,2,4,9],when:[0,1,2,4,7,9,10],where:[2,3,4,6,10],whether:[2,4],which:[0,1,2,4,6,8,9,10,11],whiteman:10,who:[2,4,10],whose:10,wider:[2,4],wildcard:[2,4],window:[2,3,4,6,8,10],wise:6,wish:[1,2],within:[2,4,10],without:[0,2,4,10],workgroup:[2,4,11],wrap:0,write:[2,4,9,11],write_result:4,written:[2,4],wrong:9,yet:7,you:[0,1,2,3,4,6,9,10,11],your:[0,1,2,3,4,6,9,10,11],yourself:10,zero:[0,1,2,4],zone:[2,4]},titles:["NBNSProtocol Class","NetBIOS class","SMBConnection Class","SMbHandler Class","SMBProtocolFactory Class","SharedDevice Class","SharedFile Class","SMB Exceptions","Security Descriptors","Extending pysmb For Other Frameworks","Welcome to pysmb\u2019s documentation!","Upgrading from older pysmb versions"],titleterms:{"class":[0,1,2,3,4,5,6],For:9,Using:10,caveat:[2,4],content:10,credit:10,descript:10,descriptor:8,document:10,exampl:[2,3,4],except:7,extend:9,framework:9,from:11,indic:10,licens:10,nbnsprotocol:0,netbio:1,note:3,older:11,other:9,packag:10,pysmb:[9,10,11],secur:8,shareddevic:5,sharedfil:6,smb2:[2,4],smb:7,smbconnect:2,smbhandler:3,smbprotocolfactori:4,support:[2,4],tabl:10,upgrad:11,version:11,welcom:10}}) \ No newline at end of file diff --git a/docs/html/upgrading.html b/docs/html/upgrading.html new file mode 100644 index 0000000..049bbc0 --- /dev/null +++ b/docs/html/upgrading.html @@ -0,0 +1,195 @@ + + + + + + + + Upgrading from older pysmb versions — pysmb 1.2.7 documentation + + + + + + + + + + + + +
    +
    +
    +
    + +
    +

    Upgrading from older pysmb versions

    +

    This page documents the improvements and changes to the API that could be incompatible with previous releases.

    +
    +

    pysmb 1.2.0

    +
      +
    • Add new delete_matching_folders parameter to deleteFiles() method in SMBProtocolFactory and SMBConnection +class to support deletion of sub-folders. If you are passing timeout parameter to the deleteFiles() method +in your application, please switch to using named parameter for timeout.

    • +
    +
    +
    +

    pysmb 1.1.28

    +
      +
    • SharedFile instances returned from the listPath() method now has a new property +file_id attribute which represents the file reference number given by the remote SMB server.

    • +
    +
    +
    +

    pysmb 1.1.26

    +
      +
    • SMBConnection class can now be used as a context manager

    • +
    +
    +
    +

    pysmb 1.1.25

    +
      +
    • SharedFile class has a new property isNormal which will be True if the file is a +‘normal’ file. pysmb defines a ‘normal’ file as a file entry that is not +read-only, not hidden, not system, not archive and not a directory; +it ignores other attributes like compression, indexed, sparse, temporary and encryption.

    • +
    • listPath() method in SMBProtocolFactory and SMBConnection class will now include +‘normal’ files by default if you do not specify the search parameter.

    • +
    +
    +
    +

    pysmb 1.1.20

    +
      +
    • A new method getSecurity() was added to SMBConnection and SMBProtocolFactory class.

    • +
    +
    +
    +

    pysmb 1.1.15

    +
      +
    • Add new truncate parameter to storeFileFromOffset() in SMBProtocolFactory and SMBConnection +class to support truncation of the file before writing. If you are passing timeout parameter +to the storeFileFromOffset() method in your application, please switch to using named parameter for timeout.

    • +
    +
    +
    +

    pysmb 1.1.11

    +
      +
    • A new method storeFileFromOffset() was added to SMBConnection and SMBProtocolFactory class.

    • +
    +
    +
    +

    pysmb 1.1.10

    +
      +
    • A new method getAttributes() was added to SMBConnection and SMBProtocolFactory class

    • +
    • SharedFile class has a new property isReadOnly to indicate the file is read-only on the remote filesystem.

    • +
    +
    +
    +

    pysmb 1.1.2

    +
      +
    • queryIPForName() method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names.

    • +
    +
    +
    +

    pysmb 1.0.3

    +
      +
    • Two new methods were added to NBNSProtocol class: queryIPForName() and NetBIOS.queryIPForName() +to support querying for a machine’s NetBIOS name at the given IP address.

    • +
    • A new method retrieveFileFromOffset() was added to SMBProtocolFactory and SMBConnection +to support finer control of file retrieval operation.

    • +
    +
    +
    +

    pysmb 1.0.0

    +

    pysmb was completely rewritten in version 1.0.0. +If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API.

    +
    +
    + + +
    +
    +
    +
    + +
    +
    + + + + \ No newline at end of file diff --git a/python2/nmb/base.py b/python2/nmb/base.py index 4731dfe..6de0867 100644 --- a/python2/nmb/base.py +++ b/python2/nmb/base.py @@ -77,6 +77,9 @@ self.onNMBSessionOK() elif packet.type == NEGATIVE_SESSION_RESPONSE: self.onNMBSessionFailed() + elif packet.type == SESSION_KEEPALIVE: + # Discard keepalive packets - [RFC1002]: 5.2.2.1 + pass else: self.log.warning('Unrecognized NMB session type: 0x%02x', packet.type) @@ -151,21 +154,25 @@ opcode = (code >> 11) & 0x0F flags = (code >> 4) & 0x7F rcode = code & 0x0F - numnames = struct.unpack('B', data[self.HEADER_STRUCT_SIZE + 44])[0] - if numnames > 0: - ret = [ ] - offset = self.HEADER_STRUCT_SIZE + 45 + try: + numnames = struct.unpack('B', data[self.HEADER_STRUCT_SIZE + 44])[0] - for i in range(0, numnames): - mynme = data[offset:offset + 15] - mynme = mynme.strip() - ret.append(( mynme, ord(data[offset+15]) )) - offset += 18 + if numnames > 0: + ret = [ ] + offset = self.HEADER_STRUCT_SIZE + 45 - return trn_id, ret - else: - return trn_id, None + for i in range(0, numnames): + mynme = data[offset:offset + 15] + mynme = mynme.strip() + ret.append(( mynme, ord(data[offset+15]) )) + offset += 18 + + return trn_id, ret + except IndexError: + pass + + return trn_id, None # # Contributed by Jason Anderson diff --git a/python2/smb/SMBConnection.py b/python2/smb/SMBConnection.py index 77b1760..cae3ab9 100644 --- a/python2/smb/SMBConnection.py +++ b/python2/smb/SMBConnection.py @@ -21,6 +21,7 @@ Create a new SMBConnection instance. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. + *password* can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully. Note that you need to call *connect* method to actually establish the SMB connection to the remote server and perform authentication. @@ -29,7 +30,7 @@ Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. - You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+`` + You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. @@ -72,6 +73,15 @@ total_sent = total_sent + sent # + # Support for "with" context + # + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + # # Misc Properties # @@ -153,15 +163,23 @@ return results def listPath(self, service_name, path, - search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE, + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* + + For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + + Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), + system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files + and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). + If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. + SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). - The default *search* value will query for all read-only, hidden, system, archive files and directories. :param string/unicode pattern: the filter to apply to the results before returning to the client. :return: A list of :doc:`smb.base.SharedFile` instances. """ @@ -245,6 +263,37 @@ self.is_busy = True try: self._getAttributes(service_name, path, cb, eb, timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False + + return results[0] + + def getSecurity(self, service_name, path, timeout = 30): + """ + Retrieve the security descriptor of the file at *path* on the *service_name*. + + :param string/unicode service_name: the name of the shared folder for the *path* + :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. + :return: A :class:`smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file. + """ + if not self.sock: + raise NotConnectedError('Not connected to server') + + results = [ ] + + def cb(info): + self.is_busy = False + results.append(info) + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True + try: + self._getSecurity(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: @@ -350,9 +399,11 @@ return results[0] - def deleteFiles(self, service_name, path_file_pattern, timeout = 30): + def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. + + If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. @@ -372,23 +423,27 @@ self.is_busy = True try: - self._deleteFiles(service_name, path_file_pattern, cb, eb, timeout = timeout) - while self.is_busy: - self._pollForNetBIOSPacket(timeout) - finally: - self.is_busy = False - - def resetFileAttributes(self, service_name, path_file_pattern, timeout = 30): + self._deleteFiles(service_name, path_file_pattern, delete_matching_folders, cb, eb, timeout = timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False + + def resetFileAttributes(self, service_name, path_file_pattern, file_attributes = ATTR_NORMAL, timeout = 30): """ Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. - Note: this function is currently only implemented for SMB2! Technically, it sets the FILE_ATTRIBUTE_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) - + By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. + (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) + + Note: this function is currently only implemented for SMB2! + :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. + :param int file_attributes: The desired file attributes to set. Defaults to `ATTR_NORMAL`. :return: None """ if not self.sock: @@ -403,7 +458,7 @@ self.is_busy = True try: - self._resetFileAttributes(service_name, path_file_pattern, cb, eb, timeout = timeout) + self._resetFileAttributes(service_name, path_file_pattern, cb, eb, file_attributes, timeout = timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: @@ -495,7 +550,7 @@ """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. - :param string data: Data to send to the remote server. + :param bytes data: Data to send to the remote server. Must be a bytes object. :return: The *data* parameter """ if not self.sock: diff --git a/python2/smb/SMBHandler.py b/python2/smb/SMBHandler.py index 137e943..4fcc74f 100644 --- a/python2/smb/SMBHandler.py +++ b/python2/smb/SMBHandler.py @@ -44,12 +44,15 @@ passwd = passwd or '' myname = MACHINE_NAME or self.generateClientMachineName() - n = NetBIOS() - names = n.queryIPForName(host) - if names: - server_name = names[0] - else: - raise urllib2.URLError('SMB error: Hostname does not reply back with its machine name') + server_name,host = host.split(',') if ',' in host else [None,host] + + if server_name is None: + n = NetBIOS() + names = n.queryIPForName(host) + if names: + server_name = names[0] + else: + raise urllib2.URLError('SMB error: Hostname does not reply back with its machine name') path, attrs = splitattr(req.get_selector()) if path.startswith('/'): diff --git a/python2/smb/SMBProtocol.py b/python2/smb/SMBProtocol.py index 2af2747..1238d63 100644 --- a/python2/smb/SMBProtocol.py +++ b/python2/smb/SMBProtocol.py @@ -177,15 +177,23 @@ return d def listPath(self, service_name, path, - search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE, + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* + + For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + + Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), + system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files + and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). + If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. + SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). - The default *search* value will query for all read-only, hidden, system, archive files and directories. :param string/unicode pattern: the filter to apply to the results before returning to the client. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile` instances. @@ -368,7 +376,7 @@ """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. - :param string data: Data to send to the remote server. + :param bytes data: Data to send to the remote server. Must be a bytes object. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter. """ diff --git a/python2/smb/base.py b/python2/smb/base.py index c1544c8..5f85609 100644 --- a/python2/smb/base.py +++ b/python2/smb/base.py @@ -5,6 +5,7 @@ from smb2_constants import * from smb_structs import * from smb2_structs import * +from .security_descriptors import SecurityDescriptor from nmb.base import NMBSession from utils import convertFILETIMEtoEpoch import ntlm, securityblob @@ -59,13 +60,14 @@ def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) self.username = _convert_to_unicode(username) - self.password = _convert_to_unicode(password) + self._password = password self.domain = _convert_to_unicode(domain) self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1 self.smb_message = SMBMessage() self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True + self.async_requests = { } #: AsyncID mapped to _PendingRequest instance self.pending_requests = { } #: MID mapped to _PendingRequest instance self.connected_trees = { } #: Share name mapped to TID self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages @@ -104,6 +106,10 @@ (self.use_ntlm_v2 and 'v2') or 'v1', (SUPPORT_EXTENDED_SECURITY and 'with') or 'without') + @property + def password(self): + password = self._password() if callable(self._password) else self._password + return _convert_to_unicode(password) # # NMBSession Methods @@ -173,6 +179,7 @@ self._listShares = self._listShares_SMB1 self._listPath = self._listPath_SMB1 self._listSnapshots = self._listSnapshots_SMB1 + self._getSecurity = self._getSecurity_SMB1 self._getAttributes = self._getAttributes_SMB1 self._retrieveFile = self._retrieveFile_SMB1 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1 @@ -196,6 +203,7 @@ self._listPath = self._listPath_SMB2 self._listSnapshots = self._listSnapshots_SMB2 self._getAttributes = self._getAttributes_SMB2 + self._getSecurity = self._getSecurity_SMB2 self._retrieveFile = self._retrieveFile_SMB2 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2 self._storeFile = self._storeFile_SMB2 @@ -219,7 +227,7 @@ if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB2() - if smb_message.command != SMB2_COM_NEGOTIATE and smb_message.command != SMB2_COM_ECHO: + if smb_message.command != SMB2_COM_NEGOTIATE: smb_message.session_id = self.session_id if self.is_signing_active: @@ -256,6 +264,19 @@ if result == securityblob.RESULT_ACCEPT_COMPLETED: self.has_authenticated = True self.log.info('Authentication (on SMB2) successful!') + + # [MS-SMB2]: 3.2.5.3.1 + # If the security subsystem indicates that the session was established by an anonymous user, + # Session.SigningRequired MUST be set to FALSE. + # If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the + # SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP + # failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags + # field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired + # MUST be set to FALSE. + if message.payload.isGuestSession or message.payload.isAnonymousSession: + self.is_signing_active = False + self.log.info('Signing disabled because session is guest/anonymous') + self.onAuthOK() else: raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message) @@ -269,18 +290,58 @@ self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ), ex: raise ProtocolError(str(ex), message.raw_data, message) - elif message.status == 0xc000006d: # STATUS_LOGON_FAILURE + elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE + or message.status == 0xc0000064 # STATUS_NO_SUCH_USER + or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Please check username and password.') self.onAuthFailed() + elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED + or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account or password has expired.') + self.onAuthFailed() + elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.') + self.onAuthFailed() + elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account has been disabled.') + self.onAuthFailed() + elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS + or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED + or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Not allowed.') + self.onAuthFailed() + elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Domain not trusted.') + self.onAuthFailed() + elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Workstation not trusted.') + self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status, message.raw_data, message) - req = self.pending_requests.pop(message.mid, None) - if req: - req.callback(message, **req.kwargs) - return True + if message.isAsync: + if message.status == 0x00000103: # STATUS_PENDING + req = self.pending_requests.pop(message.mid, None) + if req: + self.async_requests[message.async_id] = req + else: # All other status including SUCCESS + req = self.async_requests.pop(message.async_id, None) + if req: + req.callback(message, **req.kwargs) + return True + else: + req = self.pending_requests.pop(message.mid, None) + if req: + req.callback(message, **req.kwargs) + return True def _updateServerInfo_SMB2(self, payload): @@ -315,12 +376,13 @@ self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) - ntlm_data = ntlm.generateAuthenticateMessage(server_flags, - nt_challenge_response, - lm_challenge_response, - session_key, - self.username, - self.domain) + ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, + nt_challenge_response, + lm_challenge_response, + session_key, + self.username, + self.domain, + self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) @@ -340,7 +402,10 @@ if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") - self.signing_session_key = (session_key + '\0'*16)[:16] + self.signing_session_key = session_signing_key + if self.log.isEnabledFor(logging.DEBUG): + self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key)) + if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: @@ -369,7 +434,7 @@ m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid) messages_history.append(m) def connectSrvSvcCB(create_message, **kwargs): @@ -391,9 +456,9 @@ 01 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2WriteRequest(create_message.payload.fid, data_bytes, 0)) - m.tid = create_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, fid = create_message.payload.fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) messages_history.append(m) else: errback(OperationFailure('Failed to list shares: Unable to locate Server Service RPC endpoint', messages_history)) @@ -402,12 +467,12 @@ messages_history.append(trans_message) if trans_message.status == 0: m = SMB2Message(SMB2ReadRequest(kwargs['fid'], read_len = 1024, read_offset = 0)) - m.tid = trans_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, fid = kwargs['fid']) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) messages_history.append(m) else: - closeFid(trans_message.tid, kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') + closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') def rpcReadCB(read_message, **kwargs): messages_history.append(read_message) @@ -435,12 +500,12 @@ 00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00 """.replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2IoctlRequest(kwargs['fid'], 0x0011C017, flags = 0x01, max_out_size = 8196, in_data = data_bytes)) - m.tid = read_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) messages_history.append(m) else: - closeFid(read_message.tid, kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') + closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') def listShareResultsCB(result_message, **kwargs): messages_history.append(result_message) @@ -449,13 +514,11 @@ data_bytes = result_message.payload.out_data if ord(data_bytes[3]) & 0x02 == 0: - sendReadRequest(result_message.tid, kwargs['fid'], data_bytes) - else: - decodeResults(result_message.tid, kwargs['fid'], data_bytes) - elif result_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[result_message.mid] = _PendingRequest(result_message.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) - else: - closeFid(result_message.tid, kwargs['fid']) + sendReadRequest(kwargs['tid'], kwargs['fid'], data_bytes) + else: + decodeResults(kwargs['tid'], kwargs['fid'], data_bytes) + else: + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def decodeResults(tid, fid, data_bytes): @@ -494,20 +557,19 @@ m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, - fid = fid, data_bytes = data_bytes) + tid = tid, fid = fid, data_bytes = data_bytes) def readCB(read_message, **kwargs): messages_history.append(read_message) if read_message.status == 0: - data_len = read_message.payload.data_length data_bytes = read_message.payload.data if ord(data_bytes[3]) & 0x02 == 0: - sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - closeFid(read_message.tid, kwargs['fid']) + sendReadRequest(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + decodeResults(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def closeFid(tid, fid, results = None, error = None): @@ -572,39 +634,44 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendQuery(create_message.tid, create_message.payload.fid, '') + sendQuery(kwargs['tid'], create_message.payload.fid, '') + elif create_message.status == 0xC0000034L: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID + errback(OperationFailure('Failed to list %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to list %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendQuery(tid, fid, data_buf): m = SMB2Message(SMB2QueryDirectoryRequest(fid, pattern, - info_class = 0x03, # FileBothDirectoryInformation + info_class = 0x25, # FileIdBothDirectoryInformation flags = 0, output_buf_len = self.max_transact_size)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, fid = fid, data_buf = data_buf) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = tid, fid = fid, data_buf = data_buf) messages_history.append(m) def queryCB(query_message, **kwargs): messages_history.append(query_message) if query_message.status == 0: data_buf = decodeQueryStruct(kwargs['data_buf'] + query_message.payload.data) - sendQuery(query_message.tid, kwargs['fid'], data_buf) + sendQuery(kwargs['tid'], kwargs['fid'], data_buf) + elif query_message.status == 0xC000000FL: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # If there are no matching files, we just treat as success instead of failing + closeFid(kwargs['tid'], kwargs['fid'], results = results) elif query_message.status == 0x80000006L: # STATUS_NO_MORE_FILES - closeFid(query_message.tid, kwargs['fid'], results = results) - else: - closeFid(query_message.tid, kwargs['fid'], error = query_message.status) + closeFid(kwargs['tid'], kwargs['fid'], results = results) + else: + closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def decodeQueryStruct(data_bytes): - # SMB_FIND_FILE_BOTH_DIRECTORY_INFO structure. See [MS-CIFS]: 2.2.8.1.7 and [MS-SMB]: 2.2.8.1.1 - info_format = ' data_length: return data_bytes[offset:] filename = data_bytes[offset2:offset2+filename_length].decode('UTF-16LE') - short_name = short_name.decode('UTF-16LE') - results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), - convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), - file_size, alloc_size, file_attributes, short_name, filename)) + short_name = short_name[:short_name_length].decode('UTF-16LE') + + accept_result = False + if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc + accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) + else: + accept_result = (file_attributes & search) > 0 + if accept_result: + results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), + convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, short_name, filename, file_id)) if next_offset: offset += next_offset @@ -645,7 +719,11 @@ if kwargs['results'] is not None: callback(kwargs['results']) elif kwargs['error'] is not None: - errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) + if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files + callback([ ]) + else: + errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): @@ -695,17 +773,18 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: p = create_message.payload + filename = self._extractLastPathComponent(unicode(path)) info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time, p.file_size, p.allocation_size, p.file_attributes, - unicode(path), unicode(path)) - closeFid(create_message.tid, p.fid, info = info) + filename, filename) + closeFid(kwargs['tid'], p.fid, info = info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history)) @@ -730,6 +809,87 @@ sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + sendCreate(self.connected_trees[service_name]) + + def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + expiry_time = time.time() + timeout + path = path.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + messages_history = [ ] + results = [ ] + + def sendCreate(tid): + m = SMB2Message(SMB2CreateRequest(path, + file_attributes = 0, + access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + oplock = SMB2_OPLOCK_LEVEL_NONE, + impersonation = SEC_IMPERSONATE, + create_options = 0, + create_disp = FILE_OPEN)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) + messages_history.append(m) + + def createCB(create_message, **kwargs): + messages_history.append(create_message) + if create_message.status == 0: + m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, + flags = 0, + additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + info_type = SMB2_INFO_SECURITY, + file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12 + input_buf = '', + output_buf_len = self.max_transact_size)) + m.tid = kwargs['tid'] + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) + messages_history.append(m) + else: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history)) + + def queryCB(query_message, **kwargs): + messages_history.append(query_message) + if query_message.status == 0: + security = SecurityDescriptor.from_bytes(query_message.payload.data) + closeFid(kwargs['tid'], kwargs['fid'], result = security) + else: + closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) + + def closeFid(tid, fid, result = None, error = None): + m = SMB2Message(SMB2CloseRequest(fid)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error) + messages_history.append(m) + + def closeCB(close_message, **kwargs): + if kwargs['result'] is not None: + callback(kwargs['result']) + elif kwargs['error'] is not None: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) + + if not self.connected_trees.has_key(service_name): + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if connect_message.status == 0: + self.connected_trees[service_name] = connect_message.tid + sendCreate(connect_message.tid) + else: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) @@ -766,7 +926,7 @@ m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, - share_access = FILE_SHARE_READ, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, @@ -784,16 +944,18 @@ flags = 0, additional_info = 0, info_type = SMB2_INFO_FILE, - file_info_class = 0x16, # FileStreamInformation [MS-FSCC] 2.4 + file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4 input_buf = '', output_buf_len = 4096)) - m.tid = create_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback, - fid = create_message.payload.fid, file_attributes = create_message.payload.file_attributes) + tid = kwargs['tid'], + fid = create_message.payload.fid, + file_attributes = create_message.payload.file_attributes) messages_history.append(m) else: - errback(OperationFailure('Failed to list %s on %s: Unable to open file' % ( path, service_name ), messages_history)) + errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def infoCB(info_message, **kwargs): messages_history.append(info_message) @@ -808,9 +970,9 @@ remaining_len = file_len if starting_offset + remaining_len > file_len: remaining_len = file_len - starting_offset - sendRead(info_message.tid, kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) - else: - errback(OperationFailure('Failed to list %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) + sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) + else: + errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes): read_count = min(self.max_read_size, remaining_len) @@ -818,7 +980,7 @@ m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, - fid = fid, offset = offset, + tid = tid, fid = fid, offset = offset, remaining_len = remaining_len, read_len = read_len, file_attributes = file_attributes) @@ -832,12 +994,12 @@ remaining_len = kwargs['remaining_len'] - data_len if remaining_len > 0: - sendRead(read_message.tid, kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) - else: - closeFid(read_message.tid, kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) + sendRead(kwargs['tid'], kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) + else: + closeFid(kwargs['tid'], kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) else: messages_history.append(read_message) - closeFid(read_message.tid, kwargs['fid'], error = read_message.status) + closeFid(kwargs['tid'], kwargs['fid'], error = read_message.status) def closeFid(tid, fid, ret = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -913,10 +1075,6 @@ messages_history.append(create_message) if create_message.status == 0: sendWrite(create_message.tid, create_message.payload.fid, starting_offset) - elif create_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[create_message.mid] = _PendingRequest(create_message.mid, expiry_time, - createCB, errback, - tid=kwargs['tid']) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -928,17 +1086,17 @@ m = SMB2Message(SMB2WriteRequest(fid, data, offset)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, fid = fid, offset = offset+data_len) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, tid = tid, fid = fid, offset = offset+data_len) else: closeFid(tid, fid, offset = offset) def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if write_message.status == 0: - sendWrite(write_message.tid, kwargs['fid'], kwargs['offset']) + sendWrite(kwargs['tid'], kwargs['fid'], kwargs['offset']) else: messages_history.append(write_message) - closeFid(write_message.tid, kwargs['fid']) + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid, error = None, offset = None): @@ -971,16 +1129,99 @@ sendCreate(self.connected_trees[service_name]) - def _deleteFiles_SMB2(self, service_name, path_file_pattern, callback, errback, timeout = 30): + def _deleteFiles_SMB2(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') expiry_time = time.time() + timeout + pattern = None path = path_file_pattern.replace('/', '\\') if path.startswith('\\'): path = path[1:] if path.endswith('\\'): path = path[:-1] + else: + path_components = path.split('\\') + if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: + path = '\\'.join(path_components[:-1]) + pattern = path_components[-1] + messages_history, files_queue = [ ], [ ] + + if pattern is None: + path_components = path.split('\\') + if len(path_components) > 1: + files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) + else: + files_queue.append(( '', path )) + + def deleteCB(path): + if files_queue: + p, filename = files_queue.pop(0) + if filename: + if p: + filename = p + '\\' + filename + self._deleteFiles_SMB2__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) + else: + self._deleteDirectory_SMB2(service_name, p, deleteCB, errback, timeout) + else: + callback(path_file_pattern) + + def listCB(files_list): + files_queue.extend(files_list) + deleteCB(None) + + if not self.connected_trees.has_key(service_name): + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if connect_message.status == 0: + self.connected_trees[service_name] = connect_message.tid + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + + def _deleteFiles_SMB2__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): + folder_queue = [ ] + files_list = [ ] + current_path = [ path ] + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL + + def listCB(results): + files = [ ] + for f in filter(lambda x: x.filename not in [ '.', '..' ], results): + if f.isDirectory: + if delete_matching_folders: + folder_queue.append(current_path[0]+'\\'+f.filename) + else: + files.append(( current_path[0], f.filename )) + if current_path[0]!=path and delete_matching_folders: + files.append(( current_path[0], None )) + + if files: + files_list[0:0] = files + + if folder_queue: + p = folder_queue.pop() + current_path[0] = p + self._listPath_SMB2(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) + else: + callback(files_list) + + self._listPath_SMB2(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) + + def _deleteFiles_SMB2__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendCreate(tid): @@ -1011,10 +1252,10 @@ messages_history.append(open_message) if open_message.status == 0: sendDelete(open_message.tid, open_message.payload.fid) - elif open_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[open_message.mid] = _PendingRequest(open_message.mid, expiry_time, - createCB, errback, - tid=kwargs['tid']) + elif open_message.status == 0xC0000034L: # [MS-ERREF]: STATUS_OBJECT_NAME_NOT_FOUND + callback(path) + elif open_message.status == 0xC00000BAL: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY + errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -1024,22 +1265,18 @@ info_type = SMB2_INFO_FILE, file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO data = '\x01')) - ''' - Resources: - https://msdn.microsoft.com/en-us/library/cc246560.aspx - https://msdn.microsoft.com/en-us/library/cc232098.aspx - ''' - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, fid = fid) + # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4.11 + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) messages_history.append(m) def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if delete_message.status == 0: - closeFid(delete_message.tid, kwargs['fid'], status = 0) - else: - closeFid(delete_message.tid, kwargs['fid'], status = delete_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1050,27 +1287,13 @@ def closeCB(close_message, **kwargs): if kwargs['status'] == 0: - callback(path_file_pattern) + callback(path) else: errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) - if not self.connected_trees.has_key(service_name): - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if connect_message.status == 0: - self.connected_trees[service_name] = connect_message.tid - sendCreate(connect_message.tid) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendCreate(self.connected_trees[service_name]) - - def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, timeout = 30): + sendCreate(tid) + + def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, file_attributes = ATTR_NORMAL, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') @@ -1109,7 +1332,7 @@ def createCB(open_message, **kwargs): messages_history.append(open_message) if open_message.status == 0: - sendReset(open_message.tid, open_message.payload.fid) + sendReset(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -1118,25 +1341,19 @@ additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 4, # FileBasicInformation - data = struct.pack('qqqqii',0,0,0,0,0x80,0))) # FILE_ATTRIBUTE_NORMAL - ''' - Resources: - https://msdn.microsoft.com/en-us/library/cc246560.aspx - https://msdn.microsoft.com/en-us/library/cc232064.aspx - https://msdn.microsoft.com/en-us/library/cc232094.aspx - https://msdn.microsoft.com/en-us/library/cc232110.aspx - ''' - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, fid = fid) + data = struct.pack('qqqqii',0,0,0,0,file_attributes,0))) + # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4, [MS-FSCC]: 2.4.7, [MS-FSCC]: 2.6 + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, tid = tid, fid = fid) messages_history.append(m) def resetCB(reset_message, **kwargs): messages_history.append(reset_message) if reset_message.status == 0: - closeFid(reset_message.tid, kwargs['fid'], status = 0) - else: - closeFid(reset_message.tid, kwargs['fid'], status = reset_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = reset_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1199,13 +1416,13 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - closeFid(create_message.tid, create_message.payload.fid) + closeFid(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) @@ -1273,7 +1490,7 @@ def createCB(open_message, **kwargs): messages_history.append(open_message) if open_message.status == 0: - sendDelete(open_message.tid, open_message.payload.fid) + sendDelete(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) @@ -1285,15 +1502,15 @@ data = '\x01')) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, fid = fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) messages_history.append(m) def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if delete_message.status == 0: - closeFid(delete_message.tid, kwargs['fid'], status = 0) - else: - closeFid(delete_message.tid, kwargs['fid'], status = delete_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1369,7 +1586,7 @@ def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendRename(create_message.tid, create_message.payload.fid) + sendRename(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) @@ -1382,15 +1599,15 @@ data = data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, fid = fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, tid = tid, fid = fid) messages_history.append(m) def renameCB(rename_message, **kwargs): messages_history.append(rename_message) if rename_message.status == 0: - closeFid(rename_message.tid, kwargs['fid'], status = 0) - else: - closeFid(rename_message.tid, kwargs['fid'], status = rename_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = rename_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1457,7 +1674,7 @@ def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendEnumSnapshots(create_message.tid, create_message.payload.fid) + sendEnumSnapshots(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) @@ -1598,9 +1815,38 @@ self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ), ex: raise ProtocolError(str(ex), message.raw_data, message) - elif message.status.internal_value == 0xc000006d: # STATUS_LOGON_FAILURE + elif (message.status.internal_value == 0xc000006d # STATUS_LOGON_FAILURE + or message.status.internal_value == 0xc0000064 # STATUS_NO_SUCH_USER + or message.status.internal_value == 0xc000006a): # STATUS_WRONG_PASSWORD self.has_authenticated = False - self.log.info('Authentication (with extended security) failed. Please check username and password. You may need to enable/disable NTLMv2 authentication.') + self.log.info('Authentication (with extended security) failed. Please check username and password.') + self.onAuthFailed() + elif (message.status.internal_value == 0xc0000193 # STATUS_ACCOUNT_EXPIRED + or message.status.internal_value == 0xC0000071): # STATUS_PASSWORD_EXPIRED + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account or password has expired.') + self.onAuthFailed() + elif message.status.internal_value == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account has been locked due to too many invalid logon attempts.') + self.onAuthFailed() + elif message.status.internal_value == 0xc0000072: # STATUS_ACCOUNT_DISABLED + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account has been disabled.') + self.onAuthFailed() + elif (message.status.internal_value == 0xc000006f # STATUS_INVALID_LOGON_HOURS + or message.status.internal_value == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED + or message.status.internal_value == 0xc0000070): # STATUS_INVALID_WORKSTATION + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Not allowed.') + self.onAuthFailed() + elif message.status.internal_value == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Domain not trusted.') + self.onAuthFailed() + elif message.status.internal_value == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status.internal_value, @@ -1662,12 +1908,13 @@ self.log.info('Performing NTLMv1 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) - ntlm_data = ntlm.generateAuthenticateMessage(server_flags, - nt_challenge_response, - lm_challenge_response, - session_key, - self.username, - self.domain) + ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, + nt_challenge_response, + lm_challenge_response, + session_key, + self.username, + self.domain, + self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) @@ -1687,7 +1934,7 @@ if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") - self.signing_session_key = session_key + self.signing_session_key = session_signing_key if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: @@ -1861,13 +2108,12 @@ def readCB(read_message, **kwargs): messages_history.append(read_message) if not read_message.status.hasError: - data_len = read_message.payload.data_length data_bytes = read_message.payload.data if ord(data_bytes[3]) & 0x02 == 0: - sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) + sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) @@ -1906,15 +2152,15 @@ setup_bytes = struct.pack(' 0 + if accept_result: + results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), + convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, short_name, filename)) if next_offset: offset += next_offset @@ -1992,11 +2245,15 @@ elif end_of_search: callback(results) else: - sendFindNext(find_message.tid, sid, last_name_offset, kwargs.get('support_dfs', False)) - else: - errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) - - def sendFindNext(tid, sid, resume_key, support_dfs=False): + sendFindNext(find_message.tid, sid, 0, results[-1].filename, kwargs.get('support_dfs', False)) + else: + if find_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files + callback([ ]) + else: + errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) + + def sendFindNext(tid, sid, resume_key, resume_file, support_dfs=False): setup_bytes = struct.pack(' 0: @@ -2322,11 +2580,100 @@ else: sendOpen(self.connected_trees[service_name]) - def _deleteFiles_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): + def _deleteFiles_SMB1(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') + expiry_time = time.time() + timeout + pattern = None path = path_file_pattern.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + else: + path_components = path.split('\\') + if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: + path = '\\'.join(path_components[:-1]) + pattern = path_components[-1] + messages_history, files_queue = [ ], [ ] + + if pattern is None: + path_components = path.split('\\') + if len(path_components) > 1: + files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) + else: + files_queue.append(( '', path )) + + def deleteCB(path): + if files_queue: + p, filename = files_queue.pop(0) + if filename: + if p: + filename = p + '\\' + filename + self._deleteFiles_SMB1__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) + else: + self._deleteDirectory_SMB1(service_name, p, deleteCB, errback, timeout = 30) + else: + callback(path_file_pattern) + + def listCB(files_list): + files_queue.extend(files_list) + deleteCB(None) + + if not self.connected_trees.has_key(service_name): + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if not connect_message.status.hasError: + self.connected_trees[service_name] = connect_message.tid + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + + def _deleteFiles_SMB1__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): + folder_queue = [ ] + files_list = [ ] + current_path = [ path ] + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL + + def listCB(results): + files = [ ] + for f in filter(lambda x: x.filename not in [ '.', '..' ], results): + if f.isDirectory: + if delete_matching_folders: + folder_queue.append(current_path[0]+'\\'+f.filename) + else: + files.append(( current_path[0], f.filename )) + if current_path[0]!=path and delete_matching_folders: + files.append(( current_path[0], None )) + + if files: + files_list[0:0] = files + + if folder_queue: + p = folder_queue.pop() + current_path[0] = p + self._listPath_SMB1(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) + else: + callback(files_list) + + self._listPath_SMB1(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) + + + def _deleteFiles_SMB1__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendDelete(tid): @@ -2340,9 +2687,79 @@ def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if not delete_message.status.hasError: + callback(path) + elif delete_message.status.internal_value == 0xC000000FL: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # If there are no matching files, we just treat as success instead of failing callback(path_file_pattern) - else: - errback(OperationFailure('Failed to store %s on %s: Delete failed' % ( path, service_name ), messages_history)) + elif delete_message.status.internal_value == 0xC00000BAL: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY + errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) + elif delete_message.status.internal_value == 0xC0000034L: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID + errback(OperationFailure('Failed to delete %s on %s: Path not found' % ( path, service_name ), messages_history)) + else: + errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) + + sendDelete(tid) + + def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, file_attributes=ATTR_NORMAL, timeout = 30): + raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') + + def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + path = path.replace('/', '\\') + messages_history = [ ] + + def sendCreate(tid): + m = SMBMessage(ComCreateDirectoryRequest(path)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) + messages_history.append(m) + + def createCB(create_message, **kwargs): + messages_history.append(create_message) + if not create_message.status.hasError: + callback(path) + else: + errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) + + if not self.connected_trees.has_key(service_name): + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if not connect_message.status.hasError: + self.connected_trees[service_name] = connect_message.tid + sendCreate(connect_message.tid) + else: + errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) + messages_history.append(m) + else: + sendCreate(self.connected_trees[service_name]) + + def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + path = path.replace('/', '\\') + messages_history = [ ] + + def sendDelete(tid): + m = SMBMessage(ComDeleteDirectoryRequest(path)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) + messages_history.append(m) + + def deleteCB(delete_message, **kwargs): + messages_history.append(delete_message) + if not delete_message.status.hasError: + callback(path) + else: + errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) if not self.connected_trees.has_key(service_name): def connectCB(connect_message, **kwargs): @@ -2351,84 +2768,7 @@ self.connected_trees[service_name] = connect_message.tid sendDelete(connect_message.tid) else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendDelete(self.connected_trees[service_name]) - - def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): - raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') - - def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - path = path.replace('/', '\\') - messages_history = [ ] - - def sendCreate(tid): - m = SMBMessage(ComCreateDirectoryRequest(path)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) - messages_history.append(m) - - def createCB(create_message, **kwargs): - messages_history.append(create_message) - if not create_message.status.hasError: - callback(path) - else: - errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) - - if not self.connected_trees.has_key(service_name): - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if not connect_message.status.hasError: - self.connected_trees[service_name] = connect_message.tid - sendCreate(connect_message.tid) - else: - errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendCreate(self.connected_trees[service_name]) - - def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - path = path.replace('/', '\\') - messages_history = [ ] - - def sendDelete(tid): - m = SMBMessage(ComDeleteDirectoryRequest(path)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) - messages_history.append(m) - - def deleteCB(delete_message, **kwargs): - messages_history.append(delete_message) - if not delete_message.status.hasError: - callback(path) - else: - errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) - - if not self.connected_trees.has_key(service_name): - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if not connect_message.status.hasError: - self.connected_trees[service_name] = connect_message.tid - sendDelete(connect_message.tid) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + errback(OperationFailure('Failed to delete directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) @@ -2563,6 +2903,9 @@ def _echo_SMB1(self, data, callback, errback, timeout = 30): messages_history = [ ] + if not isinstance(data, type(b'')): + raise TypeError('Echo data must be %s not %s' % (type(b'').__name__, type(data).__name__)) + def echoCB(echo_message, **kwargs): messages_history.append(echo_message) if not echo_message.status.hasError: @@ -2575,10 +2918,18 @@ self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, echoCB, errback) messages_history.append(m) + def _extractLastPathComponent(self, path): + return path.replace('\\', '/').split('/')[-1] + class SharedDevice: """ Contains information about a single shared device on the remote server. + + The following attributes are available: + + * name : An unicode string containing the name of the shared device + * comments : An unicode string containing the user description of the shared device """ # The following constants are taken from [MS-SRVS]: 2.2.2.4 @@ -2633,19 +2984,33 @@ If you encounter *SharedFile* instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains - one of these prohibited characters: "\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). + one of these prohibited characters: "\\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). + + The following attributes are available: + + * create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server + * last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server + * last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server + * last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server + * file_size : File size in number of bytes + * alloc_size : Total number of bytes allocated to store this file + * file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. + * short_name : Unicode string containing the short name of this file (usually in 8.3 notation) + * filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. + * file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 """ - def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename): + def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None): self.create_time = create_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server self.last_access_time = last_access_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server self.last_write_time = last_write_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server self.last_attr_change_time = last_attr_change_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server self.file_size = file_size #: File size in number of bytes self.alloc_size = alloc_size #: Total number of bytes allocated to store this file - self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3 + self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. self.short_name = short_name #: Unicode string containing the short name of this file (usually in 8.3 notation) self.filename = filename #: Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. + self.file_id = file_id #: Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 @property def isDirectory(self): @@ -2656,6 +3021,16 @@ def isReadOnly(self): """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY) + + @property + def isNormal(self): + """ + A convenient property to return True if this is a normal file. + + Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + """ + return (self.file_attributes==ATTR_NORMAL) or ((self.file_attributes & 0xff)==0) def __unicode__(self): return u'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory ) diff --git a/python2/smb/ntlm.py b/python2/smb/ntlm.py index ae6fc9e..e9acc36 100644 --- a/python2/smb/ntlm.py +++ b/python2/smb/ntlm.py @@ -1,5 +1,6 @@ -import types, hmac, binascii, struct, random +import types, hmac, binascii, struct, random, string +from .utils.rc4 import RC4_encrypt from utils.pyDes import des try: @@ -58,14 +59,14 @@ NTLM_FLAGS = NTLM_NegotiateUnicode | \ NTLM_RequestTarget | \ + NTLM_NegotiateSign | \ NTLM_NegotiateNTLM | \ NTLM_NegotiateAlwaysSign | \ NTLM_NegotiateExtendedSecurity | \ NTLM_NegotiateTargetInfo | \ NTLM_NegotiateVersion | \ NTLM_Negotiate128 | \ - NTLM_NegotiateKeyExchange | \ - NTLM_Negotiate56 + NTLM_NegotiateKeyExchange def generateNegotiateMessage(): """ @@ -81,7 +82,7 @@ return s -def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'): +def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, request_session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'): """ References: =========== @@ -89,6 +90,13 @@ """ FORMAT = '<8sIHHIHHIHHIHHIHHIHHII' FORMAT_SIZE = struct.calcsize(FORMAT) + + # [MS-NLMP]: 3.1.5.1.2 + # http://grutz.jingojango.net/exploits/davenport-ntlm.html + session_key = session_signing_key = request_session_key + if challenge_flags & NTLM_NegotiateKeyExchange: + session_signing_key = "".join([ random.choice(string.digits+string.ascii_letters) for _ in range(16) ]).encode('ascii') + session_key = RC4_encrypt(request_session_key, session_signing_key) lm_response_length = len(lm_response) lm_response_offset = FORMAT_SIZE @@ -125,7 +133,7 @@ session_key_length, session_key_length, session_key_offset, auth_flags) - return s + lm_response + nt_response + padding + domain_unicode + user_unicode + workstation_unicode + session_key + return s + lm_response + nt_response + padding + domain_unicode + user_unicode + workstation_unicode + session_key, session_signing_key def decodeChallengeMessage(ntlm_data): diff --git a/python2/smb/security_descriptors.py b/python2/smb/security_descriptors.py new file mode 100644 index 0000000..9e6ebe1 --- /dev/null +++ b/python2/smb/security_descriptors.py @@ -0,0 +1,367 @@ +""" +This module implements security descriptors, and the partial structures +used in them, as specified in [MS-DTYP]. +""" + +import struct + + +# Security descriptor control flags +# [MS-DTYP]: 2.4.6 +SECURITY_DESCRIPTOR_OWNER_DEFAULTED = 0x0001 +SECURITY_DESCRIPTOR_GROUP_DEFAULTED = 0x0002 +SECURITY_DESCRIPTOR_DACL_PRESENT = 0x0004 +SECURITY_DESCRIPTOR_DACL_DEFAULTED = 0x0008 +SECURITY_DESCRIPTOR_SACL_PRESENT = 0x0010 +SECURITY_DESCRIPTOR_SACL_DEFAULTED = 0x0020 +SECURITY_DESCRIPTOR_SERVER_SECURITY = 0x0040 +SECURITY_DESCRIPTOR_DACL_TRUSTED = 0x0080 +SECURITY_DESCRIPTOR_DACL_COMPUTED_INHERITANCE_REQUIRED = 0x0100 +SECURITY_DESCRIPTOR_SACL_COMPUTED_INHERITANCE_REQUIRED = 0x0200 +SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED = 0x0400 +SECURITY_DESCRIPTOR_SACL_AUTO_INHERITED = 0x0800 +SECURITY_DESCRIPTOR_DACL_PROTECTED = 0x1000 +SECURITY_DESCRIPTOR_SACL_PROTECTED = 0x2000 +SECURITY_DESCRIPTOR_RM_CONTROL_VALID = 0x4000 +SECURITY_DESCRIPTOR_SELF_RELATIVE = 0x8000 + +# ACE types +# [MS-DTYP]: 2.4.4.1 +ACE_TYPE_ACCESS_ALLOWED = 0x00 +ACE_TYPE_ACCESS_DENIED = 0x01 +ACE_TYPE_SYSTEM_AUDIT = 0x02 +ACE_TYPE_SYSTEM_ALARM = 0x03 +ACE_TYPE_ACCESS_ALLOWED_COMPOUND = 0x04 +ACE_TYPE_ACCESS_ALLOWED_OBJECT = 0x05 +ACE_TYPE_ACCESS_DENIED_OBJECT = 0x06 +ACE_TYPE_SYSTEM_AUDIT_OBJECT = 0x07 +ACE_TYPE_SYSTEM_ALARM_OBJECT = 0x08 +ACE_TYPE_ACCESS_ALLOWED_CALLBACK = 0x09 +ACE_TYPE_ACCESS_DENIED_CALLBACK = 0x0A +ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = 0x0B +ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT = 0x0C +ACE_TYPE_SYSTEM_AUDIT_CALLBACK = 0x0D +ACE_TYPE_SYSTEM_ALARM_CALLBACK = 0x0E +ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = 0x0F +ACE_TYPE_SYSTEM_ALARM_CALLBACK_OBJECT = 0x10 +ACE_TYPE_SYSTEM_MANDATORY_LABEL = 0x11 +ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE = 0x12 +ACE_TYPE_SYSTEM_SCOPED_POLICY_ID = 0x13 + +# ACE flags +# [MS-DTYP]: 2.4.4.1 +ACE_FLAG_OBJECT_INHERIT = 0x01 +ACE_FLAG_CONTAINER_INHERIT = 0x02 +ACE_FLAG_NO_PROPAGATE_INHERIT = 0x04 +ACE_FLAG_INHERIT_ONLY = 0x08 +ACE_FLAG_INHERITED = 0x10 +ACE_FLAG_SUCCESSFUL_ACCESS = 0x40 +ACE_FLAG_FAILED_ACCESS = 0x80 + +# Pre-defined well-known SIDs +# [MS-DTYP]: 2.4.2.4 +SID_NULL = "S-1-0-0" +SID_EVERYONE = "S-1-1-0" +SID_LOCAL = "S-1-2-0" +SID_CONSOLE_LOGON = "S-1-2-1" +SID_CREATOR_OWNER = "S-1-3-0" +SID_CREATOR_GROUP = "S-1-3-1" +SID_OWNER_SERVER = "S-1-3-2" +SID_GROUP_SERVER = "S-1-3-3" +SID_OWNER_RIGHTS = "S-1-3-4" +SID_NT_AUTHORITY = "S-1-5" +SID_DIALUP = "S-1-5-1" +SID_NETWORK = "S-1-5-2" +SID_BATCH = "S-1-5-3" +SID_INTERACTIVE = "S-1-5-4" +SID_SERVICE = "S-1-5-6" +SID_ANONYMOUS = "S-1-5-7" +SID_PROXY = "S-1-5-8" +SID_ENTERPRISE_DOMAIN_CONTROLLERS = "S-1-5-9" +SID_PRINCIPAL_SELF = "S-1-5-10" +SID_AUTHENTICATED_USERS = "S-1-5-11" +SID_RESTRICTED_CODE = "S-1-5-12" +SID_TERMINAL_SERVER_USER = "S-1-5-13" +SID_REMOTE_INTERACTIVE_LOGON = "S-1-5-14" +SID_THIS_ORGANIZATION = "S-1-5-15" +SID_IUSR = "S-1-5-17" +SID_LOCAL_SYSTEM = "S-1-5-18" +SID_LOCAL_SERVICE = "S-1-5-19" +SID_NETWORK_SERVICE = "S-1-5-20" +SID_COMPOUNDED_AUTHENTICATION = "S-1-5-21-0-0-0-496" +SID_CLAIMS_VALID = "S-1-5-21-0-0-0-497" +SID_BUILTIN_ADMINISTRATORS = "S-1-5-32-544" +SID_BUILTIN_USERS = "S-1-5-32-545" +SID_BUILTIN_GUESTS = "S-1-5-32-546" +SID_POWER_USERS = "S-1-5-32-547" +SID_ACCOUNT_OPERATORS = "S-1-5-32-548" +SID_SERVER_OPERATORS = "S-1-5-32-549" +SID_PRINTER_OPERATORS = "S-1-5-32-550" +SID_BACKUP_OPERATORS = "S-1-5-32-551" +SID_REPLICATOR = "S-1-5-32-552" +SID_ALIAS_PREW2KCOMPACC = "S-1-5-32-554" +SID_REMOTE_DESKTOP = "S-1-5-32-555" +SID_NETWORK_CONFIGURATION_OPS = "S-1-5-32-556" +SID_INCOMING_FOREST_TRUST_BUILDERS = "S-1-5-32-557" +SID_PERFMON_USERS = "S-1-5-32-558" +SID_PERFLOG_USERS = "S-1-5-32-559" +SID_WINDOWS_AUTHORIZATION_ACCESS_GROUP = "S-1-5-32-560" +SID_TERMINAL_SERVER_LICENSE_SERVERS = "S-1-5-32-561" +SID_DISTRIBUTED_COM_USERS = "S-1-5-32-562" +SID_IIS_IUSRS = "S-1-5-32-568" +SID_CRYPTOGRAPHIC_OPERATORS = "S-1-5-32-569" +SID_EVENT_LOG_READERS = "S-1-5-32-573" +SID_CERTIFICATE_SERVICE_DCOM_ACCESS = "S-1-5-32-574" +SID_RDS_REMOTE_ACCESS_SERVERS = "S-1-5-32-575" +SID_RDS_ENDPOINT_SERVERS = "S-1-5-32-576" +SID_RDS_MANAGEMENT_SERVERS = "S-1-5-32-577" +SID_HYPER_V_ADMINS = "S-1-5-32-578" +SID_ACCESS_CONTROL_ASSISTANCE_OPS = "S-1-5-32-579" +SID_REMOTE_MANAGEMENT_USERS = "S-1-5-32-580" +SID_WRITE_RESTRICTED_CODE = "S-1-5-33" +SID_NTLM_AUTHENTICATION = "S-1-5-64-10" +SID_SCHANNEL_AUTHENTICATION = "S-1-5-64-14" +SID_DIGEST_AUTHENTICATION = "S-1-5-64-21" +SID_THIS_ORGANIZATION_CERTIFICATE = "S-1-5-65-1" +SID_NT_SERVICE = "S-1-5-80" +SID_USER_MODE_DRIVERS = "S-1-5-84-0-0-0-0-0" +SID_LOCAL_ACCOUNT = "S-1-5-113" +SID_LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP = "S-1-5-114" +SID_OTHER_ORGANIZATION = "S-1-5-1000" +SID_ALL_APP_PACKAGES = "S-1-15-2-1" +SID_ML_UNTRUSTED = "S-1-16-0" +SID_ML_LOW = "S-1-16-4096" +SID_ML_MEDIUM = "S-1-16-8192" +SID_ML_MEDIUM_PLUS = "S-1-16-8448" +SID_ML_HIGH = "S-1-16-12288" +SID_ML_SYSTEM = "S-1-16-16384" +SID_ML_PROTECTED_PROCESS = "S-1-16-20480" +SID_AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY = "S-1-18-1" +SID_SERVICE_ASSERTED_IDENTITY = "S-1-18-2" +SID_FRESH_PUBLIC_KEY_IDENTITY = "S-1-18-3" +SID_KEY_TRUST_IDENTITY = "S-1-18-4" +SID_KEY_PROPERTY_MFA = "S-1-18-5" +SID_KEY_PROPERTY_ATTESTATION = "S-1-18-6" + + +class SID(object): + """ + A Windows security identifier. Represents a single principal, such a + user or a group, as a sequence of numbers consisting of the revision, + identifier authority, and a variable-length list of subauthorities. + + See [MS-DTYP]: 2.4.2 + """ + def __init__(self, revision, identifier_authority, subauthorities): + #: Revision, should always be 1. + self.revision = revision + #: An integer representing the identifier authority. + self.identifier_authority = identifier_authority + #: A list of integers representing all subauthorities. + self.subauthorities = subauthorities + + def __str__(self): + """ + String representation, as specified in [MS-DTYP]: 2.4.2.1 + """ + if self.identifier_authority >= 2**32: + id_auth = '%#x' % (self.identifier_authority,) + else: + id_auth = self.identifier_authority + auths = [self.revision, id_auth] + self.subauthorities + return 'S-' + '-'.join(str(subauth) for subauth in auths) + + def __repr__(self): + return 'SID(%r)' % (str(self),) + + @classmethod + def from_bytes(cls, data, return_tail=False): + revision, subauth_count = struct.unpack('Q', '\x00\x00' + data[2:8])[0] + subauth_data = data[8:] + subauthorities = [struct.unpack('= size + + body = data[header_size:size] + additional_data = {} + + # In all ACE types, the mask immediately follows the header. + mask = struct.unpack('= size + + for i in range(count): + ace_size = struct.unpack(' 0 # SMB2_SESSION_FLAG_IS_GUEST + + @property + def isAnonymousSession(self): + return (self.session_flags & 0x0002) > 0 # SMB2_SESSION_FLAG_IS_NULL + def decode(self, message): assert message.command == SMB2_COM_SESSION_SETUP @@ -362,6 +370,7 @@ def prepare(self, message): buf = self.filename.encode('UTF-16LE') + filename_len = len(buf) if self.create_context_data: n = SMB2Message.HEADER_SIZE + self.STRUCTURE_SIZE + len(buf) if n % 8 != 0: @@ -389,7 +398,7 @@ self.create_disp, self.create_options, SMB2Message.HEADER_SIZE + self.STRUCTURE_SIZE, # NameOffset - len(self.filename)*2, # NameLength in bytes + filename_len, # Length of encoded filename in bytes create_context_offset, # CreateContextOffset len(self.create_context_data) # CreateContextLength ) + buf diff --git a/python2/smb/smb_constants.py b/python2/smb/smb_constants.py index 79a7514..9947680 100644 --- a/python2/smb/smb_constants.py +++ b/python2/smb/smb_constants.py @@ -115,6 +115,7 @@ FILE_READ_EA = 0x08 FILE_WRITE_EA = 0x10 FILE_EXECUTE = 0x20 +FILE_DELETE_CHILD = 0x40 FILE_READ_ATTRIBUTES = 0x80 FILE_WRITE_ATTRIBUTES = 0x0100 DELETE = 0x010000 @@ -225,9 +226,13 @@ SMB_FILE_ATTRIBUTE_READONLY = 0x01 SMB_FILE_ATTRIBUTE_HIDDEN = 0x02 SMB_FILE_ATTRIBUTE_SYSTEM = 0x04 -SMB_FILE_ATTRIBUTE_VOLUME = 0x08 +SMB_FILE_ATTRIBUTE_VOLUME = 0x08 # Unsupported for listPath() operations SMB_FILE_ATTRIBUTE_DIRECTORY = 0x10 SMB_FILE_ATTRIBUTE_ARCHIVE = 0x20 +# SMB_FILE_ATTRIBUTE_INCL_NORMAL is a special placeholder to include normal files for +# with other search attributes for listPath() operations. It is not defined in the MS-CIFS specs. +SMB_FILE_ATTRIBUTE_INCL_NORMAL = 0x10000 +# Do not use the following values for listPath() operations as they are not supported for SMB2 SMB_SEARCH_ATTRIBUTE_READONLY = 0x0100 SMB_SEARCH_ATTRIBUTE_HIDDEN = 0x0200 SMB_SEARCH_ATTRIBUTE_SYSTEM = 0x0400 @@ -237,3 +242,16 @@ # Bitmask for OptionalSupport field in SMB_COM_TREE_CONNECT_ANDX response SMB_TREE_CONNECTX_SUPPORT_SEARCH = 0x0001 SMB_TREE_CONNECTX_SUPPORT_DFS = 0x0002 + +# Bitmask for security information fields, specified as +# AdditionalInformation in SMB2 +# [MS-SMB]: 2.2.7.4 +# [MS-SMB2]: 2.2.37 +OWNER_SECURITY_INFORMATION = 0x00000001 +GROUP_SECURITY_INFORMATION = 0x00000002 +DACL_SECURITY_INFORMATION = 0x00000004 +SACL_SECURITY_INFORMATION = 0x00000008 +LABEL_SECURITY_INFORMATION = 0x00000010 +ATTRIBUTE_SECURITY_INFORMATION = 0x00000020 +SCOPE_SECURITY_INFORMATION = 0x00000040 +BACKUP_SECURITY_INFORMATION = 0x00010000 diff --git a/python2/smb/smb_structs.py b/python2/smb/smb_structs.py index 8fab1d6..65ecac0 100644 --- a/python2/smb/smb_structs.py +++ b/python2/smb/smb_structs.py @@ -1280,7 +1280,7 @@ - [MS-CIFS]: 2.2.4.39.1 """ - def __init__(self, echo_data = '', echo_count = 1): + def __init__(self, echo_data = b'', echo_count = 1): self.echo_count = echo_count self.echo_data = echo_data diff --git a/python2/smb/utils/rc4.py b/python2/smb/utils/rc4.py new file mode 100644 index 0000000..490a2f0 --- /dev/null +++ b/python2/smb/utils/rc4.py @@ -0,0 +1,22 @@ + +def RC4_encrypt(key, data): + S = list(range(256)) + j = 0 + + key_len = len(key) + for i in list(range(256)): + j = (j + S[i] + ord(key[i % key_len])) % 256 + S[i], S[j] = S[j], S[i] + + j = 0 + y = 0 + out = [] + + for char in data: + j = (j + 1) % 256 + y = (y + S[j]) % 256 + S[j], S[y] = S[y], S[j] + + out.append(chr(ord(char) ^ S[(S[j] + S[y]) % 256])) + + return ''.join(out) diff --git a/python2/smb/utils/sha256.py b/python2/smb/utils/sha256.py index a13d6bf..6efc8de 100644 --- a/python2/smb/utils/sha256.py +++ b/python2/smb/utils/sha256.py @@ -1,4 +1,3 @@ -#!/usr/bin/python __author__ = 'Thomas Dixon' __license__ = 'MIT' diff --git a/python2/tests/DirectSMBConnectionTests/test_auth.py b/python2/tests/DirectSMBConnectionTests/test_auth.py index 3af7843..d595f87 100644 --- a/python2/tests/DirectSMBConnectionTests/test_auth.py +++ b/python2/tests/DirectSMBConnectionTests/test_auth.py @@ -4,40 +4,83 @@ from nose.tools import with_setup from smb import smb_structs -conn = None +conn, conn2, conn3 = None, None, None def teardown_func(): - global conn - conn.close() + global conn, conn2, conn3 + if conn: + conn.close() + if conn2: + conn2.close() + if conn3: + conn3.close(); @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB1(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) + +@with_setup(teardown = teardown_func) +def test_NTLMv1_auth_SMB1_callable_password(): + global conn, conn2, conn3 + smb_structs.SUPPORT_SMB2 = False + info = getConnectionInfo() + conn = SMBConnection(info['user'], lambda: info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB1(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB2(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB2(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) diff --git a/python2/tests/DirectSMBConnectionTests/test_createdeletedirectory.py b/python2/tests/DirectSMBConnectionTests/test_createdeletedirectory.py index 3cbcfe7..b6bc1a3 100644 --- a/python2/tests/DirectSMBConnectionTests/test_createdeletedirectory.py +++ b/python2/tests/DirectSMBConnectionTests/test_createdeletedirectory.py @@ -13,7 +13,7 @@ smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): @@ -21,7 +21,7 @@ smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): diff --git a/python2/tests/DirectSMBConnectionTests/test_echo.py b/python2/tests/DirectSMBConnectionTests/test_echo.py index 3375972..f86f8cc 100644 --- a/python2/tests/DirectSMBConnectionTests/test_echo.py +++ b/python2/tests/DirectSMBConnectionTests/test_echo.py @@ -9,7 +9,7 @@ def setup_func(): global conn info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): @@ -22,4 +22,3 @@ data = '%d' % random.randint(1000, 9999) assert conn.echo(data) == data - diff --git a/python2/tests/DirectSMBConnectionTests/test_listpath.py b/python2/tests/DirectSMBConnectionTests/test_listpath.py index 9d706b5..8e882a7 100644 --- a/python2/tests/DirectSMBConnectionTests/test_listpath.py +++ b/python2/tests/DirectSMBConnectionTests/test_listpath.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection +from smb.smb_constants import * from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs @@ -11,14 +12,14 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): @@ -45,6 +46,13 @@ assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathWithManyFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames)==999 + @with_setup(setup_func_SMB2, teardown_func) def test_listPath_SMB2(): global conn @@ -64,3 +72,86 @@ assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathWithManyFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames)==999 + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterForDirectory_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterForDirectory_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterForFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterForFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterPattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterPattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterUnicodePattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterUnicodePattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames diff --git a/python2/tests/DirectSMBConnectionTests/test_listshares.py b/python2/tests/DirectSMBConnectionTests/test_listshares.py index 67c8378..e13bb87 100644 --- a/python2/tests/DirectSMBConnectionTests/test_listshares.py +++ b/python2/tests/DirectSMBConnectionTests/test_listshares.py @@ -10,14 +10,14 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): diff --git a/python2/tests/DirectSMBConnectionTests/test_listsnapshots.py b/python2/tests/DirectSMBConnectionTests/test_listsnapshots.py index dfc661c..ba1890e 100644 --- a/python2/tests/DirectSMBConnectionTests/test_listsnapshots.py +++ b/python2/tests/DirectSMBConnectionTests/test_listsnapshots.py @@ -10,14 +10,14 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): diff --git a/python2/tests/DirectSMBConnectionTests/test_rename.py b/python2/tests/DirectSMBConnectionTests/test_rename.py index f9896fa..356c2ad 100644 --- a/python2/tests/DirectSMBConnectionTests/test_rename.py +++ b/python2/tests/DirectSMBConnectionTests/test_rename.py @@ -13,14 +13,14 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): diff --git a/python2/tests/DirectSMBConnectionTests/test_retrievefile.py b/python2/tests/DirectSMBConnectionTests/test_retrievefile.py index 023d8ce..10aff75 100644 --- a/python2/tests/DirectSMBConnectionTests/test_retrievefile.py +++ b/python2/tests/DirectSMBConnectionTests/test_retrievefile.py @@ -20,14 +20,14 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): diff --git a/python2/tests/DirectSMBConnectionTests/test_storefile.py b/python2/tests/DirectSMBConnectionTests/test_storefile.py index a37c24b..dc8df6f 100644 --- a/python2/tests/DirectSMBConnectionTests/test_storefile.py +++ b/python2/tests/DirectSMBConnectionTests/test_storefile.py @@ -25,7 +25,7 @@ smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): @@ -33,7 +33,7 @@ smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): diff --git a/python2/tests/DirectSMBConnectionTests/util.py b/python2/tests/DirectSMBConnectionTests/util.py index aa9eb41..12f82af 100644 --- a/python2/tests/DirectSMBConnectionTests/util.py +++ b/python2/tests/DirectSMBConnectionTests/util.py @@ -10,7 +10,7 @@ info = { 'server_name': cp.get('server', 'name'), 'server_ip': cp.get('server', 'ip'), - 'server_port': cp.getint('server', 'port'), + 'server_port': cp.getint('server', 'direct_port'), 'client_name': cp.get('client', 'name'), 'user': cp.get('user', 'name'), 'password': cp.get('user', 'password'), diff --git a/python2/tests/README.md b/python2/tests/README.md new file mode 100644 index 0000000..16ee904 --- /dev/null +++ b/python2/tests/README.md @@ -0,0 +1,58 @@ + +Steps to Follow to Run the Unit Tests +===================================== + +## Step 1: Install system dependencies ## + +If you are using Ubuntu 20.04 LTS, you can install the system dependencies with the following command +``` +$> apt-get install virtualenv python-dev gcc g++ make automake autoconf +``` +For other distributions, you can use their package managers and install the system dependencies (although the package names might differ slightly). + +## Step 2: Setup python virtualenv ## + +We will create a python2 virtualenv and install the python dependencies for testing in the "venv2" folder. + +``` +$> cd /python2 +$> virtualenv -p /usr/bin/python2 venv2 +$> source venv2/bin/activate +$venv2> pip install nose pyasn1 twisted +``` + +## Step 3: Setup shared folder on your remote SMB server ## + +Prepare a shared folder called "smbtest" on your remote SMB server (Windows or Samba). + +Then, download [smbtest.zip](https://miketeo.net/files/Projects/pysmb/smbtest.zip) and unzip the contents of this zip file in the shared folder. + +You should also configure a user on the SMB server with read-write access to the "smbtest" folder. + +## Step 4: Update connection details in connection.ini ## + +In the same folder where you are viewing this readme file, there should be an ini file called "connection.ini". Edit this file's connection details to match the shared folder's access information. + +## Step 5: Run the unit tests in the python2 folder ## + +Before running the tests, the venv2 virtualenv must be activated. +``` +$> cd /python2 +$> source venv2/bin/activate +``` + +To run all the tests: +``` + $venv2> nosetests -v tests +``` + +To selectively run some tests: +``` + $venv2> nosetests -v tests/SMBConnectionTests + $venv2> nosetests -v tests/SMBConnectionTests/test_rename.py + $venv2> nosetests -v tests/SMBConnectionTests/test_rename.py:test_rename_english_file_SMB1 +``` + +For more information, please consult the [documentation for nose](https://nose.readthedocs.io/). + + diff --git a/python2/tests/README_1st.txt b/python2/tests/README_1st.txt deleted file mode 100644 index aa06a7c..0000000 --- a/python2/tests/README_1st.txt +++ /dev/null @@ -1,32 +0,0 @@ - -Steps to Follow to Run the Unit Tests -===================================== - -1a. Install Nose Testing Framework -All the unit tests here are designed to be conducted with the nose testing framework. -You can install the latest nose testing framework by running: easy_install nose -For more information on nose testing, please visit http://readthedocs.org/docs/nose/en/latest/ - -1b. Install the Twisted framework -If you need to test the SMB/NetBIOS protocol implementations for Twisted framework, -you should install the Twisted framework from http://twistedmatrix.com/ -or by running: easy_install Twisted -Without the Twisted framework, the Twisted tests will fail. - -2. Prepare a Shared Folder "smbtest" on a Remote Server -To run the unit tests here, besides installing the nose testing framework, you will -also need to prepare a shared folder on a remote server. -pysmb has been tested against Samba 3.x, Windows XP SP3 and Windows Vista. -The shared folder must be named "smbtest". - -3. Unzip smbtest.zip in the Shared Folder -In the same folder where you are viewing this readme file, there should be a zip file -called "smbtest.zip". Unzip the contents of this zip file in the shared folder. - -4. Update Connection Details in connection.ini -In the same folder where you are viewing this readme file, there should be an ini file -called "connection.ini". Edit this file's connection details to match the shared folder's -access information. - -5. Run the Unit Tests -Just run: nosetests diff --git a/python2/tests/SMBConnectionTests/test_auth.py b/python2/tests/SMBConnectionTests/test_auth.py index 3d55f20..211e079 100644 --- a/python2/tests/SMBConnectionTests/test_auth.py +++ b/python2/tests/SMBConnectionTests/test_auth.py @@ -4,11 +4,16 @@ from nose.tools import with_setup from smb import smb_structs -conn = None +conn, conn2, conn3 = None, None, None def teardown_func(): - global conn - conn.close() + global conn, conn2, conn3 + if conn: + conn.close() + if conn2: + conn2.close() + if conn3: + conn3.close(); @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB1(): @@ -18,6 +23,12 @@ conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) + assert not conn3.connect(info['server_ip'], info['server_port']) + @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB1(): global conn @@ -25,6 +36,12 @@ info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) + assert not conn3.connect(info['server_ip'], info['server_port']) @with_setup(teardown = teardown_func) def test_NTLMv1_auth_SMB2(): @@ -34,6 +51,12 @@ conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False) + assert not conn3.connect(info['server_ip'], info['server_port']) + @with_setup(teardown = teardown_func) def test_NTLMv2_auth_SMB2(): global conn @@ -41,3 +64,9 @@ info = getConnectionInfo() conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True) + assert not conn3.connect(info['server_ip'], info['server_port']) diff --git a/python2/tests/SMBConnectionTests/test_deletepattern.py b/python2/tests/SMBConnectionTests/test_deletepattern.py index 23b0774..7a2689d 100644 --- a/python2/tests/SMBConnectionTests/test_deletepattern.py +++ b/python2/tests/SMBConnectionTests/test_deletepattern.py @@ -30,17 +30,24 @@ conn.close() @with_setup(setup_func_SMB1, teardown_func) -def test_delete_SMB1(): - global conn - - path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) - conn.createDirectory('smbtest', path) - - for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: - conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) - - results = conn.listPath('smbtest', path) - filenames = map(lambda r: r.filename, results) +def test_delete_without_subfolder_SMB1(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames @@ -51,6 +58,8 @@ results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames @@ -61,25 +70,80 @@ results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) - assert 'aaTest.bin' not in filenames - assert 'aaBest.bin' in filenames - assert 'random.txt' in filenames - - conn.deleteFiles('smbtest', path+'/*') - conn.deleteDirectory('smbtest', path) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + +@with_setup(setup_func_SMB1, teardown_func) +def test_delete_with_subfolder_SMB1(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' in filenames + assert 'aaBest.txt' in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' not in filenames + assert 'aaBest.txt' not in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' not in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + @with_setup(setup_func_SMB2, teardown_func) -def test_delete_SMB2(): - global conn - - path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) - conn.createDirectory('smbtest', path) - - for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: - conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) - - results = conn.listPath('smbtest', path) - filenames = map(lambda r: r.filename, results) +def test_delete_without_subfolder_SMB2(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames @@ -90,6 +154,8 @@ results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames @@ -100,6 +166,55 @@ results = conn.listPath('smbtest', path) filenames = map(lambda r: r.filename, results) - assert 'aaTest.bin' not in filenames - assert 'aaBest.bin' in filenames - assert 'random.txt' in filenames + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_delete_with_subfolder_SMB2(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, StringIO("0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, StringIO("0123456789")) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' in filenames + assert 'aaBest.txt' in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' not in filenames + assert 'aaBest.txt' not in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = map(lambda r: r.filename, results) + assert 'aaTest.Folder' not in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames diff --git a/python2/tests/SMBConnectionTests/test_listpath.py b/python2/tests/SMBConnectionTests/test_listpath.py index 9d706b5..82ad2fd 100644 --- a/python2/tests/SMBConnectionTests/test_listpath.py +++ b/python2/tests/SMBConnectionTests/test_listpath.py @@ -1,6 +1,7 @@ # -*- coding: utf-8 -*- from smb.SMBConnection import SMBConnection +from smb.smb_constants import * from util import getConnectionInfo from nose.tools import with_setup from smb import smb_structs @@ -45,6 +46,13 @@ assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathWithManyFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames)==999 + @with_setup(setup_func_SMB2, teardown_func) def test_listPath_SMB2(): global conn @@ -64,3 +72,98 @@ assert ( u'Test File.txt', False ) in filenames assert ( u'Test Folder', True ) in filenames assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathWithManyFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames)==999 + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterForDirectory_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterForDirectory_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterForFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterForFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterPattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterPattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterUnicodePattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterUnicodePattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB1, teardown_func) +def test_listPathFilterEmptyList_SMB1(): + global conn + results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + +@with_setup(setup_func_SMB2, teardown_func) +def test_listPathFilterEmptyList_SMB2(): + global conn + results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) diff --git a/python2/tests/SMBConnectionTests/test_security.py b/python2/tests/SMBConnectionTests/test_security.py new file mode 100644 index 0000000..205b119 --- /dev/null +++ b/python2/tests/SMBConnectionTests/test_security.py @@ -0,0 +1,34 @@ +# -*- coding: utf-8 -*- + +import os, tempfile +from StringIO import StringIO +from smb.SMBConnection import SMBConnection +from util import getConnectionInfo +from nose.tools import with_setup +from smb import smb_structs + +try: + import hashlib + def MD5(): return hashlib.md5() +except ImportError: + import md5 + def MD5(): return md5.new() + +conn = None + +def setup_func_SMB2(): + global conn + smb_structs.SUPPORT_SMB2 = True + info = getConnectionInfo() + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + assert conn.connect(info['server_ip'], info['server_port']) + +def teardown_func(): + global conn + conn.close() + +@with_setup(setup_func_SMB2, teardown_func) +def test_security_SMB2(): + global conn + # TODO: Need a way to setup the environment on the remote server and perform some verification on the returned results. + attributes = conn.getSecurity('smbtest', '/rfc1001.txt') diff --git a/python2/tests/SMBConnectionTests/test_with_context.py b/python2/tests/SMBConnectionTests/test_with_context.py new file mode 100644 index 0000000..58d9567 --- /dev/null +++ b/python2/tests/SMBConnectionTests/test_with_context.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +from smb.SMBConnection import SMBConnection +from .util import getConnectionInfo + +def test_context(): + info = getConnectionInfo() + with SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) as conn: + assert conn.connect(info['server_ip'], info['server_port']) + + assert conn.sock is None diff --git a/python2/tests/connection.ini b/python2/tests/connection.ini index 96d2652..d8d249d 100644 --- a/python2/tests/connection.ini +++ b/python2/tests/connection.ini @@ -3,6 +3,7 @@ name = SERVER ip = 192.168.1.1 port = 139 +direct_port = 445 [client] name = TESTCLIENT diff --git a/python2/tests/smbtest.7z b/python2/tests/smbtest.7z deleted file mode 100644 index c5c9f42..0000000 Binary files a/python2/tests/smbtest.7z and /dev/null differ diff --git a/python2/tests/test_security_descriptors.py b/python2/tests/test_security_descriptors.py new file mode 100644 index 0000000..f81be4b --- /dev/null +++ b/python2/tests/test_security_descriptors.py @@ -0,0 +1,139 @@ +import binascii + +from smb import security_descriptors as sd +from smb import smb_constants as sc + + +def test_sid_string_representation(): + sid = sd.SID(1, 5, [2, 3, 4]) + assert str(sid) == "S-1-5-2-3-4" + sid = sd.SID(1, 2**32 + 3, []) + assert str(sid) == "S-1-0x100000003" + sid = sd.SID(1, 2**32, [3, 2, 1]) + assert str(sid) == "S-1-0x100000000-3-2-1" + + +def test_sid_binary_parsing(): + raw_sid = binascii.unhexlify(""" + 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a + 2a 4f da ca c1 79 a6 32 b1 04 00 00 + """.translate(None, ' \n')) + assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" + raw_sid += "garbage" + assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" + sid, tail = sd.SID.from_bytes(raw_sid, return_tail=True) + assert str(sid) == "S-1-5-21-717312990-3403304746-849770945-1201" + assert tail == "garbage" + + +def test_ace_binary_parsing(): + raw_ace = binascii.unhexlify(""" + 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 + 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 + 6e 04 00 00 + """.translate(None, ' \n')) + ace = sd.ACE.from_bytes(raw_ace) + assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1134" + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert ace.flags == sd.ACE_FLAG_INHERITED + assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC + | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA + | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA + | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE + | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES + | sc.FILE_WRITE_ATTRIBUTES) + assert not ace.additional_data + + raw_ace = binascii.unhexlify(""" + 00 13 18 00 a9 00 12 00 01 02 00 00 00 00 00 05 + 20 00 00 00 21 02 00 00 + """.translate(None, ' \n')) + ace = sd.ACE.from_bytes(raw_ace) + assert str(ace.sid) == "S-1-5-32-545" + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert ace.flags == (sd.ACE_FLAG_INHERITED | sd.ACE_FLAG_CONTAINER_INHERIT + | sd.ACE_FLAG_OBJECT_INHERIT) + assert ace.mask == (sc.SYNCHRONIZE | sc.READ_CONTROL | sc.FILE_READ_DATA + | sc.FILE_READ_EA | sc.FILE_EXECUTE + | sc.FILE_READ_ATTRIBUTES) + assert not ace.additional_data + + raw_ace = binascii.unhexlify(""" + 01 03 24 00 a9 00 02 00 01 05 00 00 00 00 00 05 + 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 + 6c 04 00 00 + """.translate(None, ' \n')) + ace = sd.ACE.from_bytes(raw_ace) + assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1132" + assert ace.type == sd.ACE_TYPE_ACCESS_DENIED + assert ace.flags == (sd.ACE_FLAG_CONTAINER_INHERIT + | sd.ACE_FLAG_OBJECT_INHERIT) + assert ace.mask == (sc.READ_CONTROL | sc.FILE_READ_DATA | sc.FILE_READ_EA + | sc.FILE_EXECUTE | sc.FILE_READ_ATTRIBUTES) + assert not ace.additional_data + + +def test_acl_binary_parsing(): + raw_acl = binascii.unhexlify(""" + 02 00 70 00 04 00 00 00 00 10 18 00 89 00 10 00 + 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 + 00 10 14 00 ff 01 1f 00 01 01 00 00 00 00 00 05 + 12 00 00 00 00 10 18 00 ff 01 1f 00 01 02 00 00 + 00 00 00 05 20 00 00 00 20 02 00 00 00 10 24 00 + ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 + de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 + """.translate(None, ' \n')) + acl = sd.ACL.from_bytes(raw_acl) + assert acl.revision == 2 + assert len(acl.aces) == 4 + + ace = acl.aces[0] + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert str(ace.sid) == "S-1-5-32-545" + assert ace.flags == sd.ACE_FLAG_INHERITED + assert ace.mask == (sc.SYNCHRONIZE | sc.FILE_READ_DATA | sc.FILE_READ_EA + | sc.FILE_READ_ATTRIBUTES) + + ace = acl.aces[3] + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1201" + assert ace.flags == sd.ACE_FLAG_INHERITED + assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC + | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA + | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA + | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE + | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES + | sc.FILE_WRITE_ATTRIBUTES) + + +def test_descriptor_binary_parsing(): + raw_descriptor = binascii.unhexlify(""" + 01 00 04 84 14 00 00 00 30 00 00 00 00 00 00 00 + 4c 00 00 00 01 05 00 00 00 00 00 05 15 00 00 00 + de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 + 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a + 2a 4f da ca c1 79 a6 32 01 02 00 00 02 00 70 00 + 04 00 00 00 00 10 18 00 89 00 10 00 01 02 00 00 + 00 00 00 05 20 00 00 00 21 02 00 00 00 10 14 00 + ff 01 1f 00 01 01 00 00 00 00 00 05 12 00 00 00 + 00 10 18 00 ff 01 1f 00 01 02 00 00 00 00 00 05 + 20 00 00 00 20 02 00 00 00 10 24 00 ff 01 1f 00 + 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a + 2a 4f da ca c1 79 a6 32 b1 04 00 00 + """.translate(None, ' \n')) + descriptor = sd.SecurityDescriptor.from_bytes(raw_descriptor) + assert descriptor.flags == (sd.SECURITY_DESCRIPTOR_SELF_RELATIVE + | sd.SECURITY_DESCRIPTOR_DACL_PRESENT + | sd.SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED) + assert descriptor.dacl is not None + assert descriptor.sacl is None + assert str(descriptor.owner) == "S-1-5-21-717312990-3403304746-849770945-1201" + assert str(descriptor.group) == "S-1-5-21-717312990-3403304746-849770945-513" + + acl = descriptor.dacl + assert acl.revision == 2 + assert len(acl.aces) == 4 + assert str(acl.aces[0].sid) == sd.SID_BUILTIN_USERS + assert str(acl.aces[1].sid) == sd.SID_LOCAL_SYSTEM + assert str(acl.aces[2].sid) == sd.SID_BUILTIN_ADMINISTRATORS + assert str(acl.aces[3].sid) == "S-1-5-21-717312990-3403304746-849770945-1201" diff --git a/python3/nmb/base.py b/python3/nmb/base.py index e161a18..f3e7651 100644 --- a/python3/nmb/base.py +++ b/python3/nmb/base.py @@ -77,6 +77,9 @@ self.onNMBSessionOK() elif packet.type == NEGATIVE_SESSION_RESPONSE: self.onNMBSessionFailed() + elif packet.type == SESSION_KEEPALIVE: + # Discard keepalive packets - [RFC1002]: 5.2.2.1 + pass else: self.log.warning('Unrecognized NMB session type: 0x%02x', packet.type) @@ -153,21 +156,25 @@ opcode = (code >> 11) & 0x0F flags = (code >> 4) & 0x7F rcode = code & 0x0F - numnames = data[self.HEADER_STRUCT_SIZE + 44] - if numnames > 0: - ret = [ ] - offset = self.HEADER_STRUCT_SIZE + 45 + try: + numnames = data[self.HEADER_STRUCT_SIZE + 44] - for i in range(0, numnames): - mynme = data[offset:offset + 15] - mynme = mynme.strip() - ret.append(( str(mynme, 'ascii'), data[offset+15] )) - offset += 18 + if numnames > 0: + ret = [ ] + offset = self.HEADER_STRUCT_SIZE + 45 - return trn_id, ret - else: - return trn_id, None + for i in range(0, numnames): + mynme = data[offset:offset + 15] + mynme = mynme.strip() + ret.append(( str(mynme, 'ascii'), data[offset+15] )) + offset += 18 + + return trn_id, ret + except IndexError: + pass + + return trn_id, None # # Contributed by Jason Anderson diff --git a/python3/pysmb.egg-info/PKG-INFO b/python3/pysmb.egg-info/PKG-INFO new file mode 100644 index 0000000..e5c24c8 --- /dev/null +++ b/python3/pysmb.egg-info/PKG-INFO @@ -0,0 +1,26 @@ +Metadata-Version: 1.1 +Name: pysmb +Version: 1.2.7 +Summary: pysmb is an experimental SMB/CIFS library written in Python to support file sharing between Windows and Linux machines +Home-page: https://miketeo.net/projects/pysmb +Author: Michael Teo +Author-email: miketeo@miketeo.net +License: zlib/libpng +Description: pysmb is an experimental SMB/CIFS library written in Python. It implements the client-side SMB/CIFS protocol which allows your Python application to access and transfer files to/from SMB/CIFS shared folders like your Windows file sharing and Samba folders. +Keywords: windows samba cifs sharing ftp smb linux +Platform: UNKNOWN +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Win32 (MS Windows) +Classifier: Environment :: Console +Classifier: License :: OSI Approved :: zlib/libpng License +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 2.4 +Classifier: Programming Language :: Python :: 2.5 +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Topic :: Communications :: File Sharing +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: System :: Networking diff --git a/python3/pysmb.egg-info/SOURCES.txt b/python3/pysmb.egg-info/SOURCES.txt new file mode 100644 index 0000000..daeebd8 --- /dev/null +++ b/python3/pysmb.egg-info/SOURCES.txt @@ -0,0 +1,261 @@ +CHANGELOG +LICENSE +MANIFEST.in +README.txt +setup.py +docs/doctrees/environment.pickle +docs/doctrees/extending.doctree +docs/doctrees/index.doctree +docs/doctrees/upgrading.doctree +docs/doctrees/api/nmb_NBNSProtocol.doctree +docs/doctrees/api/nmb_NetBIOS.doctree +docs/doctrees/api/smb_SMBConnection.doctree +docs/doctrees/api/smb_SMBHandler.doctree +docs/doctrees/api/smb_SMBProtocolFactory.doctree +docs/doctrees/api/smb_SharedDevice.doctree +docs/doctrees/api/smb_SharedFile.doctree +docs/doctrees/api/smb_exceptions.doctree +docs/doctrees/api/smb_security_descriptors.doctree +docs/html/.buildinfo +docs/html/extending.html +docs/html/genindex.html +docs/html/index.html +docs/html/objects.inv +docs/html/py-modindex.html +docs/html/search.html +docs/html/searchindex.js +docs/html/upgrading.html +docs/html/_modules/index.html +docs/html/_modules/nmb/NetBIOS.html +docs/html/_modules/nmb/NetBIOSProtocol.html +docs/html/_modules/smb/SMBConnection.html +docs/html/_modules/smb/SMBProtocol.html +docs/html/_modules/smb/base.html +docs/html/_modules/smb/security_descriptors.html +docs/html/_modules/smb/smb_structs.html +docs/html/_sources/extending.rst.txt +docs/html/_sources/extending.txt +docs/html/_sources/index.rst.txt +docs/html/_sources/index.txt +docs/html/_sources/upgrading.rst.txt +docs/html/_sources/upgrading.txt +docs/html/_sources/api/nmb_NBNSProtocol.rst.txt +docs/html/_sources/api/nmb_NBNSProtocol.txt +docs/html/_sources/api/nmb_NetBIOS.rst.txt +docs/html/_sources/api/nmb_NetBIOS.txt +docs/html/_sources/api/smb_SMBConnection.rst.txt +docs/html/_sources/api/smb_SMBConnection.txt +docs/html/_sources/api/smb_SMBHandler.rst.txt +docs/html/_sources/api/smb_SMBHandler.txt +docs/html/_sources/api/smb_SMBProtocolFactory.rst.txt +docs/html/_sources/api/smb_SMBProtocolFactory.txt +docs/html/_sources/api/smb_SharedDevice.rst.txt +docs/html/_sources/api/smb_SharedDevice.txt +docs/html/_sources/api/smb_SharedFile.rst.txt +docs/html/_sources/api/smb_SharedFile.txt +docs/html/_sources/api/smb_exceptions.rst.txt +docs/html/_sources/api/smb_exceptions.txt +docs/html/_sources/api/smb_security_descriptors.rst.txt +docs/html/_sources/api/smb_security_descriptors.txt +docs/html/_static/ajax-loader.gif +docs/html/_static/basic.css +docs/html/_static/comment-bright.png +docs/html/_static/comment-close.png +docs/html/_static/comment.png +docs/html/_static/contents.png +docs/html/_static/doctools.js +docs/html/_static/documentation_options.js +docs/html/_static/down-pressed.png +docs/html/_static/down.png +docs/html/_static/file.png +docs/html/_static/jquery-3.5.1.js +docs/html/_static/jquery.js +docs/html/_static/language_data.js +docs/html/_static/minus.png +docs/html/_static/navigation.png +docs/html/_static/plus.png +docs/html/_static/pygments.css +docs/html/_static/searchtools.js +docs/html/_static/sphinxdoc.css +docs/html/_static/underscore-1.3.1.js +docs/html/_static/underscore.js +docs/html/_static/up-pressed.png +docs/html/_static/up.png +docs/html/_static/websupport.js +docs/html/api/nmb_NBNSProtocol.html +docs/html/api/nmb_NetBIOS.html +docs/html/api/smb_SMBConnection.html +docs/html/api/smb_SMBHandler.html +docs/html/api/smb_SMBProtocolFactory.html +docs/html/api/smb_SharedDevice.html +docs/html/api/smb_SharedFile.html +docs/html/api/smb_exceptions.html +docs/html/api/smb_security_descriptors.html +python2/nmb/NetBIOS.py +python2/nmb/NetBIOSProtocol.py +python2/nmb/__init__.py +python2/nmb/base.py +python2/nmb/nmb_constants.py +python2/nmb/nmb_structs.py +python2/nmb/utils.py +python2/smb/SMBConnection.py +python2/smb/SMBHandler.py +python2/smb/SMBProtocol.py +python2/smb/__init__.py +python2/smb/base.py +python2/smb/ntlm.py +python2/smb/security_descriptors.py +python2/smb/securityblob.py +python2/smb/smb2_constants.py +python2/smb/smb2_structs.py +python2/smb/smb_constants.py +python2/smb/smb_structs.py +python2/smb/utils/README.txt +python2/smb/utils/U32.py +python2/smb/utils/__init__.py +python2/smb/utils/md4.py +python2/smb/utils/pyDes.py +python2/smb/utils/rc4.py +python2/smb/utils/sha256.py +python2/tests/README.md +python2/tests/__init__.py +python2/tests/connection.ini +python2/tests/test_ntlm.py +python2/tests/test_security_descriptors.py +python2/tests/test_securityblob.py +python2/tests/DirectSMBConnectionTests/__init__.py +python2/tests/DirectSMBConnectionTests/test_SMBHandler.py +python2/tests/DirectSMBConnectionTests/test_auth.py +python2/tests/DirectSMBConnectionTests/test_createdeletedirectory.py +python2/tests/DirectSMBConnectionTests/test_echo.py +python2/tests/DirectSMBConnectionTests/test_listpath.py +python2/tests/DirectSMBConnectionTests/test_listshares.py +python2/tests/DirectSMBConnectionTests/test_listsnapshots.py +python2/tests/DirectSMBConnectionTests/test_rename.py +python2/tests/DirectSMBConnectionTests/test_retrievefile.py +python2/tests/DirectSMBConnectionTests/test_storefile.py +python2/tests/DirectSMBConnectionTests/util.py +python2/tests/DirectSMBTwistedTests/test_auth.py +python2/tests/DirectSMBTwistedTests/test_createdeletedirectory.py +python2/tests/DirectSMBTwistedTests/test_echo.py +python2/tests/DirectSMBTwistedTests/test_listpath.py +python2/tests/DirectSMBTwistedTests/test_listshares.py +python2/tests/DirectSMBTwistedTests/test_listsnapshots.py +python2/tests/DirectSMBTwistedTests/test_rename.py +python2/tests/DirectSMBTwistedTests/test_retrievefile.py +python2/tests/DirectSMBTwistedTests/test_storefile.py +python2/tests/DirectSMBTwistedTests/util.py +python2/tests/NetBIOSTests/__init__.py +python2/tests/NetBIOSTests/test_queryname.py +python2/tests/NetBIOSTwistedTests/__init__.py +python2/tests/NetBIOSTwistedTests/test_queryname.py +python2/tests/SMBConnectionTests/__init__.py +python2/tests/SMBConnectionTests/test_SMBHandler.py +python2/tests/SMBConnectionTests/test_auth.py +python2/tests/SMBConnectionTests/test_createdeletedirectory.py +python2/tests/SMBConnectionTests/test_deletepattern.py +python2/tests/SMBConnectionTests/test_echo.py +python2/tests/SMBConnectionTests/test_getattributes.py +python2/tests/SMBConnectionTests/test_listpath.py +python2/tests/SMBConnectionTests/test_listshares.py +python2/tests/SMBConnectionTests/test_listsnapshots.py +python2/tests/SMBConnectionTests/test_rename.py +python2/tests/SMBConnectionTests/test_retrievefile.py +python2/tests/SMBConnectionTests/test_security.py +python2/tests/SMBConnectionTests/test_storefile.py +python2/tests/SMBConnectionTests/test_with_context.py +python2/tests/SMBConnectionTests/util.py +python2/tests/SMBTwistedTests/__init__.py +python2/tests/SMBTwistedTests/test_auth.py +python2/tests/SMBTwistedTests/test_createdeletedirectory.py +python2/tests/SMBTwistedTests/test_echo.py +python2/tests/SMBTwistedTests/test_getattributes.py +python2/tests/SMBTwistedTests/test_listpath.py +python2/tests/SMBTwistedTests/test_listshares.py +python2/tests/SMBTwistedTests/test_listsnapshots.py +python2/tests/SMBTwistedTests/test_rename.py +python2/tests/SMBTwistedTests/test_retrievefile.py +python2/tests/SMBTwistedTests/test_storefile.py +python2/tests/SMBTwistedTests/util.py +python2/tests/SupportFiles/binary.dat +python3/nmb/NetBIOS.py +python3/nmb/NetBIOSProtocol.py +python3/nmb/__init__.py +python3/nmb/base.py +python3/nmb/nmb_constants.py +python3/nmb/nmb_structs.py +python3/nmb/utils.py +python3/pysmb.egg-info/PKG-INFO +python3/pysmb.egg-info/SOURCES.txt +python3/pysmb.egg-info/dependency_links.txt +python3/pysmb.egg-info/requires.txt +python3/pysmb.egg-info/top_level.txt +python3/smb/SMBConnection.py +python3/smb/SMBHandler.py +python3/smb/SMBProtocol.py +python3/smb/__init__.py +python3/smb/base.py +python3/smb/ntlm.py +python3/smb/security_descriptors.py +python3/smb/securityblob.py +python3/smb/smb2_constants.py +python3/smb/smb2_structs.py +python3/smb/smb_constants.py +python3/smb/smb_structs.py +python3/smb/utils/U32.py +python3/smb/utils/__init__.py +python3/smb/utils/md4.py +python3/smb/utils/pyDes.py +python3/smb/utils/rc4.py +python3/smb/utils/sha256.py +python3/tests/README.md +python3/tests/__init__.py +python3/tests/connection.ini +python3/tests/test_ntlm.py +python3/tests/test_security_descriptors.py +python3/tests/test_securityblob.py +python3/tests/DirectSMBConnectionTests/__init__.py +python3/tests/DirectSMBConnectionTests/test_auth.py +python3/tests/DirectSMBConnectionTests/test_createdeletedirectory.py +python3/tests/DirectSMBConnectionTests/test_echo.py +python3/tests/DirectSMBConnectionTests/test_listpath.py +python3/tests/DirectSMBConnectionTests/test_listshares.py +python3/tests/DirectSMBConnectionTests/test_listsnapshots.py +python3/tests/DirectSMBConnectionTests/test_rename.py +python3/tests/DirectSMBConnectionTests/test_retrievefile.py +python3/tests/DirectSMBConnectionTests/test_storefile.py +python3/tests/DirectSMBConnectionTests/util.py +python3/tests/NetBIOSTests/__init__.py +python3/tests/NetBIOSTests/test_queryname.py +python3/tests/SMBConnectionTests/__init__.py +python3/tests/SMBConnectionTests/test_SMBHandler.py +python3/tests/SMBConnectionTests/test_auth.py +python3/tests/SMBConnectionTests/test_createdeletedirectory.py +python3/tests/SMBConnectionTests/test_deletepattern.py +python3/tests/SMBConnectionTests/test_echo.py +python3/tests/SMBConnectionTests/test_getattributes.py +python3/tests/SMBConnectionTests/test_listpath.py +python3/tests/SMBConnectionTests/test_listshares.py +python3/tests/SMBConnectionTests/test_listsnapshots.py +python3/tests/SMBConnectionTests/test_rename.py +python3/tests/SMBConnectionTests/test_retrievefile.py +python3/tests/SMBConnectionTests/test_storefile.py +python3/tests/SMBConnectionTests/test_with_context.py +python3/tests/SMBConnectionTests/util.py +python3/tests/SupportFiles/binary.dat +sphinx/Makefile +sphinx/make.bat +sphinx/requirements.txt +sphinx/source/conf.py +sphinx/source/extending.rst +sphinx/source/index.rst +sphinx/source/upgrading.rst +sphinx/source/api/nmb_NBNSProtocol.rst +sphinx/source/api/nmb_NetBIOS.rst +sphinx/source/api/smb_SMBConnection.rst +sphinx/source/api/smb_SMBHandler.rst +sphinx/source/api/smb_SMBProtocolFactory.rst +sphinx/source/api/smb_SharedDevice.rst +sphinx/source/api/smb_SharedFile.rst +sphinx/source/api/smb_exceptions.rst +sphinx/source/api/smb_security_descriptors.rst \ No newline at end of file diff --git a/python3/pysmb.egg-info/dependency_links.txt b/python3/pysmb.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/python3/pysmb.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/python3/pysmb.egg-info/requires.txt b/python3/pysmb.egg-info/requires.txt new file mode 100644 index 0000000..38fe414 --- /dev/null +++ b/python3/pysmb.egg-info/requires.txt @@ -0,0 +1 @@ +pyasn1 diff --git a/python3/pysmb.egg-info/top_level.txt b/python3/pysmb.egg-info/top_level.txt new file mode 100644 index 0000000..65ad110 --- /dev/null +++ b/python3/pysmb.egg-info/top_level.txt @@ -0,0 +1,2 @@ +nmb +smb diff --git a/python3/smb/SMBConnection.py b/python3/smb/SMBConnection.py index 172d203..4c36561 100644 --- a/python3/smb/SMBConnection.py +++ b/python3/smb/SMBConnection.py @@ -21,6 +21,7 @@ Create a new SMBConnection instance. *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server. + *password* can be a string or a callable returning a string. File operations can only be proceeded after the connection has been authenticated successfully. Note that you need to call *connect* method to actually establish the SMB connection to the remote server and perform authentication. @@ -29,7 +30,7 @@ Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445. :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from. - You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\/:*?";|+`` + You can freely choose a name as long as it contains a maximum of 15 alphanumeric characters and does not contain spaces and any of ``\\/:*?";|+`` :param string remote_name: The NetBIOS machine name of the remote server. On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties". This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected. @@ -72,6 +73,15 @@ total_sent = total_sent + sent # + # Support for "with" context + # + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + # # Misc Properties # @@ -85,22 +95,27 @@ # Public Methods # - def connect(self, ip, port = 139, sock_family = socket.AF_INET, timeout = 60): + def connect(self, ip, port = 139, sock_family = None, timeout = 60): """ Establish the SMB connection to the remote SMB/CIFS server. You must call this method before attempting any of the file operations with the remote server. This method will block until the SMB connection has attempted at least one authentication. + :param port: Defaults to 139. If you are using direct TCP mode (is_direct_tcp=true when creating this SMBConnection instance), use 445. + :param sock_family: In Python 3.x, use *None* as we can infer the socket family from the provided *ip*. In Python 2.x, it must be either *socket.AF_INET* or *socket.AF_INET6*. :return: A boolean value indicating the result of the authentication atttempt: True if authentication is successful; False, if otherwise. """ if self.sock: self.sock.close() self.auth_result = None - self.sock = socket.socket(sock_family) - self.sock.settimeout(timeout) - self.sock.connect(( ip, port )) + if sock_family: + self.sock = socket.socket(sock_family) + self.sock.settimeout(timeout) + self.sock.connect(( ip, port )) + else: + self.sock = socket.create_connection(( ip, port )) self.is_busy = True try: @@ -153,15 +168,23 @@ return results def listPath(self, service_name, path, - search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE, + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* + + For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + + Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), + system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files + and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). + If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. + SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). - The default *search* value will query for all read-only, hidden, system, archive files and directories. :param string/unicode pattern: the filter to apply to the results before returning to the client. :return: A list of :doc:`smb.base.SharedFile` instances. """ @@ -245,6 +268,37 @@ self.is_busy = True try: self._getAttributes(service_name, path, cb, eb, timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False + + return results[0] + + def getSecurity(self, service_name, path, timeout = 30): + """ + Retrieve the security descriptor of the file at *path* on the *service_name*. + + :param string/unicode service_name: the name of the shared folder for the *path* + :param string/unicode path: Path of the file on the remote server. If the file cannot be opened for reading, an :doc:`OperationFailure` will be raised. + :return: A :class:`smb.security_descriptors.SecurityDescriptor` instance containing the security information of the file. + """ + if not self.sock: + raise NotConnectedError('Not connected to server') + + results = [ ] + + def cb(info): + self.is_busy = False + results.append(info) + + def eb(failure): + self.is_busy = False + raise failure + + self.is_busy = True + try: + self._getSecurity(service_name, path, cb, eb, timeout) while self.is_busy: self._pollForNetBIOSPacket(timeout) finally: @@ -350,9 +404,11 @@ return results[0] - def deleteFiles(self, service_name, path_file_pattern, timeout = 30): + def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. + + If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. @@ -372,23 +428,27 @@ self.is_busy = True try: - self._deleteFiles(service_name, path_file_pattern, cb, eb, timeout = timeout) - while self.is_busy: - self._pollForNetBIOSPacket(timeout) - finally: - self.is_busy = False - - def resetFileAttributes(self, service_name, path_file_pattern, timeout = 30): + self._deleteFiles(service_name, path_file_pattern, delete_matching_folders, cb, eb, timeout = timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False + + def resetFileAttributes(self, service_name, path_file_pattern, file_attributes = ATTR_NORMAL, timeout = 30): """ Reset file attributes of one or more regular files or folders. It supports the use of wildcards in file names, allowing for unlocking of multiple files/folders in a single request. This function is very helpful when deleting files/folders that are read-only. - Note: this function is currently only implemented for SMB2! Technically, it sets the FILE_ATTRIBUTE_NORMAL flag, therefore clearing all other flags. (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) - + By default, it sets the ATTR_NORMAL flag, therefore clearing all other flags. + (See https://msdn.microsoft.com/en-us/library/cc232110.aspx for further information) + + Note: this function is currently only implemented for SMB2! + :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in the filename component of the path. If your path/filename contains non-English characters, you must pass in an unicode string. + :param int file_attributes: The desired file attributes to set. Defaults to `ATTR_NORMAL`. :return: None """ if not self.sock: @@ -403,12 +463,11 @@ self.is_busy = True try: - self._resetFileAttributes(service_name, path_file_pattern, cb, eb, timeout = timeout) - while self.is_busy: - self._pollForNetBIOSPacket(timeout) - finally: - self.is_busy = False - + self._resetFileAttributes(service_name, path_file_pattern, cb, eb, file_attributes, timeout) + while self.is_busy: + self._pollForNetBIOSPacket(timeout) + finally: + self.is_busy = False def createDirectory(self, service_name, path, timeout = 30): """ @@ -496,7 +555,7 @@ """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. - :param string data: Data to send to the remote server. + :param bytes data: Data to send to the remote server. Must be a bytes object. :return: The *data* parameter """ if not self.sock: diff --git a/python3/smb/SMBHandler.py b/python3/smb/SMBHandler.py index 042d356..0241a01 100644 --- a/python3/smb/SMBHandler.py +++ b/python3/smb/SMBHandler.py @@ -1,4 +1,3 @@ - import os, sys, socket, urllib.request, urllib.error, urllib.parse, mimetypes, email, tempfile from urllib.parse import (unwrap, unquote, splittype, splithost, quote, splitport, splittag, splitattr, splituser, splitpasswd, splitvalue) @@ -26,11 +25,14 @@ port = int(port) # username/password handling + user, host = splituser(host) + if user: user, passwd = splitpasswd(user) else: passwd = None + host = unquote(host) user = user or '' @@ -41,12 +43,16 @@ passwd = passwd or '' myname = MACHINE_NAME or self.generateClientMachineName() - n = NetBIOS() - names = n.queryIPForName(host) - if names: - server_name = names[0] - else: - raise urllib.error.URLError('SMB error: Hostname does not reply back with its machine name') + server_name,host = host.split(',') if ',' in host else [None,host] + + if server_name is None: + n = NetBIOS() + + names = n.queryIPForName(host) + if names: + server_name = names[0] + else: + raise urllib.error.URLError('SMB error: Hostname does not reply back with its machine name') path, attrs = splitattr(req.selector) if path.startswith('/'): diff --git a/python3/smb/SMBProtocol.py b/python3/smb/SMBProtocol.py index e0089c2..b76aa57 100644 --- a/python3/smb/SMBProtocol.py +++ b/python3/smb/SMBProtocol.py @@ -178,15 +178,23 @@ return d def listPath(self, service_name, path, - search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE, + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL, pattern = '*', timeout = 30): """ Retrieve a directory listing of files/folders at *path* + + For simplicity, pysmb defines a "normal" file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + + Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN), + system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files + and directories (SMB_FILE_ATTRIBUTE_DIRECTORY). + If you do not need to include "normal" files in the result, define your own search parameter without the SMB_FILE_ATTRIBUTE_INCL_NORMAL constant. + SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants. :param string/unicode service_name: the name of the shared folder for the *path* :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders. :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py). - The default *search* value will query for all read-only, hidden, system, archive files and directories. :param string/unicode pattern: the filter to apply to the results before returning to the client. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile` instances. @@ -295,10 +303,12 @@ self.instance._storeFile(service_name, path, file_obj, d.callback, d.errback, timeout = timeout) return d - def deleteFiles(self, service_name, path_file_pattern, timeout = 30): + def deleteFiles(self, service_name, path_file_pattern, delete_matching_folders = False, timeout = 30): """ Delete one or more regular files. It supports the use of wildcards in file names, allowing for deletion of multiple files in a single request. + If delete_matching_folders is True, immediate sub-folders that match the path_file_pattern will be deleted recursively. + :param string/unicode service_name: Contains the name of the shared folder. :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name. Wildcards may be used in th filename component of the path. @@ -310,7 +320,7 @@ raise NotConnectedError('Not connected to server') d = defer.Deferred() - self.instance._deleteFiles(service_name, path_file_pattern, d.callback, d.errback, timeout = timeout) + self.instance._deleteFiles(service_name, path_file_pattern, delete_matching_folders, d.callback, d.errback, timeout = timeout) return d def createDirectory(self, service_name, path): @@ -369,7 +379,7 @@ """ Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*. - :param string data: Data to send to the remote server. + :param bytes data: Data to send to the remote server. Must be a bytes object. :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method. :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter. """ diff --git a/python3/smb/base.py b/python3/smb/base.py index a1ec271..d457bc6 100644 --- a/python3/smb/base.py +++ b/python3/smb/base.py @@ -5,6 +5,7 @@ from .smb2_constants import * from .smb_structs import * from .smb2_structs import * +from .security_descriptors import SecurityDescriptor from nmb.base import NMBSession from .utils import convertFILETIMEtoEpoch from . import ntlm, securityblob @@ -53,13 +54,14 @@ def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False): NMBSession.__init__(self, my_name, remote_name, is_direct_tcp = is_direct_tcp) self.username = username - self.password = password + self._password = password self.domain = domain self.sign_options = sign_options self.is_direct_tcp = is_direct_tcp self.use_ntlm_v2 = use_ntlm_v2 #: Similar to LMAuthenticationPolicy and NTAuthenticationPolicy as described in [MS-CIFS] 3.2.1.1 self.smb_message = SMBMessage() self.is_using_smb2 = False #: Are we communicating using SMB2 protocol? self.smb_message will be a SMB2Message instance if this flag is True + self.async_requests = { } #: AsyncID mapped to _PendingRequest instance self.pending_requests = { } #: MID mapped to _PendingRequest instance self.connected_trees = { } #: Share name mapped to TID self.next_rpc_call_id = 1 #: Next RPC callID value. Not used directly in SMB message. Usually encapsulated in sub-commands under SMB_COM_TRANSACTION or SMB_COM_TRANSACTION2 messages @@ -98,6 +100,11 @@ (self.use_ntlm_v2 and 'v2') or 'v1', (SUPPORT_EXTENDED_SECURITY and 'with') or 'without') + @property + def password(self): + if callable(self._password): + return self._password() + return self._password # # NMBSession Methods @@ -167,6 +174,7 @@ self._listShares = self._listShares_SMB1 self._listPath = self._listPath_SMB1 self._listSnapshots = self._listSnapshots_SMB1 + self._getSecurity = self._getSecurity_SMB1 self._getAttributes = self._getAttributes_SMB1 self._retrieveFile = self._retrieveFile_SMB1 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB1 @@ -189,6 +197,7 @@ self._listShares = self._listShares_SMB2 self._listPath = self._listPath_SMB2 self._listSnapshots = self._listSnapshots_SMB2 + self._getSecurity = self._getSecurity_SMB2 self._getAttributes = self._getAttributes_SMB2 self._retrieveFile = self._retrieveFile_SMB2 self._retrieveFileFromOffset = self._retrieveFileFromOffset_SMB2 @@ -213,7 +222,7 @@ if smb_message.mid == 0: smb_message.mid = self._getNextMID_SMB2() - if smb_message.command != SMB2_COM_NEGOTIATE and smb_message.command != SMB2_COM_ECHO: + if smb_message.command != SMB2_COM_NEGOTIATE: smb_message.session_id = self.session_id if self.is_signing_active: @@ -250,6 +259,19 @@ if result == securityblob.RESULT_ACCEPT_COMPLETED: self.has_authenticated = True self.log.info('Authentication (on SMB2) successful!') + + # [MS-SMB2]: 3.2.5.3.1 + # If the security subsystem indicates that the session was established by an anonymous user, + # Session.SigningRequired MUST be set to FALSE. + # If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags field of the + # SMB2 SESSION_SETUP Response and if Session.SigningRequired is TRUE, this indicates a SESSION_SETUP + # failure and the connection MUST be terminated. If the SMB2_SESSION_FLAG_IS_GUEST bit is set in the SessionFlags + # field of the SMB2 SESSION_SETUP Response and if RequireMessageSigning is FALSE, Session.SigningRequired + # MUST be set to FALSE. + if message.payload.isGuestSession or message.payload.isAnonymousSession: + self.is_signing_active = False + self.log.info('Signing disabled because session is guest/anonymous') + self.onAuthOK() else: raise ProtocolError('SMB2_COM_SESSION_SETUP status is 0 but security blob negResult value is %d' % result, message.raw_data, message) @@ -263,18 +285,58 @@ self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) - elif message.status == 0xc000006d: # STATUS_LOGON_FAILURE + elif (message.status == 0xc000006d # STATUS_LOGON_FAILURE + or message.status == 0xc0000064 # STATUS_NO_SUCH_USER + or message.status == 0xc000006a):# STATUS_WRONG_PASSWORD self.has_authenticated = False self.log.info('Authentication (on SMB2) failed. Please check username and password.') self.onAuthFailed() + elif (message.status == 0xc0000193 # STATUS_ACCOUNT_EXPIRED + or message.status == 0xC0000071): # STATUS_PASSWORD_EXPIRED + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account or password has expired.') + self.onAuthFailed() + elif message.status == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account has been locked due to too many invalid logon attempts.') + self.onAuthFailed() + elif message.status == 0xc0000072: # STATUS_ACCOUNT_DISABLED + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Account has been disabled.') + self.onAuthFailed() + elif (message.status == 0xc000006f # STATUS_INVALID_LOGON_HOURS + or message.status == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED + or message.status == 0xc0000070): # STATUS_INVALID_WORKSTATION + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Not allowed.') + self.onAuthFailed() + elif message.status == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Domain not trusted.') + self.onAuthFailed() + elif message.status == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE + self.has_authenticated = False + self.log.info('Authentication (on SMB2) failed. Workstation not trusted.') + self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status, message.raw_data, message) - req = self.pending_requests.pop(message.mid, None) - if req: - req.callback(message, **req.kwargs) - return True + if message.isAsync: + if message.status == 0x00000103: # STATUS_PENDING + req = self.pending_requests.pop(message.mid, None) + if req: + self.async_requests[message.async_id] = req + else: # All other status including SUCCESS + req = self.async_requests.pop(message.async_id, None) + if req: + req.callback(message, **req.kwargs) + return True + else: + req = self.pending_requests.pop(message.mid, None) + if req: + req.callback(message, **req.kwargs) + return True def _updateServerInfo_SMB2(self, payload): @@ -309,12 +371,13 @@ self.log.info('Performing NTLMv1 authentication (on SMB2) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) - ntlm_data = ntlm.generateAuthenticateMessage(server_flags, - nt_challenge_response, - lm_challenge_response, - session_key, - self.username, - self.domain) + ntlm_data, session_signing_key = ntlm.generateAuthenticateMessage(server_flags, + nt_challenge_response, + lm_challenge_response, + session_key, + self.username, + self.domain, + self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) @@ -334,7 +397,10 @@ if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") - self.signing_session_key = (session_key + b'\0'*16)[:16] + self.signing_session_key = session_signing_key + if self.log.isEnabledFor(logging.DEBUG): + self.log.info("SMB signing key is %s", binascii.hexlify(self.signing_session_key)) + if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: @@ -363,7 +429,7 @@ m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectSrvSvcCB, errback, tid = tid) messages_history.append(m) def connectSrvSvcCB(create_message, **kwargs): @@ -385,9 +451,9 @@ 01 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2WriteRequest(create_message.payload.fid, data_bytes, 0)) - m.tid = create_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, fid = create_message.payload.fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcBindCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) messages_history.append(m) else: errback(OperationFailure('Failed to list shares: Unable to locate Server Service RPC endpoint', messages_history)) @@ -396,12 +462,12 @@ messages_history.append(trans_message) if trans_message.status == 0: m = SMB2Message(SMB2ReadRequest(kwargs['fid'], read_len = 1024, read_offset = 0)) - m.tid = trans_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, fid = kwargs['fid']) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, rpcReadCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) messages_history.append(m) else: - closeFid(trans_message.tid, kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') + closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to read from Server Service RPC endpoint') def rpcReadCB(read_message, **kwargs): messages_history.append(read_message) @@ -429,12 +495,12 @@ 00 00 00 00 ff ff ff ff 08 00 02 00 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) m = SMB2Message(SMB2IoctlRequest(kwargs['fid'], 0x0011C017, flags = 0x01, max_out_size = 8196, in_data = data_bytes)) - m.tid = read_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, listShareResultsCB, errback, tid = kwargs['tid'], fid = kwargs['fid']) messages_history.append(m) else: - closeFid(read_message.tid, kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') + closeFid(kwargs['tid'], kwargs['fid'], error = 'Failed to list shares: Unable to bind to Server Service RPC endpoint') def listShareResultsCB(result_message, **kwargs): messages_history.append(result_message) @@ -443,13 +509,11 @@ data_bytes = result_message.payload.out_data if data_bytes[3] & 0x02 == 0: - sendReadRequest(result_message.tid, kwargs['fid'], data_bytes) - else: - decodeResults(result_message.tid, kwargs['fid'], data_bytes) - elif result_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[result_message.mid] = _PendingRequest(result_message.mid, expiry_time, listShareResultsCB, errback, fid = kwargs['fid']) - else: - closeFid(result_message.tid, kwargs['fid']) + sendReadRequest(kwargs['tid'], kwargs['fid'], data_bytes) + else: + decodeResults(kwargs['tid'], kwargs['fid'], data_bytes) + else: + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def decodeResults(tid, fid, data_bytes): @@ -488,20 +552,19 @@ m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, - fid = fid, data_bytes = data_bytes) + tid = tid, fid = fid, data_bytes = data_bytes) def readCB(read_message, **kwargs): messages_history.append(read_message) if read_message.status == 0: - data_len = read_message.payload.data_length data_bytes = read_message.payload.data if data_bytes[3] & 0x02 == 0: - sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - closeFid(read_message.tid, kwargs['fid']) + sendReadRequest(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + decodeResults(kwargs['tid'], kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) def closeFid(tid, fid, results = None, error = None): @@ -566,39 +629,44 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendQuery(create_message.tid, create_message.payload.fid, b'') + sendQuery(kwargs['tid'], create_message.payload.fid, b'') + elif create_message.status == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID + errback(OperationFailure('Failed to list %s on %s: Path not found' % ( path, service_name ), messages_history)) else: errback(OperationFailure('Failed to list %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) def sendQuery(tid, fid, data_buf): m = SMB2Message(SMB2QueryDirectoryRequest(fid, pattern, - info_class = 0x03, # FileBothDirectoryInformation + info_class = 0x25, # FileIdBothDirectoryInformation flags = 0, output_buf_len = self.max_transact_size)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, fid = fid, data_buf = data_buf) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = tid, fid = fid, data_buf = data_buf) messages_history.append(m) def queryCB(query_message, **kwargs): messages_history.append(query_message) if query_message.status == 0: data_buf = decodeQueryStruct(kwargs['data_buf'] + query_message.payload.data) - sendQuery(query_message.tid, kwargs['fid'], data_buf) + sendQuery(kwargs['tid'], kwargs['fid'], data_buf) + elif query_message.status == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # If there are no matching files, we just treat as success instead of failing + closeFid(kwargs['tid'], kwargs['fid'], results = results) elif query_message.status == 0x80000006: # STATUS_NO_MORE_FILES - closeFid(query_message.tid, kwargs['fid'], results = results) - else: - closeFid(query_message.tid, kwargs['fid'], error = query_message.status) + closeFid(kwargs['tid'], kwargs['fid'], results = results) + else: + closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) def decodeQueryStruct(data_bytes): - # SMB_FIND_FILE_BOTH_DIRECTORY_INFO structure. See [MS-CIFS]: 2.2.8.1.7 and [MS-SMB]: 2.2.8.1.1 - info_format = ' data_length: return data_bytes[offset:] filename = data_bytes[offset2:offset2+filename_length].decode('UTF-16LE') - short_name = short_name.decode('UTF-16LE') - results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), - convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), - file_size, alloc_size, file_attributes, short_name, filename)) + short_name = short_name[:short_name_length].decode('UTF-16LE') + + accept_result = False + if (file_attributes & 0xff) in ( 0x00, ATTR_NORMAL ): # Only the first 8-bits are compared. We ignore other bits like temp, compressed, encryption, sparse, indexed, etc + accept_result = (search == SMB_FILE_ATTRIBUTE_NORMAL) or (search & SMB_FILE_ATTRIBUTE_INCL_NORMAL) + else: + accept_result = (file_attributes & search) > 0 + if accept_result: + results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), + convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, short_name, filename, file_id)) if next_offset: offset += next_offset @@ -639,7 +714,11 @@ if kwargs['results'] is not None: callback(kwargs['results']) elif kwargs['error'] is not None: - errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) + if kwargs['error'] == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files + callback([ ]) + else: + errback(OperationFailure('Failed to list %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): @@ -689,17 +768,18 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: p = create_message.payload + filename = self._extractLastPathComponent(path) info = SharedFile(p.create_time, p.lastaccess_time, p.lastwrite_time, p.change_time, p.file_size, p.allocation_size, p.file_attributes, - path, path) - closeFid(create_message.tid, p.fid, info = info) + filename, filename) + closeFid(kwargs['tid'], p.fid, info = info) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to open remote file object' % ( path, service_name ), messages_history)) @@ -724,6 +804,87 @@ sendCreate(connect_message.tid) else: errback(OperationFailure('Failed to get attributes for %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + sendCreate(self.connected_trees[service_name]) + + def _getSecurity_SMB2(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + expiry_time = time.time() + timeout + path = path.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + messages_history = [ ] + results = [ ] + + def sendCreate(tid): + m = SMB2Message(SMB2CreateRequest(path, + file_attributes = 0, + access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + oplock = SMB2_OPLOCK_LEVEL_NONE, + impersonation = SEC_IMPERSONATE, + create_options = 0, + create_disp = FILE_OPEN)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, createCB, errback, tid = tid) + messages_history.append(m) + + def createCB(create_message, **kwargs): + messages_history.append(create_message) + if create_message.status == 0: + m = SMB2Message(SMB2QueryInfoRequest(create_message.payload.fid, + flags = 0, + additional_info = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, + info_type = SMB2_INFO_SECURITY, + file_info_class = 0, # [MS-SMB2] 2.2.37, 3.2.4.12 + input_buf = '', + output_buf_len = self.max_transact_size)) + m.tid = kwargs['tid'] + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, queryCB, errback, tid = kwargs['tid'], fid = create_message.payload.fid) + messages_history.append(m) + else: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to open file or directory' % ( path, service_name ), messages_history)) + + def queryCB(query_message, **kwargs): + messages_history.append(query_message) + if query_message.status == 0: + security = SecurityDescriptor.from_bytes(query_message.payload.data) + closeFid(kwargs['tid'], kwargs['fid'], result = security) + else: + closeFid(kwargs['tid'], kwargs['fid'], error = query_message.status) + + def closeFid(tid, fid, result = None, error = None): + m = SMB2Message(SMB2CloseRequest(fid)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, closeCB, errback, result = result, error = error) + messages_history.append(m) + + def closeCB(close_message, **kwargs): + if kwargs['result'] is not None: + callback(kwargs['result']) + elif kwargs['error'] is not None: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Query failed with errorcode 0x%08x' % ( path, service_name, kwargs['error'] ), messages_history)) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if connect_message.status == 0: + self.connected_trees[service_name] = connect_message.tid + sendCreate(connect_message.tid) + else: + errback(OperationFailure('Failed to get the security descriptor of %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) self._sendSMBMessage(m) @@ -760,7 +921,7 @@ m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, access_mask = FILE_READ_DATA | FILE_READ_EA | FILE_READ_ATTRIBUTES | READ_CONTROL | SYNCHRONIZE, - share_access = FILE_SHARE_READ, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE, oplock = SMB2_OPLOCK_LEVEL_NONE, impersonation = SEC_IMPERSONATE, create_options = FILE_SEQUENTIAL_ONLY | FILE_NON_DIRECTORY_FILE, @@ -778,16 +939,18 @@ flags = 0, additional_info = 0, info_type = SMB2_INFO_FILE, - file_info_class = 0x16, # FileStreamInformation [MS-FSCC] 2.4 + file_info_class = 0x05, # FileStandardInformation [MS-FSCC] 2.4 input_buf = b'', output_buf_len = 4096)) - m.tid = create_message.tid + m.tid = kwargs['tid'] self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, infoCB, errback, - fid = create_message.payload.fid, file_attributes = create_message.payload.file_attributes) + tid = kwargs['tid'], + fid = create_message.payload.fid, + file_attributes = create_message.payload.file_attributes) messages_history.append(m) else: - errback(OperationFailure('Failed to list %s on %s: Unable to open file' % ( path, service_name ), messages_history)) + errback(OperationFailure('Failed to retrieve %s on %s: Unable to open file' % ( path, service_name ), messages_history)) def infoCB(info_message, **kwargs): messages_history.append(info_message) @@ -802,9 +965,9 @@ remaining_len = file_len if starting_offset + remaining_len > file_len: remaining_len = file_len - starting_offset - sendRead(info_message.tid, kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) - else: - errback(OperationFailure('Failed to list %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) + sendRead(kwargs['tid'], kwargs['fid'], starting_offset, remaining_len, 0, kwargs['file_attributes']) + else: + errback(OperationFailure('Failed to retrieve %s on %s: Unable to retrieve information on file' % ( path, service_name ), messages_history)) def sendRead(tid, fid, offset, remaining_len, read_len, file_attributes): read_count = min(self.max_read_size, remaining_len) @@ -812,7 +975,7 @@ m.tid = tid self._sendSMBMessage(m) self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, readCB, errback, - fid = fid, offset = offset, + tid = tid, fid = fid, offset = offset, remaining_len = remaining_len, read_len = read_len, file_attributes = file_attributes) @@ -826,12 +989,12 @@ remaining_len = kwargs['remaining_len'] - data_len if remaining_len > 0: - sendRead(read_message.tid, kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) - else: - closeFid(read_message.tid, kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) + sendRead(kwargs['tid'], kwargs['fid'], kwargs['offset'] + data_len, remaining_len, kwargs['read_len'] + data_len, kwargs['file_attributes']) + else: + closeFid(kwargs['tid'], kwargs['fid'], ret = ( file_obj, kwargs['file_attributes'], kwargs['read_len'] + data_len )) else: messages_history.append(read_message) - closeFid(read_message.tid, kwargs['fid'], error = read_message.status) + closeFid(kwargs['tid'], kwargs['fid'], error = read_message.status) def closeFid(tid, fid, ret = None, error = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -907,10 +1070,6 @@ messages_history.append(create_message) if create_message.status == 0: sendWrite(create_message.tid, create_message.payload.fid, starting_offset) - elif create_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[create_message.mid] = _PendingRequest(create_message.mid, expiry_time, - createCB, errback, - tid=kwargs['tid']) else: errback(OperationFailure('Failed to store %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -922,17 +1081,17 @@ m = SMB2Message(SMB2WriteRequest(fid, data, offset)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, fid = fid, offset = offset+data_len) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, writeCB, errback, tid = tid, fid = fid, offset = offset+data_len) else: closeFid(tid, fid, offset = offset) def writeCB(write_message, **kwargs): # To avoid crazy memory usage when saving large files, we do not save every write_message in messages_history. if write_message.status == 0: - sendWrite(write_message.tid, kwargs['fid'], kwargs['offset']) + sendWrite(kwargs['tid'], kwargs['fid'], kwargs['offset']) else: messages_history.append(write_message) - closeFid(write_message.tid, kwargs['fid']) + closeFid(kwargs['tid'], kwargs['fid']) errback(OperationFailure('Failed to store %s on %s: Write failed' % ( path, service_name ), messages_history)) def closeFid(tid, fid, error = None, offset = None): @@ -965,7 +1124,171 @@ sendCreate(self.connected_trees[service_name]) - def _deleteFiles_SMB2(self, service_name, path_file_pattern, callback, errback, timeout = 30): + def _deleteFiles_SMB2(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + expiry_time = time.time() + timeout + pattern = None + path = path_file_pattern.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + else: + path_components = path.split('\\') + if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: + path = '\\'.join(path_components[:-1]) + pattern = path_components[-1] + messages_history, files_queue = [ ], [ ] + + if pattern is None: + path_components = path.split('\\') + if len(path_components) > 1: + files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) + else: + files_queue.append(( '', path )) + + def deleteCB(path): + if files_queue: + p, filename = files_queue.pop(0) + if filename: + if p: + filename = p + '\\' + filename + self._deleteFiles_SMB2__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) + else: + self._deleteDirectory_SMB2(service_name, p, deleteCB, errback, timeout) + else: + callback(path_file_pattern) + + def listCB(files_list): + files_queue.extend(files_list) + deleteCB(None) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if connect_message.status == 0: + self.connected_trees[service_name] = connect_message.tid + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB2__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + + def _deleteFiles_SMB2__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): + folder_queue = [ ] + files_list = [ ] + current_path = [ path ] + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL + + def listCB(results): + files = [ ] + for f in filter(lambda x: x.filename not in [ '.', '..' ], results): + if f.isDirectory: + if delete_matching_folders: + folder_queue.append(current_path[0]+'\\'+f.filename) + else: + files.append(( current_path[0], f.filename )) + if current_path[0]!=path and delete_matching_folders: + files.append(( current_path[0], None )) + + if files: + files_list[0:0] = files + + if folder_queue: + p = folder_queue.pop() + current_path[0] = p + self._listPath_SMB2(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) + else: + callback(files_list) + + self._listPath_SMB2(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) + + def _deleteFiles_SMB2__del(self, service_name, tid, path, callback, errback, timeout = 30): + messages_history = [ ] + + def sendCreate(tid): + create_context_data = binascii.unhexlify(b""" + 28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 + 44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 + 00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 + 00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 + 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 + 51 46 69 64 00 00 00 00 + """.replace(b' ', b'').replace(b'\n', b'')) + m = SMB2Message(SMB2CreateRequest(path, + file_attributes = 0, + access_mask = DELETE | FILE_READ_ATTRIBUTES, + share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + oplock = SMB2_OPLOCK_LEVEL_NONE, + impersonation = SEC_IMPERSONATE, + create_options = FILE_NON_DIRECTORY_FILE, + create_disp = FILE_OPEN, + create_context_data = create_context_data)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) + messages_history.append(m) + + def createCB(open_message, **kwargs): + open_message.tid = kwargs['tid'] + messages_history.append(open_message) + if open_message.status == 0: + sendDelete(open_message.tid, open_message.payload.fid) + elif open_message.status == 0xc0000034: # STATUS_OBJECT_NAME_NOT_FOUND + callback(path) + elif open_message.status == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY + errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) + + def sendDelete(tid, fid): + m = SMB2Message(SMB2SetInfoRequest(fid, + additional_info = 0, + info_type = SMB2_INFO_FILE, + file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO + data = b'\x01')) + # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4.11 + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) + messages_history.append(m) + + def deleteCB(delete_message, **kwargs): + messages_history.append(delete_message) + if delete_message.status == 0: + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) + + def closeFid(tid, fid, status = None): + m = SMB2Message(SMB2CloseRequest(fid)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) + messages_history.append(m) + + def closeCB(close_message, **kwargs): + if kwargs['status'] == 0: + callback(path) + else: + errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) + + sendCreate(tid) + + def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, file_attributes = ATTR_NORMAL, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') @@ -986,105 +1309,6 @@ 00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 51 46 69 64 00 00 00 00 """.replace(b' ', b'').replace(b'\n', b'')) - m = SMB2Message(SMB2CreateRequest(path, - file_attributes = 0, - access_mask = DELETE | FILE_READ_ATTRIBUTES, - share_access = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - oplock = SMB2_OPLOCK_LEVEL_NONE, - impersonation = SEC_IMPERSONATE, - create_options = FILE_NON_DIRECTORY_FILE, - create_disp = FILE_OPEN, - create_context_data = create_context_data)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) - messages_history.append(m) - - def createCB(open_message, **kwargs): - open_message.tid = kwargs['tid'] - messages_history.append(open_message) - if open_message.status == 0: - sendDelete(open_message.tid, open_message.payload.fid) - elif open_message.status == 0x0103: # STATUS_PENDING - self.pending_requests[open_message.mid] = _PendingRequest(open_message.mid, expiry_time, - createCB, errback, - tid=kwargs['tid']) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to open file' % ( path, service_name ), messages_history)) - - def sendDelete(tid, fid): - m = SMB2Message(SMB2SetInfoRequest(fid, - additional_info = 0, - info_type = SMB2_INFO_FILE, - file_info_class = 0x0d, # SMB2_FILE_DISPOSITION_INFO - data = b'\x01')) - ''' - Resources: - https://msdn.microsoft.com/en-us/library/cc246560.aspx - https://msdn.microsoft.com/en-us/library/cc232098.aspx - ''' - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, fid = fid) - messages_history.append(m) - - def deleteCB(delete_message, **kwargs): - messages_history.append(delete_message) - if delete_message.status == 0: - closeFid(delete_message.tid, kwargs['fid'], status = 0) - else: - closeFid(delete_message.tid, kwargs['fid'], status = delete_message.status) - - def closeFid(tid, fid, status = None): - m = SMB2Message(SMB2CloseRequest(fid)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, closeCB, errback, status = status) - messages_history.append(m) - - def closeCB(close_message, **kwargs): - if kwargs['status'] == 0: - callback(path_file_pattern) - else: - errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) - - if service_name not in self.connected_trees: - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if connect_message.status == 0: - self.connected_trees[service_name] = connect_message.tid - sendCreate(connect_message.tid) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMB2Message(SMB2TreeConnectRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ))) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendCreate(self.connected_trees[service_name]) - - def _resetFileAttributes_SMB2(self, service_name, path_file_pattern, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - expiry_time = time.time() + timeout - path = path_file_pattern.replace('/', '\\') - if path.startswith('\\'): - path = path[1:] - if path.endswith('\\'): - path = path[:-1] - messages_history = [ ] - - def sendCreate(tid): - create_context_data = binascii.unhexlify(""" -28 00 00 00 10 00 04 00 00 00 18 00 10 00 00 00 -44 48 6e 51 00 00 00 00 00 00 00 00 00 00 00 00 -00 00 00 00 00 00 00 00 18 00 00 00 10 00 04 00 -00 00 18 00 00 00 00 00 4d 78 41 63 00 00 00 00 -00 00 00 00 10 00 04 00 00 00 18 00 00 00 00 00 -51 46 69 64 00 00 00 00 -""".replace(' ', '').replace('\n', '')) m = SMB2Message(SMB2CreateRequest(path, file_attributes = 0, @@ -1103,7 +1327,7 @@ def createCB(open_message, **kwargs): messages_history.append(open_message) if open_message.status == 0: - sendReset(open_message.tid, open_message.payload.fid) + sendReset(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to reset attributes of %s on %s: Unable to open file' % ( path, service_name ), messages_history)) @@ -1112,25 +1336,19 @@ additional_info = 0, info_type = SMB2_INFO_FILE, file_info_class = 4, # FileBasicInformation - data = struct.pack('qqqqii',0,0,0,0,0x80,0))) # FILE_ATTRIBUTE_NORMAL - ''' - Resources: - https://msdn.microsoft.com/en-us/library/cc246560.aspx - https://msdn.microsoft.com/en-us/library/cc232064.aspx - https://msdn.microsoft.com/en-us/library/cc232094.aspx - https://msdn.microsoft.com/en-us/library/cc232110.aspx - ''' - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, fid = fid) + data = struct.pack('qqqqii', 0, 0, 0, 0, file_attributes, 0))) + # [MS-SMB2]: 2.2.39, [MS-FSCC]: 2.4, [MS-FSCC]: 2.4.7, [MS-FSCC]: 2.6 + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, resetCB, errback, tid = tid, fid = fid) messages_history.append(m) def resetCB(reset_message, **kwargs): messages_history.append(reset_message) if reset_message.status == 0: - closeFid(reset_message.tid, kwargs['fid'], status = 0) - else: - closeFid(reset_message.tid, kwargs['fid'], status = reset_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = reset_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1160,8 +1378,6 @@ messages_history.append(m) else: sendCreate(self.connected_trees[service_name]) - - def _createDirectory_SMB2(self, service_name, path, callback, errback, timeout = 30): if not self.has_authenticated: @@ -1195,13 +1411,13 @@ create_context_data = create_context_data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback, tid = tid) messages_history.append(m) def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - closeFid(create_message.tid, create_message.payload.fid) + closeFid(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) @@ -1269,7 +1485,7 @@ def createCB(open_message, **kwargs): messages_history.append(open_message) if open_message.status == 0: - sendDelete(open_message.tid, open_message.payload.fid) + sendDelete(kwargs['tid'], open_message.payload.fid) else: errback(OperationFailure('Failed to delete %s on %s: Unable to open directory' % ( path, service_name ), messages_history)) @@ -1281,15 +1497,15 @@ data = b'\x01')) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, fid = fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback, tid = tid, fid = fid) messages_history.append(m) def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if delete_message.status == 0: - closeFid(delete_message.tid, kwargs['fid'], status = 0) - else: - closeFid(delete_message.tid, kwargs['fid'], status = delete_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = delete_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1365,7 +1581,7 @@ def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendRename(create_message.tid, create_message.payload.fid) + sendRename(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to rename %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) @@ -1378,15 +1594,15 @@ data = data)) m.tid = tid self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, fid = fid) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, renameCB, errback, tid = tid, fid = fid) messages_history.append(m) def renameCB(rename_message, **kwargs): messages_history.append(rename_message) if rename_message.status == 0: - closeFid(rename_message.tid, kwargs['fid'], status = 0) - else: - closeFid(rename_message.tid, kwargs['fid'], status = rename_message.status) + closeFid(kwargs['tid'], kwargs['fid'], status = 0) + else: + closeFid(kwargs['tid'], kwargs['fid'], status = rename_message.status) def closeFid(tid, fid, status = None): m = SMB2Message(SMB2CloseRequest(fid)) @@ -1453,7 +1669,7 @@ def createCB(create_message, **kwargs): messages_history.append(create_message) if create_message.status == 0: - sendEnumSnapshots(create_message.tid, create_message.payload.fid) + sendEnumSnapshots(kwargs['tid'], create_message.payload.fid) else: errback(OperationFailure('Failed to list snapshots %s on %s: Unable to open file/directory' % ( old_path, service_name ), messages_history)) @@ -1594,9 +1810,38 @@ self._handleSessionChallenge(message, ntlm_token) except ( securityblob.BadSecurityBlobError, securityblob.UnsupportedSecurityProvider ) as ex: raise ProtocolError(str(ex), message.raw_data, message) - elif message.status.internal_value == 0xc000006d: # STATUS_LOGON_FAILURE + elif (message.status.internal_value == 0xc000006d # STATUS_LOGON_FAILURE + or message.status.internal_value == 0xc0000064 # STATUS_NO_SUCH_USER + or message.status.internal_value == 0xc000006a): # STATUS_WRONG_PASSWORD self.has_authenticated = False - self.log.info('Authentication (with extended security) failed. Please check username and password. You may need to enable/disable NTLMv2 authentication.') + self.log.info('Authentication (with extended security) failed. Please check username and password.') + self.onAuthFailed() + elif (message.status.internal_value == 0xc0000193 # STATUS_ACCOUNT_EXPIRED + or message.status.internal_value == 0xC0000071): # STATUS_PASSWORD_EXPIRED + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account or password has expired.') + self.onAuthFailed() + elif message.status.internal_value == 0xc0000234: # STATUS_ACCOUNT_LOCKED_OUT + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account has been locked due to too many invalid logon attempts.') + self.onAuthFailed() + elif message.status.internal_value == 0xc0000072: # STATUS_ACCOUNT_DISABLED + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Account has been disabled.') + self.onAuthFailed() + elif (message.status.internal_value == 0xc000006f # STATUS_INVALID_LOGON_HOURS + or message.status.internal_value == 0xc000015b # STATUS_LOGON_TYPE_NOT_GRANTED + or message.status.internal_value == 0xc0000070): # STATUS_INVALID_WORKSTATION + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Not allowed.') + self.onAuthFailed() + elif message.status.internal_value == 0xc000018c: # STATUS_TRUSTED_DOMAIN_FAILURE + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Domain not trusted.') + self.onAuthFailed() + elif message.status.internal_value == 0xc000018d: # STATUS_TRUSTED_RELATIONSHIP_FAILURE + self.has_authenticated = False + self.log.info('Authentication (with extended security) failed. Workstation not trusted.') self.onAuthFailed() else: raise ProtocolError('Unknown status value (0x%08X) in SMB_COM_SESSION_SETUP_ANDX (with extended security)' % message.status.internal_value, @@ -1658,12 +1903,13 @@ self.log.info('Performing NTLMv1 authentication (with extended security) with server challenge "%s"', binascii.hexlify(server_challenge)) nt_challenge_response, lm_challenge_response, session_key = ntlm.generateChallengeResponseV1(self.password, server_challenge, True) - ntlm_data = ntlm.generateAuthenticateMessage(server_flags, - nt_challenge_response, - lm_challenge_response, - session_key, - self.username, - self.domain) + ntlm_data, signing_session_key = ntlm.generateAuthenticateMessage(server_flags, + nt_challenge_response, + lm_challenge_response, + session_key, + self.username, + self.domain, + self.my_name) if self.log.isEnabledFor(logging.DEBUG): self.log.debug('NT challenge response is "%s" (%d bytes)', binascii.hexlify(nt_challenge_response), len(nt_challenge_response)) @@ -1683,7 +1929,7 @@ if self.is_signing_active: self.log.info("SMB signing activated. All SMB messages will be signed.") - self.signing_session_key = session_key + self.signing_session_key = signing_session_key if self.capabilities & CAP_EXTENDED_SECURITY: self.signing_challenge_response = None else: @@ -1857,13 +2103,12 @@ def readCB(read_message, **kwargs): messages_history.append(read_message) if not read_message.status.hasError: - data_len = read_message.payload.data_length data_bytes = read_message.payload.data if data_bytes[3] & 0x02 == 0: - sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) - else: - decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:data_len-24]) + sendReadRequest(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) + else: + decodeResults(read_message.tid, kwargs['fid'], kwargs['data_bytes'] + data_bytes[24:]) else: closeFid(read_message.tid, kwargs['fid']) errback(OperationFailure('Failed to list shares: Unable to retrieve shared device list', messages_history)) @@ -1902,15 +2147,15 @@ setup_bytes = struct.pack(' 0 + if accept_result: + results.append(SharedFile(convertFILETIMEtoEpoch(create_time), convertFILETIMEtoEpoch(last_access_time), + convertFILETIMEtoEpoch(last_write_time), convertFILETIMEtoEpoch(last_attr_change_time), + file_size, alloc_size, file_attributes, short_name, filename)) if next_offset: offset += next_offset @@ -1988,11 +2240,15 @@ elif end_of_search: callback(results) else: - sendFindNext(find_message.tid, sid, last_name_offset, kwargs.get('support_dfs', False)) - else: - errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) - - def sendFindNext(tid, sid, resume_key, support_dfs=False): + sendFindNext(find_message.tid, sid, 0, results[-1].filename, kwargs.get('support_dfs', False)) + else: + if find_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # Remote server returns STATUS_NO_SUCH_FILE error so we assume that the search returns no matching files + callback([ ]) + else: + errback(OperationFailure('Failed to list %s on %s: Unable to retrieve file list' % ( path, service_name ), messages_history)) + + def sendFindNext(tid, sid, resume_key, resume_file, support_dfs): setup_bytes = struct.pack(' 0: @@ -2318,11 +2575,99 @@ else: sendOpen(self.connected_trees[service_name]) - def _deleteFiles_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): + def _deleteFiles_SMB1(self, service_name, path_file_pattern, delete_matching_folders, callback, errback, timeout = 30): if not self.has_authenticated: raise NotReadyError('SMB connection not authenticated') + expiry_time = time.time() + timeout + pattern = None path = path_file_pattern.replace('/', '\\') + if path.startswith('\\'): + path = path[1:] + if path.endswith('\\'): + path = path[:-1] + else: + path_components = path.split('\\') + if path_components[-1].find('*') > -1 or path_components[-1].find('?') > -1: + path = '\\'.join(path_components[:-1]) + pattern = path_components[-1] + messages_history, files_queue = [ ], [ ] + + if pattern is None: + path_components = path.split('\\') + if len(path_components) > 1: + files_queue.append(( '\\'.join(path_components[:-1]), path_components[-1] )) + else: + files_queue.append(( '', path )) + + def deleteCB(path): + if files_queue: + p, filename = files_queue.pop(0) + if filename: + if p: + filename = p + '\\' + filename + self._deleteFiles_SMB1__del(service_name, self.connected_trees[service_name], filename, deleteCB, errback, timeout) + else: + self._deleteDirectory_SMB1(service_name, p, deleteCB, errback, timeout = 30) + else: + callback(path_file_pattern) + + def listCB(files_list): + files_queue.extend(files_list) + deleteCB(None) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if not connect_message.status.hasError: + self.connected_trees[service_name] = connect_message.tid + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + else: + errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, expiry_time, connectCB, errback, path = service_name) + messages_history.append(m) + else: + if files_queue: + deleteCB(None) + else: + self._deleteFiles_SMB1__list(service_name, path, pattern, delete_matching_folders, listCB, errback, timeout) + + def _deleteFiles_SMB1__list(self, service_name, path, pattern, delete_matching_folders, callback, errback, timeout = 30): + folder_queue = [ ] + files_list = [ ] + current_path = [ path ] + search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_DIRECTORY | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL + + def listCB(results): + files = [ ] + for f in filter(lambda x: x.filename not in [ '.', '..' ], results): + if f.isDirectory: + if delete_matching_folders: + folder_queue.append(current_path[0]+'\\'+f.filename) + else: + files.append(( current_path[0], f.filename )) + if current_path[0]!=path and delete_matching_folders: + files.append(( current_path[0], None )) + + if files: + files_list[0:0] = files + + if folder_queue: + p = folder_queue.pop() + current_path[0] = p + self._listPath_SMB1(service_name, current_path[0], listCB, errback, search = search, pattern = '*', timeout = 30) + else: + callback(files_list) + + self._listPath_SMB1(service_name, path, listCB, errback, search = search, pattern = pattern, timeout = timeout) + + def _deleteFiles_SMB1__del(self, service_name, tid, path, callback, errback, timeout = 30): messages_history = [ ] def sendDelete(tid): @@ -2336,9 +2681,79 @@ def deleteCB(delete_message, **kwargs): messages_history.append(delete_message) if not delete_message.status.hasError: + callback(path) + elif delete_message.status.internal_value == 0xC000000F: # [MS-ERREF]: STATUS_NO_SUCH_FILE + # If there are no matching files, we just treat as success instead of failing callback(path_file_pattern) - else: - errback(OperationFailure('Failed to store %s on %s: Delete failed' % ( path, service_name ), messages_history)) + elif delete_message.status.internal_value == 0xC00000BA: # [MS-ERREF]: STATUS_FILE_IS_A_DIRECTORY + errback(OperationFailure('Failed to delete %s on %s: Cannot delete a folder. Please use deleteDirectory() method or append "/*" to your path if you wish to delete all files in the folder.' % ( path, service_name ), messages_history)) + elif delete_message.status.internal_value == 0xC0000034: # [MS-ERREF]: STATUS_OBJECT_NAME_INVALID + errback(OperationFailure('Failed to delete %s on %s: Path not found' % ( path, service_name ), messages_history)) + else: + errback(OperationFailure('Failed to delete %s on %s: Delete failed' % ( path, service_name ), messages_history)) + + sendDelete(tid) + + def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, file_attributes=ATTR_NORMAL, timeout = 30): + raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') + + def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + path = path.replace('/', '\\') + messages_history = [ ] + + def sendCreate(tid): + m = SMBMessage(ComCreateDirectoryRequest(path)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) + messages_history.append(m) + + def createCB(create_message, **kwargs): + messages_history.append(create_message) + if not create_message.status.hasError: + callback(path) + else: + errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) + + if service_name not in self.connected_trees: + def connectCB(connect_message, **kwargs): + messages_history.append(connect_message) + if not connect_message.status.hasError: + self.connected_trees[service_name] = connect_message.tid + sendCreate(connect_message.tid) + else: + errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + + m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) + messages_history.append(m) + else: + sendCreate(self.connected_trees[service_name]) + + def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): + if not self.has_authenticated: + raise NotReadyError('SMB connection not authenticated') + + path = path.replace('/', '\\') + messages_history = [ ] + + def sendDelete(tid): + m = SMBMessage(ComDeleteDirectoryRequest(path)) + m.tid = tid + self._sendSMBMessage(m) + self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) + messages_history.append(m) + + def deleteCB(delete_message, **kwargs): + messages_history.append(delete_message) + if not delete_message.status.hasError: + callback(path) + else: + errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) if service_name not in self.connected_trees: def connectCB(connect_message, **kwargs): @@ -2347,84 +2762,7 @@ self.connected_trees[service_name] = connect_message.tid sendDelete(connect_message.tid) else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendDelete(self.connected_trees[service_name]) - - def _resetFileAttributes_SMB1(self, service_name, path_file_pattern, callback, errback, timeout = 30): - raise NotReadyError('resetFileAttributes is not yet implemented for SMB1') - - def _createDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - path = path.replace('/', '\\') - messages_history = [ ] - - def sendCreate(tid): - m = SMBMessage(ComCreateDirectoryRequest(path)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, createCB, errback) - messages_history.append(m) - - def createCB(create_message, **kwargs): - messages_history.append(create_message) - if not create_message.status.hasError: - callback(path) - else: - errback(OperationFailure('Failed to create directory %s on %s: Create failed' % ( path, service_name ), messages_history)) - - if service_name not in self.connected_trees: - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if not connect_message.status.hasError: - self.connected_trees[service_name] = connect_message.tid - sendCreate(connect_message.tid) - else: - errback(OperationFailure('Failed to create directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) - - m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, connectCB, errback, path = service_name) - messages_history.append(m) - else: - sendCreate(self.connected_trees[service_name]) - - def _deleteDirectory_SMB1(self, service_name, path, callback, errback, timeout = 30): - if not self.has_authenticated: - raise NotReadyError('SMB connection not authenticated') - - path = path.replace('/', '\\') - messages_history = [ ] - - def sendDelete(tid): - m = SMBMessage(ComDeleteDirectoryRequest(path)) - m.tid = tid - self._sendSMBMessage(m) - self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, deleteCB, errback) - messages_history.append(m) - - def deleteCB(delete_message, **kwargs): - messages_history.append(delete_message) - if not delete_message.status.hasError: - callback(path) - else: - errback(OperationFailure('Failed to delete directory %s on %s: Delete failed' % ( path, service_name ), messages_history)) - - if service_name not in self.connected_trees: - def connectCB(connect_message, **kwargs): - messages_history.append(connect_message) - if not connect_message.status.hasError: - self.connected_trees[service_name] = connect_message.tid - sendDelete(connect_message.tid) - else: - errback(OperationFailure('Failed to delete %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) + errback(OperationFailure('Failed to delete directory %s on %s: Unable to connect to shared device' % ( path, service_name ), messages_history)) m = SMBMessage(ComTreeConnectAndxRequest(r'\\%s\%s' % ( self.remote_name.upper(), service_name ), SERVICE_ANY, '')) self._sendSMBMessage(m) @@ -2559,6 +2897,9 @@ def _echo_SMB1(self, data, callback, errback, timeout = 30): messages_history = [ ] + if not isinstance(data, type(b'')): + raise TypeError('Echo data must be %s not %s' % (type(b'').__name__, type(data).__name__)) + def echoCB(echo_message, **kwargs): messages_history.append(echo_message) if not echo_message.status.hasError: @@ -2571,10 +2912,18 @@ self.pending_requests[m.mid] = _PendingRequest(m.mid, int(time.time()) + timeout, echoCB, errback) messages_history.append(m) + def _extractLastPathComponent(self, path): + return path.replace('\\', '/').split('/')[-1] + class SharedDevice: """ Contains information about a single shared device on the remote server. + + The following attributes are available: + + * name : An unicode string containing the name of the shared device + * comments : An unicode string containing the user description of the shared device """ # The following constants are taken from [MS-SRVS]: 2.2.2.4 @@ -2629,19 +2978,33 @@ If you encounter *SharedFile* instance where its short_name attribute is empty but the filename attribute contains a short name which does not correspond to any files/folders on your remote shared device, it could be that the original filename on the file/folder entry on the shared device contains - one of these prohibited characters: "\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). + one of these prohibited characters: "\\/[]:+|<>=;?,* (see [MS-CIFS]: 2.2.1.1.1 for more details). + + The following attributes are available: + + * create_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server + * last_access_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server + * last_write_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server + * last_attr_change_time : Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server + * file_size : File size in number of bytes + * alloc_size : Total number of bytes allocated to store this file + * file_attributes : A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. + * short_name : Unicode string containing the short name of this file (usually in 8.3 notation) + * filename : Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. + * file_id : Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 """ - def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename): + def __init__(self, create_time, last_access_time, last_write_time, last_attr_change_time, file_size, alloc_size, file_attributes, short_name, filename, file_id=None): self.create_time = create_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of creation of this file resource on the remote server self.last_access_time = last_access_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last access of this file resource on the remote server self.last_write_time = last_write_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last modification of this file resource on the remote server self.last_attr_change_time = last_attr_change_time #: Float value in number of seconds since 1970-01-01 00:00:00 to the time of last attribute change of this file resource on the remote server self.file_size = file_size #: File size in number of bytes self.alloc_size = alloc_size #: Total number of bytes allocated to store this file - self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3 + self.file_attributes = file_attributes #: A SMB_EXT_FILE_ATTR integer value. See [MS-CIFS]: 2.2.1.2.3. You can perform bit-wise tests to determine the status of the file using the ATTR_xxx constants in smb_constants.py. self.short_name = short_name #: Unicode string containing the short name of this file (usually in 8.3 notation) self.filename = filename #: Unicode string containing the long filename of this file. Each OS has a limit to the length of this file name. On Windows, it is 256 characters. + self.file_id = file_id #: Long value representing the file reference number for the file. If the remote system does not support this field, this field will be None or 0. See [MS-FSCC]: 2.4.17 @property def isDirectory(self): @@ -2652,6 +3015,16 @@ def isReadOnly(self): """A convenient property to return True if this file resource is read-only on the remote server""" return bool(self.file_attributes & ATTR_READONLY) + + @property + def isNormal(self): + """ + A convenient property to return True if this is a normal file. + + Note that pysmb defines a normal file as a file entry that is not read-only, not hidden, not system, not archive and not a directory. + It ignores other attributes like compression, indexed, sparse, temporary and encryption. + """ + return (self.file_attributes==ATTR_NORMAL) or ((self.file_attributes & 0xff)==0) def __unicode__(self): return 'Shared file: %s (FileSize:%d bytes, isDirectory:%s)' % ( self.filename, self.file_size, self.isDirectory ) diff --git a/python3/smb/ntlm.py b/python3/smb/ntlm.py index bc5c783..d364f98 100644 --- a/python3/smb/ntlm.py +++ b/python3/smb/ntlm.py @@ -1,5 +1,6 @@ -import types, hmac, binascii, struct, random +import types, hmac, binascii, struct, random, string +from .utils.rc4 import RC4_encrypt from .utils.pyDes import des try: @@ -58,14 +59,14 @@ NTLM_FLAGS = NTLM_NegotiateUnicode | \ NTLM_RequestTarget | \ + NTLM_NegotiateSign | \ NTLM_NegotiateNTLM | \ NTLM_NegotiateAlwaysSign | \ NTLM_NegotiateExtendedSecurity | \ NTLM_NegotiateTargetInfo | \ NTLM_NegotiateVersion | \ NTLM_Negotiate128 | \ - NTLM_NegotiateKeyExchange | \ - NTLM_Negotiate56 + NTLM_NegotiateKeyExchange def generateNegotiateMessage(): """ @@ -81,7 +82,7 @@ return s -def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'): +def generateAuthenticateMessage(challenge_flags, nt_response, lm_response, request_session_key, user, domain = 'WORKGROUP', workstation = 'LOCALHOST'): """ References: =========== @@ -89,6 +90,13 @@ """ FORMAT = '<8sIHHIHHIHHIHHIHHIHHII' FORMAT_SIZE = struct.calcsize(FORMAT) + + # [MS-NLMP]: 3.1.5.1.2 + # http://grutz.jingojango.net/exploits/davenport-ntlm.html + session_key = session_signing_key = request_session_key + if challenge_flags & NTLM_NegotiateKeyExchange: + session_signing_key = "".join([ random.choice(string.digits+string.ascii_letters) for _ in range(16) ]).encode('ascii') + session_key = RC4_encrypt(request_session_key, session_signing_key) lm_response_length = len(lm_response) lm_response_offset = FORMAT_SIZE @@ -125,7 +133,7 @@ session_key_length, session_key_length, session_key_offset, auth_flags) - return s + lm_response + nt_response + padding + domain_unicode + user_unicode + workstation_unicode + session_key + return s + lm_response + nt_response + padding + domain_unicode + user_unicode + workstation_unicode + session_key, session_signing_key def decodeChallengeMessage(ntlm_data): @@ -161,13 +169,13 @@ d = MD4() d.update(password.encode('UTF-16LE')) ntlm_hash = d.digest() # The NT password hash - response_key = hmac.new(ntlm_hash, (user.upper() + domain).encode('UTF-16LE')).digest() # The NTLMv2 password hash. In [MS-NLMP], this is the result of NTOWFv2 and LMOWFv2 functions + response_key = hmac.new(ntlm_hash, (user.upper() + domain).encode('UTF-16LE'), 'md5').digest() # The NTLMv2 password hash. In [MS-NLMP], this is the result of NTOWFv2 and LMOWFv2 functions temp = b'\x01\x01' + b'\0'*6 + client_timestamp + client_challenge + b'\0'*4 + server_info - ntproofstr = hmac.new(response_key, server_challenge + temp).digest() + ntproofstr = hmac.new(response_key, server_challenge + temp, 'md5').digest() nt_challenge_response = ntproofstr + temp - lm_challenge_response = hmac.new(response_key, server_challenge + client_challenge).digest() + client_challenge - session_key = hmac.new(response_key, ntproofstr).digest() + lm_challenge_response = hmac.new(response_key, server_challenge + client_challenge, 'md5').digest() + client_challenge + session_key = hmac.new(response_key, ntproofstr, 'md5').digest() return nt_challenge_response, lm_challenge_response, session_key diff --git a/python3/smb/security_descriptors.py b/python3/smb/security_descriptors.py new file mode 100644 index 0000000..44a678f --- /dev/null +++ b/python3/smb/security_descriptors.py @@ -0,0 +1,367 @@ +""" +This module implements security descriptors, and the partial structures +used in them, as specified in [MS-DTYP]. +""" + +import struct + + +# Security descriptor control flags +# [MS-DTYP]: 2.4.6 +SECURITY_DESCRIPTOR_OWNER_DEFAULTED = 0x0001 +SECURITY_DESCRIPTOR_GROUP_DEFAULTED = 0x0002 +SECURITY_DESCRIPTOR_DACL_PRESENT = 0x0004 +SECURITY_DESCRIPTOR_DACL_DEFAULTED = 0x0008 +SECURITY_DESCRIPTOR_SACL_PRESENT = 0x0010 +SECURITY_DESCRIPTOR_SACL_DEFAULTED = 0x0020 +SECURITY_DESCRIPTOR_SERVER_SECURITY = 0x0040 +SECURITY_DESCRIPTOR_DACL_TRUSTED = 0x0080 +SECURITY_DESCRIPTOR_DACL_COMPUTED_INHERITANCE_REQUIRED = 0x0100 +SECURITY_DESCRIPTOR_SACL_COMPUTED_INHERITANCE_REQUIRED = 0x0200 +SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED = 0x0400 +SECURITY_DESCRIPTOR_SACL_AUTO_INHERITED = 0x0800 +SECURITY_DESCRIPTOR_DACL_PROTECTED = 0x1000 +SECURITY_DESCRIPTOR_SACL_PROTECTED = 0x2000 +SECURITY_DESCRIPTOR_RM_CONTROL_VALID = 0x4000 +SECURITY_DESCRIPTOR_SELF_RELATIVE = 0x8000 + +# ACE types +# [MS-DTYP]: 2.4.4.1 +ACE_TYPE_ACCESS_ALLOWED = 0x00 +ACE_TYPE_ACCESS_DENIED = 0x01 +ACE_TYPE_SYSTEM_AUDIT = 0x02 +ACE_TYPE_SYSTEM_ALARM = 0x03 +ACE_TYPE_ACCESS_ALLOWED_COMPOUND = 0x04 +ACE_TYPE_ACCESS_ALLOWED_OBJECT = 0x05 +ACE_TYPE_ACCESS_DENIED_OBJECT = 0x06 +ACE_TYPE_SYSTEM_AUDIT_OBJECT = 0x07 +ACE_TYPE_SYSTEM_ALARM_OBJECT = 0x08 +ACE_TYPE_ACCESS_ALLOWED_CALLBACK = 0x09 +ACE_TYPE_ACCESS_DENIED_CALLBACK = 0x0A +ACE_TYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = 0x0B +ACE_TYPE_ACCESS_DENIED_CALLBACK_OBJECT = 0x0C +ACE_TYPE_SYSTEM_AUDIT_CALLBACK = 0x0D +ACE_TYPE_SYSTEM_ALARM_CALLBACK = 0x0E +ACE_TYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = 0x0F +ACE_TYPE_SYSTEM_ALARM_CALLBACK_OBJECT = 0x10 +ACE_TYPE_SYSTEM_MANDATORY_LABEL = 0x11 +ACE_TYPE_SYSTEM_RESOURCE_ATTRIBUTE = 0x12 +ACE_TYPE_SYSTEM_SCOPED_POLICY_ID = 0x13 + +# ACE flags +# [MS-DTYP]: 2.4.4.1 +ACE_FLAG_OBJECT_INHERIT = 0x01 +ACE_FLAG_CONTAINER_INHERIT = 0x02 +ACE_FLAG_NO_PROPAGATE_INHERIT = 0x04 +ACE_FLAG_INHERIT_ONLY = 0x08 +ACE_FLAG_INHERITED = 0x10 +ACE_FLAG_SUCCESSFUL_ACCESS = 0x40 +ACE_FLAG_FAILED_ACCESS = 0x80 + +# Pre-defined well-known SIDs +# [MS-DTYP]: 2.4.2.4 +SID_NULL = "S-1-0-0" +SID_EVERYONE = "S-1-1-0" +SID_LOCAL = "S-1-2-0" +SID_CONSOLE_LOGON = "S-1-2-1" +SID_CREATOR_OWNER = "S-1-3-0" +SID_CREATOR_GROUP = "S-1-3-1" +SID_OWNER_SERVER = "S-1-3-2" +SID_GROUP_SERVER = "S-1-3-3" +SID_OWNER_RIGHTS = "S-1-3-4" +SID_NT_AUTHORITY = "S-1-5" +SID_DIALUP = "S-1-5-1" +SID_NETWORK = "S-1-5-2" +SID_BATCH = "S-1-5-3" +SID_INTERACTIVE = "S-1-5-4" +SID_SERVICE = "S-1-5-6" +SID_ANONYMOUS = "S-1-5-7" +SID_PROXY = "S-1-5-8" +SID_ENTERPRISE_DOMAIN_CONTROLLERS = "S-1-5-9" +SID_PRINCIPAL_SELF = "S-1-5-10" +SID_AUTHENTICATED_USERS = "S-1-5-11" +SID_RESTRICTED_CODE = "S-1-5-12" +SID_TERMINAL_SERVER_USER = "S-1-5-13" +SID_REMOTE_INTERACTIVE_LOGON = "S-1-5-14" +SID_THIS_ORGANIZATION = "S-1-5-15" +SID_IUSR = "S-1-5-17" +SID_LOCAL_SYSTEM = "S-1-5-18" +SID_LOCAL_SERVICE = "S-1-5-19" +SID_NETWORK_SERVICE = "S-1-5-20" +SID_COMPOUNDED_AUTHENTICATION = "S-1-5-21-0-0-0-496" +SID_CLAIMS_VALID = "S-1-5-21-0-0-0-497" +SID_BUILTIN_ADMINISTRATORS = "S-1-5-32-544" +SID_BUILTIN_USERS = "S-1-5-32-545" +SID_BUILTIN_GUESTS = "S-1-5-32-546" +SID_POWER_USERS = "S-1-5-32-547" +SID_ACCOUNT_OPERATORS = "S-1-5-32-548" +SID_SERVER_OPERATORS = "S-1-5-32-549" +SID_PRINTER_OPERATORS = "S-1-5-32-550" +SID_BACKUP_OPERATORS = "S-1-5-32-551" +SID_REPLICATOR = "S-1-5-32-552" +SID_ALIAS_PREW2KCOMPACC = "S-1-5-32-554" +SID_REMOTE_DESKTOP = "S-1-5-32-555" +SID_NETWORK_CONFIGURATION_OPS = "S-1-5-32-556" +SID_INCOMING_FOREST_TRUST_BUILDERS = "S-1-5-32-557" +SID_PERFMON_USERS = "S-1-5-32-558" +SID_PERFLOG_USERS = "S-1-5-32-559" +SID_WINDOWS_AUTHORIZATION_ACCESS_GROUP = "S-1-5-32-560" +SID_TERMINAL_SERVER_LICENSE_SERVERS = "S-1-5-32-561" +SID_DISTRIBUTED_COM_USERS = "S-1-5-32-562" +SID_IIS_IUSRS = "S-1-5-32-568" +SID_CRYPTOGRAPHIC_OPERATORS = "S-1-5-32-569" +SID_EVENT_LOG_READERS = "S-1-5-32-573" +SID_CERTIFICATE_SERVICE_DCOM_ACCESS = "S-1-5-32-574" +SID_RDS_REMOTE_ACCESS_SERVERS = "S-1-5-32-575" +SID_RDS_ENDPOINT_SERVERS = "S-1-5-32-576" +SID_RDS_MANAGEMENT_SERVERS = "S-1-5-32-577" +SID_HYPER_V_ADMINS = "S-1-5-32-578" +SID_ACCESS_CONTROL_ASSISTANCE_OPS = "S-1-5-32-579" +SID_REMOTE_MANAGEMENT_USERS = "S-1-5-32-580" +SID_WRITE_RESTRICTED_CODE = "S-1-5-33" +SID_NTLM_AUTHENTICATION = "S-1-5-64-10" +SID_SCHANNEL_AUTHENTICATION = "S-1-5-64-14" +SID_DIGEST_AUTHENTICATION = "S-1-5-64-21" +SID_THIS_ORGANIZATION_CERTIFICATE = "S-1-5-65-1" +SID_NT_SERVICE = "S-1-5-80" +SID_USER_MODE_DRIVERS = "S-1-5-84-0-0-0-0-0" +SID_LOCAL_ACCOUNT = "S-1-5-113" +SID_LOCAL_ACCOUNT_AND_MEMBER_OF_ADMINISTRATORS_GROUP = "S-1-5-114" +SID_OTHER_ORGANIZATION = "S-1-5-1000" +SID_ALL_APP_PACKAGES = "S-1-15-2-1" +SID_ML_UNTRUSTED = "S-1-16-0" +SID_ML_LOW = "S-1-16-4096" +SID_ML_MEDIUM = "S-1-16-8192" +SID_ML_MEDIUM_PLUS = "S-1-16-8448" +SID_ML_HIGH = "S-1-16-12288" +SID_ML_SYSTEM = "S-1-16-16384" +SID_ML_PROTECTED_PROCESS = "S-1-16-20480" +SID_AUTHENTICATION_AUTHORITY_ASSERTED_IDENTITY = "S-1-18-1" +SID_SERVICE_ASSERTED_IDENTITY = "S-1-18-2" +SID_FRESH_PUBLIC_KEY_IDENTITY = "S-1-18-3" +SID_KEY_TRUST_IDENTITY = "S-1-18-4" +SID_KEY_PROPERTY_MFA = "S-1-18-5" +SID_KEY_PROPERTY_ATTESTATION = "S-1-18-6" + + +class SID(object): + """ + A Windows security identifier. Represents a single principal, such a + user or a group, as a sequence of numbers consisting of the revision, + identifier authority, and a variable-length list of subauthorities. + + See [MS-DTYP]: 2.4.2 + """ + def __init__(self, revision, identifier_authority, subauthorities): + #: Revision, should always be 1. + self.revision = revision + #: An integer representing the identifier authority. + self.identifier_authority = identifier_authority + #: A list of integers representing all subauthorities. + self.subauthorities = subauthorities + + def __str__(self): + """ + String representation, as specified in [MS-DTYP]: 2.4.2.1 + """ + if self.identifier_authority >= 2**32: + id_auth = '%#x' % (self.identifier_authority,) + else: + id_auth = self.identifier_authority + auths = [self.revision, id_auth] + self.subauthorities + return 'S-' + '-'.join(str(subauth) for subauth in auths) + + def __repr__(self): + return 'SID(%r)' % (str(self),) + + @classmethod + def from_bytes(cls, data, return_tail=False): + revision, subauth_count = struct.unpack('Q', b'\x00\x00' + data[2:8])[0] + subauth_data = data[8:] + subauthorities = [struct.unpack('= size + + body = data[header_size:size] + additional_data = {} + + # In all ACE types, the mask immediately follows the header. + mask = struct.unpack('= size + + for i in range(count): + ace_size = struct.unpack(' 0 # SMB2_SESSION_FLAG_IS_GUEST + + @property + def isAnonymousSession(self): + return (self.session_flags & 0x0002) > 0 # SMB2_SESSION_FLAG_IS_NULL + def decode(self, message): assert message.command == SMB2_COM_SESSION_SETUP @@ -362,6 +370,7 @@ def prepare(self, message): buf = self.filename.encode('UTF-16LE') + filename_len = len(buf) if self.create_context_data: n = SMB2Message.HEADER_SIZE + self.STRUCTURE_SIZE + len(buf) if n % 8 != 0: @@ -389,7 +398,7 @@ self.create_disp, self.create_options, SMB2Message.HEADER_SIZE + self.STRUCTURE_SIZE, # NameOffset - len(self.filename)*2, # NameLength in bytes + filename_len, # Length of encoded filename in bytes create_context_offset, # CreateContextOffset len(self.create_context_data) # CreateContextLength ) + buf diff --git a/python3/smb/smb_constants.py b/python3/smb/smb_constants.py index 685ae68..de85652 100644 --- a/python3/smb/smb_constants.py +++ b/python3/smb/smb_constants.py @@ -115,6 +115,7 @@ FILE_READ_EA = 0x08 FILE_WRITE_EA = 0x10 FILE_EXECUTE = 0x20 +FILE_DELETE_CHILD = 0x40 FILE_READ_ATTRIBUTES = 0x80 FILE_WRITE_ATTRIBUTES = 0x0100 DELETE = 0x010000 @@ -225,9 +226,13 @@ SMB_FILE_ATTRIBUTE_READONLY = 0x01 SMB_FILE_ATTRIBUTE_HIDDEN = 0x02 SMB_FILE_ATTRIBUTE_SYSTEM = 0x04 -SMB_FILE_ATTRIBUTE_VOLUME = 0x08 +SMB_FILE_ATTRIBUTE_VOLUME = 0x08 # Unsupported for listPath() operations SMB_FILE_ATTRIBUTE_DIRECTORY = 0x10 SMB_FILE_ATTRIBUTE_ARCHIVE = 0x20 +# SMB_FILE_ATTRIBUTE_INCL_NORMAL is a special placeholder to include normal files +# with other search attributes for listPath() operations. It is not defined in the MS-CIFS specs. +SMB_FILE_ATTRIBUTE_INCL_NORMAL = 0x10000 +# Do not use the following values for listPath() operations as they are not supported for SMB2 SMB_SEARCH_ATTRIBUTE_READONLY = 0x0100 SMB_SEARCH_ATTRIBUTE_HIDDEN = 0x0200 SMB_SEARCH_ATTRIBUTE_SYSTEM = 0x0400 @@ -237,3 +242,16 @@ # Bitmask for OptionalSupport field in SMB_COM_TREE_CONNECT_ANDX response SMB_TREE_CONNECTX_SUPPORT_SEARCH = 0x0001 SMB_TREE_CONNECTX_SUPPORT_DFS = 0x0002 + +# Bitmask for security information fields, specified as +# AdditionalInformation in SMB2 +# [MS-SMB]: 2.2.7.4 +# [MS-SMB2]: 2.2.37 +OWNER_SECURITY_INFORMATION = 0x00000001 +GROUP_SECURITY_INFORMATION = 0x00000002 +DACL_SECURITY_INFORMATION = 0x00000004 +SACL_SECURITY_INFORMATION = 0x00000008 +LABEL_SECURITY_INFORMATION = 0x00000010 +ATTRIBUTE_SECURITY_INFORMATION = 0x00000020 +SCOPE_SECURITY_INFORMATION = 0x00000040 +BACKUP_SECURITY_INFORMATION = 0x00010000 diff --git a/python3/smb/smb_structs.py b/python3/smb/smb_structs.py index 3583605..2332014 100644 --- a/python3/smb/smb_structs.py +++ b/python3/smb/smb_structs.py @@ -142,6 +142,10 @@ self.parameters_data = b'' self.data = b'' self.payload = None + + @property + def isAsync(self): + return bool(self.flags & SMB2_FLAGS_ASYNC_COMMAND) @property def isReply(self): @@ -1279,7 +1283,7 @@ - [MS-CIFS]: 2.2.4.39.1 """ - def __init__(self, echo_data = '', echo_count = 1): + def __init__(self, echo_data = b'', echo_count = 1): self.echo_count = echo_count self.echo_data = echo_data diff --git a/python3/smb/utils/md4.py b/python3/smb/utils/md4.py index f4a7ad0..4948904 100644 --- a/python3/smb/utils/md4.py +++ b/python3/smb/utils/md4.py @@ -82,16 +82,18 @@ dest.C = self.C dest.D = self.D dest.count = self.count - for i in range(self.count): + for i in range(int(self.count)): dest.buf[i] = self.buf[i] return dest #----------------------------------------------------- def update(self, str): - - buf = [] - for i in str: buf.append(ord(i)) + if isinstance(str, bytes): + buf = list(str) + else: + buf = [ord(i) for i in str] + ilen = U32(len(buf)) # check if the first length is out of range @@ -227,7 +229,7 @@ res[14]=(temp.D >> 16) & U32(0xFF) res[15]=(temp.D >> 24) & U32(0xFF) - return int_array2str(res) + return int_array2str(res).encode('UTF-16LE') #==================================================================== # helpers diff --git a/python3/smb/utils/rc4.py b/python3/smb/utils/rc4.py new file mode 100644 index 0000000..037c1d3 --- /dev/null +++ b/python3/smb/utils/rc4.py @@ -0,0 +1,22 @@ + +def RC4_encrypt(key, data): + S = list(range(256)) + j = 0 + + key_len = len(key) + for i in list(range(256)): + j = (j + S[i] + key[i % key_len]) % 256 + S[i], S[j] = S[j], S[i] + + j = 0 + y = 0 + out = [] + + for char in data: + j = (j + 1) % 256 + y = (y + S[j]) % 256 + S[j], S[y] = S[y], S[j] + + out.append(char ^ S[(S[j] + S[y]) % 256]) + + return bytes(out) diff --git a/python3/smb/utils/sha256.py b/python3/smb/utils/sha256.py index d535a4b..574a639 100644 --- a/python3/smb/utils/sha256.py +++ b/python3/smb/utils/sha256.py @@ -1,4 +1,3 @@ -#!/usr/bin/python __author__ = 'Thomas Dixon' __license__ = 'MIT' diff --git a/python3/tests/DirectSMBConnectionTests/test_auth.py b/python3/tests/DirectSMBConnectionTests/test_auth.py index c3f1081..f789944 100644 --- a/python3/tests/DirectSMBConnectionTests/test_auth.py +++ b/python3/tests/DirectSMBConnectionTests/test_auth.py @@ -1,43 +1,86 @@ +from nose2.tools.decorators import with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs -conn = None +conn, conn2, conn3 = None, None, None def teardown_func(): - global conn - conn.close() + global conn, conn2, conn3 + if conn: + conn.close() + if conn2: + conn2.close() + if conn3: + conn3.close(); -@with_setup(teardown = teardown_func) +@with_teardown(teardown_func) def test_NTLMv1_auth_SMB1(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) -@with_setup(teardown = teardown_func) -def test_NTLMv2_auth_SMB1(): - global conn + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) + +@with_teardown(teardown_func) +def test_NTLMv1_auth_SMB1_callable_password(): + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], lambda: info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) -@with_setup(teardown = teardown_func) + conn2 = SMBConnection(info['user'], lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', lambda: 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) + +@with_teardown(teardown_func) +def test_NTLMv2_auth_SMB1(): + global conn, conn2, conn3 + smb_structs.SUPPORT_SMB2 = False + info = getConnectionInfo() + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) + +@with_teardown(teardown_func) def test_NTLMv1_auth_SMB2(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) -@with_setup(teardown = teardown_func) + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = False, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) + +@with_teardown(teardown_func) def test_NTLMv2_auth_SMB2(): - global conn + global conn, conn2, conn3 smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) + + conn2 = SMBConnection(info['user'], 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn2.connect(info['server_ip'], info['server_port']) + + conn3 = SMBConnection('INVALIDUSER', 'wrongPass', info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) + assert not conn3.connect(info['server_ip'], info['server_port']) diff --git a/python3/tests/DirectSMBConnectionTests/test_createdeletedirectory.py b/python3/tests/DirectSMBConnectionTests/test_createdeletedirectory.py index 814d89d..dbbc313 100644 --- a/python3/tests/DirectSMBConnectionTests/test_createdeletedirectory.py +++ b/python3/tests/DirectSMBConnectionTests/test_createdeletedirectory.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- import os, time, random +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -13,7 +13,7 @@ smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): @@ -21,14 +21,15 @@ smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_english_directory_SMB1(): global conn @@ -45,7 +46,8 @@ names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_english_directory_SMB2(): global conn @@ -62,7 +64,8 @@ names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_unicode_directory_SMB1(): global conn @@ -79,7 +82,8 @@ names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_unicode_directory_SMB2(): global conn diff --git a/python3/tests/DirectSMBConnectionTests/test_echo.py b/python3/tests/DirectSMBConnectionTests/test_echo.py index c81675d..9633e04 100644 --- a/python3/tests/DirectSMBConnectionTests/test_echo.py +++ b/python3/tests/DirectSMBConnectionTests/test_echo.py @@ -1,22 +1,23 @@ import random +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from .util import getConnectionInfo -from nose.tools import with_setup conn = None def setup_func(): global conn info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func, teardown_func) +@with_setup(setup_func) +@with_teardown(teardown_func) def test_echo(): global conn diff --git a/python3/tests/DirectSMBConnectionTests/test_listpath.py b/python3/tests/DirectSMBConnectionTests/test_listpath.py index c3b08a7..2dfbd3a 100644 --- a/python3/tests/DirectSMBConnectionTests/test_listpath.py +++ b/python3/tests/DirectSMBConnectionTests/test_listpath.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb.smb_constants import * +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -11,21 +12,22 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listPath_SMB1(): global conn results = conn.listPath('smbtest', '/') @@ -36,7 +38,8 @@ assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listSubPath_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') @@ -45,7 +48,16 @@ assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathWithManyFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames))==999 + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listPath_SMB2(): global conn results = conn.listPath('smbtest', '/') @@ -56,7 +68,8 @@ assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listSubPath_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') @@ -64,3 +77,96 @@ assert ( 'Test File.txt', False ) in filenames assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathWithManyFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames))==999 + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterForDirectory_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterForDirectory_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterForFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterForFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert not isDirectory + + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterPattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterPattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterUnicodePattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterUnicodePattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames diff --git a/python3/tests/DirectSMBConnectionTests/test_listshares.py b/python3/tests/DirectSMBConnectionTests/test_listshares.py index 23328ec..2c9e815 100644 --- a/python3/tests/DirectSMBConnectionTests/test_listshares.py +++ b/python3/tests/DirectSMBConnectionTests/test_listshares.py @@ -1,8 +1,8 @@ +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -10,27 +10,29 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listshares_SMB1(): global conn results = conn.listShares() assert 'smbtest' in [r.name.lower() for r in results] -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listshares_SMB2(): global conn results = conn.listShares() diff --git a/python3/tests/DirectSMBConnectionTests/test_listsnapshots.py b/python3/tests/DirectSMBConnectionTests/test_listsnapshots.py index 551581f..e48c85f 100644 --- a/python3/tests/DirectSMBConnectionTests/test_listsnapshots.py +++ b/python3/tests/DirectSMBConnectionTests/test_listsnapshots.py @@ -1,8 +1,8 @@ +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -10,27 +10,29 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listsnapshots_SMB1(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listsnapshots_SMB2(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') diff --git a/python3/tests/DirectSMBConnectionTests/test_rename.py b/python3/tests/DirectSMBConnectionTests/test_rename.py index cb6d880..b67b3b2 100644 --- a/python3/tests/DirectSMBConnectionTests/test_rename.py +++ b/python3/tests/DirectSMBConnectionTests/test_rename.py @@ -2,10 +2,10 @@ import os, time, random from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -13,21 +13,22 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_english_file_SMB1(): global conn @@ -50,7 +51,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_english_file_SMB2(): global conn @@ -73,7 +75,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_unicode_file_SMB1(): global conn @@ -96,7 +99,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_unicode_file_SMB2(): global conn @@ -119,7 +123,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_english_directory_SMB1(): global conn @@ -142,7 +147,8 @@ conn.deleteDirectory('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_english_directory_SMB2(): global conn @@ -165,7 +171,8 @@ conn.deleteDirectory('smbtest', new_path) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_unicode_directory_SMB1(): global conn @@ -188,7 +195,8 @@ conn.deleteDirectory('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_unicode_directory_SMB2(): global conn diff --git a/python3/tests/DirectSMBConnectionTests/test_retrievefile.py b/python3/tests/DirectSMBConnectionTests/test_retrievefile.py index e49ab8f..7a93733 100644 --- a/python3/tests/DirectSMBConnectionTests/test_retrievefile.py +++ b/python3/tests/DirectSMBConnectionTests/test_retrievefile.py @@ -2,10 +2,10 @@ import os, tempfile from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs try: import hashlib @@ -20,21 +20,22 @@ global conn smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn @@ -48,7 +49,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn @@ -62,7 +64,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename global conn @@ -76,7 +79,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename global conn @@ -90,7 +94,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn @@ -104,7 +109,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn @@ -118,7 +124,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF global conn @@ -132,7 +139,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF global conn @@ -146,7 +154,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length global conn @@ -160,7 +169,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length global conn @@ -174,7 +184,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length global conn @@ -188,7 +199,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length global conn @@ -202,7 +214,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 global conn @@ -216,7 +229,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 global conn diff --git a/python3/tests/DirectSMBConnectionTests/test_storefile.py b/python3/tests/DirectSMBConnectionTests/test_storefile.py index 80c804c..fe9144c 100644 --- a/python3/tests/DirectSMBConnectionTests/test_storefile.py +++ b/python3/tests/DirectSMBConnectionTests/test_storefile.py @@ -2,10 +2,10 @@ import os, tempfile, random, time from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs try: import hashlib @@ -25,7 +25,7 @@ smb_structs.SUPPORT_SMB2 = False info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def setup_func_SMB2(): @@ -33,7 +33,7 @@ smb_structs.SUPPORT_SMB2 = True info = getConnectionInfo() - conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) + conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True, is_direct_tcp = True) assert conn.connect(info['server_ip'], info['server_port']) def teardown_func(): @@ -41,7 +41,8 @@ conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_store_long_filename_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -64,7 +65,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_store_long_filename_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -87,7 +89,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_store_unicode_filename_SMB1(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -110,7 +113,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_store_unicode_filename_SMB2(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) diff --git a/python3/tests/DirectSMBTwistedTests/test_auth.py b/python3/tests/DirectSMBTwistedTests/test_auth.py deleted file mode 100644 index 967a117..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_auth.py +++ /dev/null @@ -1,77 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class AuthFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - self.d.callback(True) - - def onAuthFailed(self): - self.d.callback(False) - - -@deferred(timeout=5.0) -def test_NTLMv1_auth_SMB1(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = False - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - - -@deferred(timeout=5.0) -def test_NTLMv2_auth_SMB1(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = False - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - - -@deferred(timeout=5.0) -def test_NTLMv1_auth_SMB2(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = True - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - - -@deferred(timeout=5.0) -def test_NTLMv2_auth_SMB2(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = True - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_createdeletedirectory.py b/python3/tests/DirectSMBTwistedTests/test_createdeletedirectory.py deleted file mode 100644 index 8874da8..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_createdeletedirectory.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, random, time -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class DirectoryFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service_name = '' - self.path = '' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def createDone(self, result): - d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) - d.addCallback(self.listComplete) - d.addErrback(self.d.errback) - - def listComplete(self, entries): - names = [e.filename for e in entries] - assert os.path.basename(self.path.replace('/', os.sep)) in names - - d = self.deleteDirectory(self.service_name, self.path) - d.addCallback(self.deleteDone) - d.addErrback(self.d.errback) - - def deleteDone(self, result): - d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) - d.addCallback(self.list2Complete) - d.addErrback(self.d.errback) - - def list2Complete(self, entries): - names = [e.filename for e in entries] - assert os.path.basename(self.path.replace('/', os.sep)) not in names - self.d.callback(True) - - def onAuthOK(self): - d = self.createDirectory(self.service_name, self.path) - d.addCallback(self.createDone) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_english_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_english_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_unicode_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_unicode_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_echo.py b/python3/tests/DirectSMBTwistedTests/test_echo.py deleted file mode 100644 index b781eee..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_echo.py +++ /dev/null @@ -1,39 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from .util import getConnectionInfo - - -class EchoFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.echo_data = 'This is an echo test' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(data): - assert data == self.echo_data - self.d.callback(True) - - d = self.echo(self.echo_data) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_echo(): - info = getConnectionInfo() - factory = EchoFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_listpath.py b/python3/tests/DirectSMBTwistedTests/test_listpath.py deleted file mode 100644 index a827955..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_listpath.py +++ /dev/null @@ -1,56 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class ListPathFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(results): - filenames = [( r.filename, r.isDirectory ) for r in results] - assert ( '\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names - assert ( 'Test Folder with Long Name', True ) in filenames # Test long English folder names - assert ( 'TestDir1', True ) in filenames # Test short English folder names - assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names - assert ( 'rfc1001.txt', False ) in filenames # Test short English file names - - self.d.callback(True) - - d = self.listPath('smbtest', '/', timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_listPath_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_listPath_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_listshares.py b/python3/tests/DirectSMBTwistedTests/test_listshares.py deleted file mode 100644 index 9c35919..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_listshares.py +++ /dev/null @@ -1,51 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class ListSharesFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(results): - assert 'smbtest' in [r.name.lower() for r in results] - self.d.callback(True) - self.instance.transport.loseConnection() - - d = self.listShares(timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_listshares_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_listshares_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_listsnapshots.py b/python3/tests/DirectSMBTwistedTests/test_listsnapshots.py deleted file mode 100644 index 7c3a5b6..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_listsnapshots.py +++ /dev/null @@ -1,57 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class ListSnapshotsFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service_name = None - self.path = None - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(results): - assert len(results) > 0 - self.d.callback(True) - self.instance.transport.loseConnection() - - d = self.listSnapshots(self.service_name, self.path, timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_listshares_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = '/rfc1001.txt' - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_listshares_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = '/rfc1001.txt' - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_rename.py b/python3/tests/DirectSMBTwistedTests/test_rename.py deleted file mode 100644 index 2658d79..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_rename.py +++ /dev/null @@ -1,174 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, random, time -from io import StringIO -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class RenameFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service = '' - self.new_path = '' - self.old_path = '' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def pathCreated(self, result): - d = self.listPath(self.service, os.path.dirname(self.old_path.replace('/', os.sep))) - d.addCallback(self.listComplete) - d.addErrback(self.d.errback) - - def listComplete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.old_path.replace('/', os.sep)) in filenames - assert os.path.basename(self.new_path.replace('/', os.sep)) not in filenames - - d = self.rename(self.service, self.old_path, self.new_path) - d.addCallback(self.renameComplete) - d.addErrback(self.d.errback) - - def renameComplete(self, result): - d = self.listPath(self.service, os.path.dirname(self.new_path.replace('/', os.sep))) - d.addCallback(self.list2Complete) - d.addErrback(self.d.errback) - - def list2Complete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.new_path.replace('/', os.sep)) in filenames - assert os.path.basename(self.old_path.replace('/', os.sep)) not in filenames - self.cleanup() - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -class RenameFileFactory(RenameFactory): - - def onAuthOK(self): - d = self.storeFile(self.service, self.old_path, StringIO('Rename file test')) - d.addCallback(self.pathCreated) - d.addErrback(self.d.errback) - - def cleanup(self): - d = self.deleteFiles(self.service, self.new_path) - d.chainDeferred(self.d) - - -class RenameDirectoryFactory(RenameFactory): - - def onAuthOK(self): - d = self.createDirectory(self.service, self.old_path) - d.addCallback(self.pathCreated) - d.addErrback(self.d.errback) - - def cleanup(self): - d = self.deleteDirectory(self.service, self.new_path) - d.chainDeferred(self.d) - - -@deferred(timeout=30.0) -def test_rename_english_file_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_english_file_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_file_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_file_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_english_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_english_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_retrievefile.py b/python3/tests/DirectSMBTwistedTests/test_retrievefile.py deleted file mode 100644 index bbfc7d0..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_retrievefile.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, tempfile -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - -try: - import hashlib - def MD5(): return hashlib.md5() -except ImportError: - import md5 - def MD5(): return md5.new() - - -class RetrieveFileFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.temp_fh = tempfile.NamedTemporaryFile(prefix = 'pysmbtest-') - self.service = '' - self.path = '' - self.digest = '' - self.offset = 0 - self.max_length = -1 - self.filesize = 0 - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def fileRetrieved(self, write_result): - file_obj, file_attributes, file_size = write_result - assert file_obj == self.temp_fh - - md = MD5() - filesize = 0 - self.temp_fh.seek(0) - while True: - s = self.temp_fh.read(8192) - if not s: - break - md.update(s) - filesize += len(s) - - assert self.filesize == filesize - assert md.hexdigest() == self.digest - - self.temp_fh.close() - self.d.callback(True) - self.instance.transport.loseConnection() - - def onAuthOK(self): - assert self.service - assert self.path - - d = self.retrieveFileFromOffset(self.service, self.path, self.temp_fh, self.offset, self.max_length, timeout = 15) - d.addCallback(self.fileRetrieved) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=30.0) -def test_retr_multiplereads_SMB1(): - # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/rfc1001.txt' - factory.digest = '5367c2bbf97f521059c78eab65309ad3' - factory.filesize = 158437 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_multiplereads_SMB2(): - # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/rfc1001.txt' - factory.digest = '5367c2bbf97f521059c78eab65309ad3' - factory.filesize = 158437 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_longfilename_SMB1(): - # Test file retrieval that has a long English filename - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/Implementing CIFS - SMB.html' - factory.digest = '671c5700d279fcbbf958c1bba3c2639e' - factory.filesize = 421269 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_longfilename_SMB2(): - # Test file retrieval that has a long English filename - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/Implementing CIFS - SMB.html' - factory.digest = '671c5700d279fcbbf958c1bba3c2639e' - factory.filesize = 421269 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_unicodefilename_SMB1(): - # Test file retrieval that has a long non-English filename inside a folder with a non-English name - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '8a44c1e80d55e91c92350955cdf83442' - factory.filesize = 256000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_unicodefilename_SMB2(): - # Test file retrieval that has a long non-English filename inside a folder with a non-English name - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '8a44c1e80d55e91c92350955cdf83442' - factory.filesize = 256000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_SMB1(): - # Test file retrieval from offset to EOF - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' - factory.filesize = 156000 - factory.offset = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_SMB2(): - # Test file retrieval from offset to EOF - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' - factory.filesize = 156000 - factory.offset = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_biglimit_SMB1(): - # Test file retrieval from offset with a big max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' - factory.filesize = 100000 - factory.offset = 100000 - factory.max_length = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_biglimit_SMB2(): - # Test file retrieval from offset with a big max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' - factory.filesize = 100000 - factory.offset = 100000 - factory.max_length = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_smalllimit_SMB1(): - # Test file retrieval from offset with a small max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '746f60a96b39b712a7b6e17ddde19986' - factory.filesize = 10 - factory.offset = 100000 - factory.max_length = 10 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_smalllimit_SMB2(): - # Test file retrieval from offset with a small max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '746f60a96b39b712a7b6e17ddde19986' - factory.filesize = 10 - factory.offset = 100000 - factory.max_length = 10 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_zerolimit_SMB1(): - # Test file retrieval from offset to EOF with max_length=0 - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' - factory.filesize = 0 - factory.offset = 100000 - factory.max_length = 0 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_zerolimit_SMB2(): - # Test file retrieval from offset to EOF with max_length=0 - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' - factory.filesize = 0 - factory.offset = 100000 - factory.max_length = 0 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/test_storefile.py b/python3/tests/DirectSMBTwistedTests/test_storefile.py deleted file mode 100644 index 0d5e6d0..0000000 --- a/python3/tests/DirectSMBTwistedTests/test_storefile.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, time, random -from io import StringIO -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - -try: - import hashlib - def MD5(): return hashlib.md5() -except ImportError: - import md5 - def MD5(): return md5.new() - -class StoreFilesFactory(SMBProtocolFactory): - """ - A super test factory that tests store file, list files, retrieve file and delete file functionlities in sequence. - """ - - TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') - TEST_FILESIZE = 256000 - TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service_name = '' - self.filename = '' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def storeComplete(self, result): - file_obj, filesize = result - file_obj.close() - assert filesize == self.TEST_FILESIZE - - d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) - d.addCallback(self.listComplete) - d.addErrback(self.d.errback) - - def listComplete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.filename.replace('/', os.sep)) in filenames - - for entry in entries: - if os.path.basename(self.filename.replace('/', os.sep)) == entry.filename: - # The following asserts will fail if the remote machine's time is not in sync with the test machine's time - assert abs(entry.create_time - time.time()) < 3 - assert abs(entry.last_access_time - time.time()) < 3 - assert abs(entry.last_write_time - time.time()) < 3 - assert abs(entry.last_attr_change_time - time.time()) < 3 - break - - d = self.retrieveFile(self.service_name, self.filename, StringIO()) - d.addCallback(self.retrieveComplete) - d.addErrback(self.d.errback) - - def retrieveComplete(self, result): - file_obj, file_attributes, file_size = result - - md = MD5() - md.update(file_obj.getvalue()) - file_obj.close() - - assert file_size == self.TEST_FILESIZE - assert md.hexdigest() == self.TEST_DIGEST - - d = self.deleteFiles(self.service_name, self.filename) - d.addCallback(self.deleteComplete) - d.addErrback(self.d.errback) - - def deleteComplete(self, result): - d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) - d.addCallback(self.list2Complete) - d.addErrback(self.d.errback) - - def list2Complete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.filename.replace('/', os.sep)) not in filenames - self.d.callback(True) - self.instance.transport.loseConnection() - - def onAuthOK(self): - d = self.storeFile(self.service_name, self.filename, open(self.TEST_FILENAME, 'rb')) - d.addCallback(self.storeComplete) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=30.0) -def test_store_long_filename_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_store_long_filename_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_store_unicode_filename_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_store_unicode_filename_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/DirectSMBTwistedTests/util.py b/python3/tests/DirectSMBTwistedTests/util.py deleted file mode 100644 index 12f82af..0000000 --- a/python3/tests/DirectSMBTwistedTests/util.py +++ /dev/null @@ -1,19 +0,0 @@ - -import os -from ConfigParser import SafeConfigParser - -def getConnectionInfo(): - config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') - cp = SafeConfigParser() - cp.read(config_filename) - - info = { - 'server_name': cp.get('server', 'name'), - 'server_ip': cp.get('server', 'ip'), - 'server_port': cp.getint('server', 'direct_port'), - 'client_name': cp.get('client', 'name'), - 'user': cp.get('user', 'name'), - 'password': cp.get('user', 'password'), - 'is_direct_tcp': True, - } - return info diff --git a/python3/tests/NetBIOSTests/test_queryname.py b/python3/tests/NetBIOSTests/test_queryname.py index a727cba..4d13560 100644 --- a/python3/tests/NetBIOSTests/test_queryname.py +++ b/python3/tests/NetBIOSTests/test_queryname.py @@ -1,6 +1,6 @@ from nmb.NetBIOS import NetBIOS -from nose.tools import with_setup +from nose2.tools.decorators import with_teardown conn = None @@ -8,7 +8,7 @@ global conn conn.close() -@with_setup(teardown = teardown_func) +@with_teardown(teardown_func) def test_broadcast(): global conn conn = NetBIOS() diff --git a/python3/tests/NetBIOSTwistedTests/__init__.py b/python3/tests/NetBIOSTwistedTests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/python3/tests/NetBIOSTwistedTests/test_queryname.py b/python3/tests/NetBIOSTwistedTests/test_queryname.py deleted file mode 100644 index 43e4548..0000000 --- a/python3/tests/NetBIOSTwistedTests/test_queryname.py +++ /dev/null @@ -1,21 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from nmb.NetBIOSProtocol import NBNSProtocol -from nose.tools import with_setup - - -@deferred(timeout=15.0) -def test_broadcast(): - def cb(results): - assert results - - def cleanup(r): - p.transport.stopListening() - - p = NBNSProtocol() - d = p.queryName('MICHAEL-I5PC', timeout = 10) - d.addCallback(cb) - d.addBoth(cleanup) - - return d diff --git a/python3/tests/README.md b/python3/tests/README.md new file mode 100644 index 0000000..200a17e --- /dev/null +++ b/python3/tests/README.md @@ -0,0 +1,57 @@ + +Steps to Follow to Run the Unit Tests +===================================== + +## Step 1: Install system dependencies ## + +If you are using Ubuntu 20.04 LTS, you can install the system dependencies with the following command +``` +$> apt-get install python3-dev python3-venv gcc g++ make automake autoconf +``` +For other distributions, you can use their package managers and install the system dependencies (although the package names might differ slightly). + +## Step 2: Setup python virtualenv ## + +We will create a python3 virtualenv and install the python dependencies for testing in the "venv3" folder. + +``` +$> cd /python3 +$> virtualenv -p /usr/bin/python3 venv3 +$> source venv3/bin/activate +$venv3> pip install nose2 pyasn1 twisted +``` + +## Step 3: Setup shared folder on your remote SMB server ## + +Prepare a shared folder called "smbtest" on your remote SMB server (Windows or Samba). + +Then, download [smbtest.zip](https://miketeo.net/files/Projects/pysmb/smbtest.zip) and unzip the contents of this zip file in the shared folder. + +You should also configure a user on the SMB server with read-write access to the "smbtest" folder. + +## Step 4: Update connection details in connection.ini ## + +In the same folder where you are viewing this readme file, there should be an ini file called "connection.ini". Edit this file's connection details to match the shared folder's access information. + +## Step 5: Run the unit tests in the python3 folder ## + +Before running the tests, the venv3 virtualenv must be activated. +``` +$> cd /python3 +$> source venv3/bin/activate +``` + +To run all the tests: +``` + $venv3> nose2 -v tests +``` + +To selectively run some tests: +``` + $venv3> nose2 -v tests.SMBConnectionTests + $venv3> nose2 -v tests.SMBConnectionTests.test_rename + $venv3> nose2 -v tests.SMBConnectionTests.test_rename.test_rename_english_file_SMB1 +``` +For more information, please consult the [documentation for nose2](https://docs.nose2.io/). + + diff --git a/python3/tests/SMBConnectionTests/test_SMBHandler.py b/python3/tests/SMBConnectionTests/test_SMBHandler.py index 8fe5f02..9d2dcb3 100644 --- a/python3/tests/SMBConnectionTests/test_SMBHandler.py +++ b/python3/tests/SMBConnectionTests/test_SMBHandler.py @@ -2,7 +2,7 @@ import os, urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, time, random from smb.SMBHandler import SMBHandler -from . import util +import util try: diff --git a/python3/tests/SMBConnectionTests/test_auth.py b/python3/tests/SMBConnectionTests/test_auth.py index 5e114b0..189d1b4 100644 --- a/python3/tests/SMBConnectionTests/test_auth.py +++ b/python3/tests/SMBConnectionTests/test_auth.py @@ -1,8 +1,8 @@ +from nose2.tools.decorators import with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -10,7 +10,7 @@ global conn conn.close() -@with_setup(teardown = teardown_func) +@with_teardown(teardown_func) def test_NTLMv1_auth_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False @@ -18,7 +18,7 @@ conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) -@with_setup(teardown = teardown_func) +@with_teardown(teardown_func) def test_NTLMv2_auth_SMB1(): global conn smb_structs.SUPPORT_SMB2 = False @@ -26,7 +26,7 @@ conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = True) assert conn.connect(info['server_ip'], info['server_port']) -@with_setup(teardown = teardown_func) +@with_teardown(teardown_func) def test_NTLMv1_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True @@ -34,7 +34,7 @@ conn = SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], domain = info['domain'], use_ntlm_v2 = False) assert conn.connect(info['server_ip'], info['server_port']) -@with_setup(teardown = teardown_func) +@with_teardown(teardown_func) def test_NTLMv2_auth_SMB2(): global conn smb_structs.SUPPORT_SMB2 = True diff --git a/python3/tests/SMBConnectionTests/test_createdeletedirectory.py b/python3/tests/SMBConnectionTests/test_createdeletedirectory.py index 814d89d..35e115f 100644 --- a/python3/tests/SMBConnectionTests/test_createdeletedirectory.py +++ b/python3/tests/SMBConnectionTests/test_createdeletedirectory.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- import os, time, random +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -28,7 +28,8 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_english_directory_SMB1(): global conn @@ -45,7 +46,8 @@ names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_english_directory_SMB2(): global conn @@ -62,7 +64,8 @@ names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_unicode_directory_SMB1(): global conn @@ -79,7 +82,8 @@ names = [e.filename for e in entries] assert os.path.basename(path.replace('/', os.sep)) not in names -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_unicode_directory_SMB2(): global conn diff --git a/python3/tests/SMBConnectionTests/test_deletepattern.py b/python3/tests/SMBConnectionTests/test_deletepattern.py index a7d183d..6fedf60 100644 --- a/python3/tests/SMBConnectionTests/test_deletepattern.py +++ b/python3/tests/SMBConnectionTests/test_deletepattern.py @@ -2,10 +2,10 @@ import os, time, random from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -29,18 +29,26 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) -def test_delete_SMB1(): - global conn - - path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) - conn.createDirectory('smbtest', path) - - for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: - conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) - - results = conn.listPath('smbtest', path) - filenames = list(map(lambda r: r.filename, results)) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_delete_without_subfolder_SMB1(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames @@ -51,6 +59,8 @@ results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames @@ -61,25 +71,82 @@ results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) - assert 'aaTest.bin' not in filenames - assert 'aaBest.bin' in filenames - assert 'random.txt' in filenames - - conn.deleteFiles('smbtest', path+'/*') - conn.deleteDirectory('smbtest', path) - -@with_setup(setup_func_SMB2, teardown_func) -def test_delete_SMB2(): - global conn - - path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) - conn.createDirectory('smbtest', path) - - for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: - conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) - - results = conn.listPath('smbtest', path) - filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_delete_with_subfolder_SMB1(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' in filenames + assert 'aaBest.txt' in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' not in filenames + assert 'aaBest.txt' not in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' not in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_delete_without_subfolder_SMB2(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' in filenames assert 'aaBest.txt' in filenames assert 'aaTest.bin' in filenames @@ -90,6 +157,8 @@ results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames assert 'aaTest.txt' not in filenames assert 'aaBest.txt' not in filenames assert 'aaTest.bin' in filenames @@ -100,6 +169,56 @@ results = conn.listPath('smbtest', path) filenames = list(map(lambda r: r.filename, results)) - assert 'aaTest.bin' not in filenames - assert 'aaBest.bin' in filenames - assert 'random.txt' in filenames + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_delete_with_subfolder_SMB2(): + global conn + + path = os.sep + u'testDelete %d-%d' % ( time.time(), random.randint(0, 1000) ) + conn.createDirectory('smbtest', path) + + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+filename, BytesIO(b"0123456789")) + + for p in [ 'aaTest.Folder', 'aaTest.Folder/xyz', 'bbTest.Folder' ]: + conn.createDirectory('smbtest', path+"/"+p) + for filename in [ 'aaTest.txt', 'aaBest.txt', 'aaTest.bin', 'aaBest.bin', 'random.txt' ]: + conn.storeFile('smbtest', path+"/"+p+"/"+filename, BytesIO(b"0123456789")) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' in filenames + assert 'aaBest.txt' in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aa*.txt', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.txt' not in filenames + assert 'aaBest.txt' not in filenames + assert 'aaTest.bin' in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames + + conn.deleteFiles('smbtest', path+'/aaTest.*', delete_matching_folders=True) + + results = conn.listPath('smbtest', path) + filenames = list(map(lambda r: r.filename, results)) + assert 'aaTest.Folder' not in filenames + assert 'bbTest.Folder' in filenames + assert 'aaTest.bin' not in filenames + assert 'aaBest.bin' in filenames + assert 'random.txt' in filenames diff --git a/python3/tests/SMBConnectionTests/test_echo.py b/python3/tests/SMBConnectionTests/test_echo.py index c81675d..f560a6f 100644 --- a/python3/tests/SMBConnectionTests/test_echo.py +++ b/python3/tests/SMBConnectionTests/test_echo.py @@ -1,8 +1,8 @@ import random +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection from .util import getConnectionInfo -from nose.tools import with_setup conn = None @@ -16,7 +16,8 @@ global conn conn.close() -@with_setup(setup_func, teardown_func) +@with_setup(setup_func) +@with_teardown(teardown_func) def test_echo(): global conn diff --git a/python3/tests/SMBConnectionTests/test_getattributes.py b/python3/tests/SMBConnectionTests/test_getattributes.py index c6e5d68..e2973ea 100644 --- a/python3/tests/SMBConnectionTests/test_getattributes.py +++ b/python3/tests/SMBConnectionTests/test_getattributes.py @@ -2,7 +2,7 @@ from smb.SMBConnection import SMBConnection from .util import getConnectionInfo -from nose.tools import with_setup +from nose2.tools.decorators import with_setup from smb import smb_structs conn = None diff --git a/python3/tests/SMBConnectionTests/test_listpath.py b/python3/tests/SMBConnectionTests/test_listpath.py index c3b08a7..46870bb 100644 --- a/python3/tests/SMBConnectionTests/test_listpath.py +++ b/python3/tests/SMBConnectionTests/test_listpath.py @@ -1,9 +1,10 @@ # -*- coding: utf-8 -*- +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb.smb_constants import * +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -25,7 +26,8 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listPath_SMB1(): global conn results = conn.listPath('smbtest', '/') @@ -36,7 +38,8 @@ assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listSubPath_SMB1(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') @@ -45,7 +48,16 @@ assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathWithManyFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames))==999 + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listPath_SMB2(): global conn results = conn.listPath('smbtest', '/') @@ -56,7 +68,8 @@ assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names assert ( 'rfc1001.txt', False ) in filenames # Test short English file names -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listSubPath_SMB2(): global conn results = conn.listPath('smbtest', '/Test Folder with Long Name/') @@ -64,3 +77,109 @@ assert ( 'Test File.txt', False ) in filenames assert ( 'Test Folder', True ) in filenames assert ( '子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathWithManyFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/RFC Archive/') + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames))==999 + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterForDirectory_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterForDirectory_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_DIRECTORY) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert isDirectory + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterForFiles_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterForFiles_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', search = SMB_FILE_ATTRIBUTE_READONLY | SMB_FILE_ATTRIBUTE_HIDDEN | SMB_FILE_ATTRIBUTE_SYSTEM | SMB_FILE_ATTRIBUTE_ARCHIVE | SMB_FILE_ATTRIBUTE_INCL_NORMAL) + filenames = map(lambda r: ( r.filename, r.isDirectory ), results) + assert len(list(filenames)) > 0 + for f, isDirectory in filenames: + assert not isDirectory + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterPattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterPattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = 'Test*') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 2 + assert ( u'Test File.txt', False ) in filenames + assert ( u'Test Folder', True ) in filenames + assert ( u'子文件夹', True ) not in filenames + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterUnicodePattern_SMB1(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterUnicodePattern_SMB2(): + global conn + results = conn.listPath('smbtest', '/Test Folder with Long Name', pattern = u'*件夹') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + assert len(filenames) == 1 + assert ( u'Test File.txt', False ) not in filenames + assert ( u'Test Folder', True ) not in filenames + assert ( u'子文件夹', True ) in filenames + +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) +def test_listPathFilterEmptyList_SMB1(): + global conn + results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) + +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) +def test_listPathFilterEmptyList_SMB2(): + global conn + results = conn.listPath('smbtest', '/RFC Archive', pattern = '*.abc') + filenames = list(map(lambda r: ( r.filename, r.isDirectory ), results)) diff --git a/python3/tests/SMBConnectionTests/test_listshares.py b/python3/tests/SMBConnectionTests/test_listshares.py index 23328ec..431b043 100644 --- a/python3/tests/SMBConnectionTests/test_listshares.py +++ b/python3/tests/SMBConnectionTests/test_listshares.py @@ -1,8 +1,8 @@ +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -24,13 +24,15 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listshares_SMB1(): global conn results = conn.listShares() assert 'smbtest' in [r.name.lower() for r in results] -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listshares_SMB2(): global conn results = conn.listShares() diff --git a/python3/tests/SMBConnectionTests/test_listsnapshots.py b/python3/tests/SMBConnectionTests/test_listsnapshots.py index 551581f..1ad2830 100644 --- a/python3/tests/SMBConnectionTests/test_listsnapshots.py +++ b/python3/tests/SMBConnectionTests/test_listsnapshots.py @@ -1,8 +1,8 @@ +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -24,13 +24,15 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_listsnapshots_SMB1(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') assert len(results) > 0 -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_listsnapshots_SMB2(): global conn results = conn.listSnapshots('smbtest', '/rfc1001.txt') diff --git a/python3/tests/SMBConnectionTests/test_rename.py b/python3/tests/SMBConnectionTests/test_rename.py index cb6d880..b9fec70 100644 --- a/python3/tests/SMBConnectionTests/test_rename.py +++ b/python3/tests/SMBConnectionTests/test_rename.py @@ -2,10 +2,10 @@ import os, time, random from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs conn = None @@ -27,7 +27,8 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_english_file_SMB1(): global conn @@ -50,7 +51,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_english_file_SMB2(): global conn @@ -73,7 +75,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_unicode_file_SMB1(): global conn @@ -96,7 +99,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_unicode_file_SMB2(): global conn @@ -119,7 +123,8 @@ conn.deleteFiles('smbtest', new_path) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_english_directory_SMB1(): global conn @@ -142,7 +147,8 @@ conn.deleteDirectory('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_english_directory_SMB2(): global conn @@ -165,7 +171,8 @@ conn.deleteDirectory('smbtest', new_path) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_rename_unicode_directory_SMB1(): global conn @@ -188,7 +195,8 @@ conn.deleteDirectory('smbtest', new_path) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_rename_unicode_directory_SMB2(): global conn diff --git a/python3/tests/SMBConnectionTests/test_retrievefile.py b/python3/tests/SMBConnectionTests/test_retrievefile.py index e49ab8f..fc1bb11 100644 --- a/python3/tests/SMBConnectionTests/test_retrievefile.py +++ b/python3/tests/SMBConnectionTests/test_retrievefile.py @@ -2,10 +2,10 @@ import os, tempfile from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs try: import hashlib @@ -34,7 +34,8 @@ global conn conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_multiplereads_SMB1(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn @@ -48,7 +49,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_multiplereads_SMB2(): # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) global conn @@ -62,7 +64,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_longfilename_SMB1(): # Test file retrieval that has a long English filename global conn @@ -76,7 +79,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_longfilename_SMB2(): # Test file retrieval that has a long English filename global conn @@ -90,7 +94,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_unicodefilename_SMB1(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn @@ -104,7 +109,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_unicodefilename_SMB2(): # Test file retrieval that has a long non-English filename inside a folder with a non-English name global conn @@ -118,7 +124,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_SMB1(): # Test file retrieval from offset to EOF global conn @@ -132,7 +139,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_SMB2(): # Test file retrieval from offset to EOF global conn @@ -146,7 +154,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB1(): # Test file retrieval from offset with a big max_length global conn @@ -160,7 +169,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_and_biglimit_SMB2(): # Test file retrieval from offset with a big max_length global conn @@ -174,7 +184,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB1(): # Test file retrieval from offset with a small max_length global conn @@ -188,7 +199,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_and_smalllimit_SMB2(): # Test file retrieval from offset with a small max_length global conn @@ -202,7 +214,8 @@ temp_fh.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB1(): # Test file retrieval from offset to EOF with max_length=0 global conn @@ -216,7 +229,8 @@ temp_fh.close() -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_retr_offset_and_zerolimit_SMB2(): # Test file retrieval from offset to EOF with max_length=0 global conn diff --git a/python3/tests/SMBConnectionTests/test_storefile.py b/python3/tests/SMBConnectionTests/test_storefile.py index 2e8e0b8..22c7dd7 100644 --- a/python3/tests/SMBConnectionTests/test_storefile.py +++ b/python3/tests/SMBConnectionTests/test_storefile.py @@ -2,10 +2,10 @@ import os, tempfile, random, time from io import BytesIO +from nose2.tools.decorators import with_setup, with_teardown from smb.SMBConnection import SMBConnection +from smb import smb_structs from .util import getConnectionInfo -from nose.tools import with_setup -from smb import smb_structs try: import hashlib @@ -41,7 +41,8 @@ conn.close() -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_store_long_filename_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -64,7 +65,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_store_long_filename_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -87,7 +89,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_store_unicode_filename_SMB1(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -110,7 +113,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB1, teardown_func) +@with_setup(setup_func_SMB1) +@with_teardown(teardown_func) def test_store_from_offset_SMB1(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -130,7 +134,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_store_unicode_filename_SMB2(): filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) @@ -152,7 +157,8 @@ conn.deleteFiles('smbtest', filename) -@with_setup(setup_func_SMB2, teardown_func) +@with_setup(setup_func_SMB2) +@with_teardown(teardown_func) def test_store_from_offset_SMB2(): filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) diff --git a/python3/tests/SMBConnectionTests/test_with_context.py b/python3/tests/SMBConnectionTests/test_with_context.py new file mode 100644 index 0000000..58d9567 --- /dev/null +++ b/python3/tests/SMBConnectionTests/test_with_context.py @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +from smb.SMBConnection import SMBConnection +from .util import getConnectionInfo + +def test_context(): + info = getConnectionInfo() + with SMBConnection(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) as conn: + assert conn.connect(info['server_ip'], info['server_port']) + + assert conn.sock is None diff --git a/python3/tests/SMBTwistedTests/__init__.py b/python3/tests/SMBTwistedTests/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/python3/tests/SMBTwistedTests/test_auth.py b/python3/tests/SMBTwistedTests/test_auth.py deleted file mode 100644 index 967a117..0000000 --- a/python3/tests/SMBTwistedTests/test_auth.py +++ /dev/null @@ -1,77 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class AuthFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - self.d.callback(True) - - def onAuthFailed(self): - self.d.callback(False) - - -@deferred(timeout=5.0) -def test_NTLMv1_auth_SMB1(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = False - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - - -@deferred(timeout=5.0) -def test_NTLMv2_auth_SMB1(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = False - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - - -@deferred(timeout=5.0) -def test_NTLMv1_auth_SMB2(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = True - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = False) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - - -@deferred(timeout=5.0) -def test_NTLMv2_auth_SMB2(): - def result(auth_passed): - assert auth_passed - - smb_structs.SUPPORT_SMB2 = True - info = getConnectionInfo() - factory = AuthFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.d.addCallback(result) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_createdeletedirectory.py b/python3/tests/SMBTwistedTests/test_createdeletedirectory.py deleted file mode 100644 index 8874da8..0000000 --- a/python3/tests/SMBTwistedTests/test_createdeletedirectory.py +++ /dev/null @@ -1,99 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, random, time -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class DirectoryFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service_name = '' - self.path = '' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def createDone(self, result): - d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) - d.addCallback(self.listComplete) - d.addErrback(self.d.errback) - - def listComplete(self, entries): - names = [e.filename for e in entries] - assert os.path.basename(self.path.replace('/', os.sep)) in names - - d = self.deleteDirectory(self.service_name, self.path) - d.addCallback(self.deleteDone) - d.addErrback(self.d.errback) - - def deleteDone(self, result): - d = self.listPath(self.service_name, os.path.dirname(self.path.replace('/', os.sep))) - d.addCallback(self.list2Complete) - d.addErrback(self.d.errback) - - def list2Complete(self, entries): - names = [e.filename for e in entries] - assert os.path.basename(self.path.replace('/', os.sep)) not in names - self.d.callback(True) - - def onAuthOK(self): - d = self.createDirectory(self.service_name, self.path) - d.addCallback(self.createDone) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_english_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_english_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + 'TestDir %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_unicode_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_unicode_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = DirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = os.sep + '文件夹创建 %d-%d' % ( time.time(), random.randint(0, 1000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_echo.py b/python3/tests/SMBTwistedTests/test_echo.py deleted file mode 100644 index b781eee..0000000 --- a/python3/tests/SMBTwistedTests/test_echo.py +++ /dev/null @@ -1,39 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from .util import getConnectionInfo - - -class EchoFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.echo_data = 'This is an echo test' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(data): - assert data == self.echo_data - self.d.callback(True) - - d = self.echo(self.echo_data) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_echo(): - info = getConnectionInfo() - factory = EchoFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_getattributes.py b/python3/tests/SMBTwistedTests/test_getattributes.py deleted file mode 100644 index f84450b..0000000 --- a/python3/tests/SMBTwistedTests/test_getattributes.py +++ /dev/null @@ -1,100 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from util import getConnectionInfo - - -class GetAttributesFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.path = '' - self.is_directory = False - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(info): - assert info.isDirectory == self.is_directory - self.d.callback(True) - - d = self.getAttributes('smbtest', self.path, timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_getAttributes_SMB1_test1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.path = '/Test Folder with Long Name/' - factory.is_directory = True - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_getAttributes_SMB1_test2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.path = '/rfc1001.txt' - factory.is_directory = False - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_getAttributes_SMB1_test3(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.path = u'/\u6d4b\u8bd5\u6587\u4ef6\u5939' - factory.is_directory = True - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_getAttributes_SMB2_test1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.path = '/Test Folder with Long Name/' - factory.is_directory = True - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_getAttributes_SMB2_test2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.path = '/rfc1001.txt' - factory.is_directory = False - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_getAttributes_SMB2_test3(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = GetAttributesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.path = u'/\u6d4b\u8bd5\u6587\u4ef6\u5939' - factory.is_directory = True - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_listpath.py b/python3/tests/SMBTwistedTests/test_listpath.py deleted file mode 100644 index a827955..0000000 --- a/python3/tests/SMBTwistedTests/test_listpath.py +++ /dev/null @@ -1,56 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class ListPathFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(results): - filenames = [( r.filename, r.isDirectory ) for r in results] - assert ( '\u6d4b\u8bd5\u6587\u4ef6\u5939', True ) in filenames # Test non-English folder names - assert ( 'Test Folder with Long Name', True ) in filenames # Test long English folder names - assert ( 'TestDir1', True ) in filenames # Test short English folder names - assert ( 'Implementing CIFS - SMB.html', False ) in filenames # Test long English file names - assert ( 'rfc1001.txt', False ) in filenames # Test short English file names - - self.d.callback(True) - - d = self.listPath('smbtest', '/', timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_listPath_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_listPath_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = ListPathFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_listshares.py b/python3/tests/SMBTwistedTests/test_listshares.py deleted file mode 100644 index 9c35919..0000000 --- a/python3/tests/SMBTwistedTests/test_listshares.py +++ /dev/null @@ -1,51 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class ListSharesFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(results): - assert 'smbtest' in [r.name.lower() for r in results] - self.d.callback(True) - self.instance.transport.loseConnection() - - d = self.listShares(timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_listshares_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_listshares_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = ListSharesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_listsnapshots.py b/python3/tests/SMBTwistedTests/test_listsnapshots.py deleted file mode 100644 index 7c3a5b6..0000000 --- a/python3/tests/SMBTwistedTests/test_listsnapshots.py +++ /dev/null @@ -1,57 +0,0 @@ - -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class ListSnapshotsFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service_name = None - self.path = None - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def onAuthOK(self): - def cb(results): - assert len(results) > 0 - self.d.callback(True) - self.instance.transport.loseConnection() - - d = self.listSnapshots(self.service_name, self.path, timeout = 15) - d.addCallback(cb) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=15.0) -def test_listshares_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = '/rfc1001.txt' - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=15.0) -def test_listshares_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = ListSnapshotsFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.path = '/rfc1001.txt' - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_rename.py b/python3/tests/SMBTwistedTests/test_rename.py deleted file mode 100644 index 2658d79..0000000 --- a/python3/tests/SMBTwistedTests/test_rename.py +++ /dev/null @@ -1,174 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, random, time -from io import StringIO -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - - -class RenameFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service = '' - self.new_path = '' - self.old_path = '' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def pathCreated(self, result): - d = self.listPath(self.service, os.path.dirname(self.old_path.replace('/', os.sep))) - d.addCallback(self.listComplete) - d.addErrback(self.d.errback) - - def listComplete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.old_path.replace('/', os.sep)) in filenames - assert os.path.basename(self.new_path.replace('/', os.sep)) not in filenames - - d = self.rename(self.service, self.old_path, self.new_path) - d.addCallback(self.renameComplete) - d.addErrback(self.d.errback) - - def renameComplete(self, result): - d = self.listPath(self.service, os.path.dirname(self.new_path.replace('/', os.sep))) - d.addCallback(self.list2Complete) - d.addErrback(self.d.errback) - - def list2Complete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.new_path.replace('/', os.sep)) in filenames - assert os.path.basename(self.old_path.replace('/', os.sep)) not in filenames - self.cleanup() - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -class RenameFileFactory(RenameFactory): - - def onAuthOK(self): - d = self.storeFile(self.service, self.old_path, StringIO('Rename file test')) - d.addCallback(self.pathCreated) - d.addErrback(self.d.errback) - - def cleanup(self): - d = self.deleteFiles(self.service, self.new_path) - d.chainDeferred(self.d) - - -class RenameDirectoryFactory(RenameFactory): - - def onAuthOK(self): - d = self.createDirectory(self.service, self.old_path) - d.addCallback(self.pathCreated) - d.addErrback(self.d.errback) - - def cleanup(self): - d = self.deleteDirectory(self.service, self.new_path) - d.chainDeferred(self.d) - - -@deferred(timeout=30.0) -def test_rename_english_file_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_english_file_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_file_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_file_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d.txt' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_english_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_english_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/RenameTest %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_directory_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_rename_unicode_directory_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RenameDirectoryFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.old_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - factory.new_path = '/改名测试 %d-%d' % ( time.time(), random.randint(1000, 9999) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_retrievefile.py b/python3/tests/SMBTwistedTests/test_retrievefile.py deleted file mode 100644 index bbfc7d0..0000000 --- a/python3/tests/SMBTwistedTests/test_retrievefile.py +++ /dev/null @@ -1,278 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, tempfile -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - -try: - import hashlib - def MD5(): return hashlib.md5() -except ImportError: - import md5 - def MD5(): return md5.new() - - -class RetrieveFileFactory(SMBProtocolFactory): - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.temp_fh = tempfile.NamedTemporaryFile(prefix = 'pysmbtest-') - self.service = '' - self.path = '' - self.digest = '' - self.offset = 0 - self.max_length = -1 - self.filesize = 0 - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def fileRetrieved(self, write_result): - file_obj, file_attributes, file_size = write_result - assert file_obj == self.temp_fh - - md = MD5() - filesize = 0 - self.temp_fh.seek(0) - while True: - s = self.temp_fh.read(8192) - if not s: - break - md.update(s) - filesize += len(s) - - assert self.filesize == filesize - assert md.hexdigest() == self.digest - - self.temp_fh.close() - self.d.callback(True) - self.instance.transport.loseConnection() - - def onAuthOK(self): - assert self.service - assert self.path - - d = self.retrieveFileFromOffset(self.service, self.path, self.temp_fh, self.offset, self.max_length, timeout = 15) - d.addCallback(self.fileRetrieved) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=30.0) -def test_retr_multiplereads_SMB1(): - # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/rfc1001.txt' - factory.digest = '5367c2bbf97f521059c78eab65309ad3' - factory.filesize = 158437 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_multiplereads_SMB2(): - # Test file retrieval using multiple ReadAndx calls (assuming each call will not reach more than 65534 bytes) - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/rfc1001.txt' - factory.digest = '5367c2bbf97f521059c78eab65309ad3' - factory.filesize = 158437 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_longfilename_SMB1(): - # Test file retrieval that has a long English filename - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/Implementing CIFS - SMB.html' - factory.digest = '671c5700d279fcbbf958c1bba3c2639e' - factory.filesize = 421269 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_longfilename_SMB2(): - # Test file retrieval that has a long English filename - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/Implementing CIFS - SMB.html' - factory.digest = '671c5700d279fcbbf958c1bba3c2639e' - factory.filesize = 421269 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_unicodefilename_SMB1(): - # Test file retrieval that has a long non-English filename inside a folder with a non-English name - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '8a44c1e80d55e91c92350955cdf83442' - factory.filesize = 256000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_unicodefilename_SMB2(): - # Test file retrieval that has a long non-English filename inside a folder with a non-English name - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '8a44c1e80d55e91c92350955cdf83442' - factory.filesize = 256000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_SMB1(): - # Test file retrieval from offset to EOF - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' - factory.filesize = 156000 - factory.offset = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_SMB2(): - # Test file retrieval from offset to EOF - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'a141bd8024571ce7cb5c67f2b0d8ea0b' - factory.filesize = 156000 - factory.offset = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_biglimit_SMB1(): - # Test file retrieval from offset with a big max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' - factory.filesize = 100000 - factory.offset = 100000 - factory.max_length = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_biglimit_SMB2(): - # Test file retrieval from offset with a big max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '83b7afd7c92cdece3975338b5ca0b1c5' - factory.filesize = 100000 - factory.offset = 100000 - factory.max_length = 100000 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_smalllimit_SMB1(): - # Test file retrieval from offset with a small max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '746f60a96b39b712a7b6e17ddde19986' - factory.filesize = 10 - factory.offset = 100000 - factory.max_length = 10 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_smalllimit_SMB2(): - # Test file retrieval from offset with a small max_length - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = '746f60a96b39b712a7b6e17ddde19986' - factory.filesize = 10 - factory.offset = 100000 - factory.max_length = 10 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_zerolimit_SMB1(): - # Test file retrieval from offset to EOF with max_length=0 - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' - factory.filesize = 0 - factory.offset = 100000 - factory.max_length = 0 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_retr_offset_and_zerolimit_SMB2(): - # Test file retrieval from offset to EOF with max_length=0 - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = RetrieveFileFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service = 'smbtest' - factory.path = '/测试文件夹/垃圾文件.dat' - factory.digest = 'd41d8cd98f00b204e9800998ecf8427e' - factory.filesize = 0 - factory.offset = 100000 - factory.max_length = 0 - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/test_storefile.py b/python3/tests/SMBTwistedTests/test_storefile.py deleted file mode 100644 index 0d5e6d0..0000000 --- a/python3/tests/SMBTwistedTests/test_storefile.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- - -import os, time, random -from io import StringIO -from nose.twistedtools import reactor, deferred -from twisted.internet import defer -from smb.SMBProtocol import SMBProtocolFactory -from smb import smb_structs -from .util import getConnectionInfo - -try: - import hashlib - def MD5(): return hashlib.md5() -except ImportError: - import md5 - def MD5(): return md5.new() - -class StoreFilesFactory(SMBProtocolFactory): - """ - A super test factory that tests store file, list files, retrieve file and delete file functionlities in sequence. - """ - - TEST_FILENAME = os.path.join(os.path.dirname(__file__), os.pardir, 'SupportFiles', 'binary.dat') - TEST_FILESIZE = 256000 - TEST_DIGEST = 'bb6303f76e29f354b6fdf6ef58587e48' - - def __init__(self, *args, **kwargs): - SMBProtocolFactory.__init__(self, *args, **kwargs) - self.d = defer.Deferred() - self.d.addBoth(self.testDone) - self.service_name = '' - self.filename = '' - - def testDone(self, r): - if self.instance: - self.instance.transport.loseConnection() - return r - - def storeComplete(self, result): - file_obj, filesize = result - file_obj.close() - assert filesize == self.TEST_FILESIZE - - d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) - d.addCallback(self.listComplete) - d.addErrback(self.d.errback) - - def listComplete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.filename.replace('/', os.sep)) in filenames - - for entry in entries: - if os.path.basename(self.filename.replace('/', os.sep)) == entry.filename: - # The following asserts will fail if the remote machine's time is not in sync with the test machine's time - assert abs(entry.create_time - time.time()) < 3 - assert abs(entry.last_access_time - time.time()) < 3 - assert abs(entry.last_write_time - time.time()) < 3 - assert abs(entry.last_attr_change_time - time.time()) < 3 - break - - d = self.retrieveFile(self.service_name, self.filename, StringIO()) - d.addCallback(self.retrieveComplete) - d.addErrback(self.d.errback) - - def retrieveComplete(self, result): - file_obj, file_attributes, file_size = result - - md = MD5() - md.update(file_obj.getvalue()) - file_obj.close() - - assert file_size == self.TEST_FILESIZE - assert md.hexdigest() == self.TEST_DIGEST - - d = self.deleteFiles(self.service_name, self.filename) - d.addCallback(self.deleteComplete) - d.addErrback(self.d.errback) - - def deleteComplete(self, result): - d = self.listPath(self.service_name, os.path.dirname(self.filename.replace('/', os.sep))) - d.addCallback(self.list2Complete) - d.addErrback(self.d.errback) - - def list2Complete(self, entries): - filenames = [e.filename for e in entries] - assert os.path.basename(self.filename.replace('/', os.sep)) not in filenames - self.d.callback(True) - self.instance.transport.loseConnection() - - def onAuthOK(self): - d = self.storeFile(self.service_name, self.filename, open(self.TEST_FILENAME, 'rb')) - d.addCallback(self.storeComplete) - d.addErrback(self.d.errback) - - def onAuthFailed(self): - self.d.errback('Auth failed') - - -@deferred(timeout=30.0) -def test_store_long_filename_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_store_long_filename_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + 'StoreTest %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_store_unicode_filename_SMB1(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = False - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d - -@deferred(timeout=30.0) -def test_store_unicode_filename_SMB2(): - info = getConnectionInfo() - smb_structs.SUPPORT_SMB2 = True - - factory = StoreFilesFactory(info['user'], info['password'], info['client_name'], info['server_name'], use_ntlm_v2 = True) - factory.service_name = 'smbtest' - factory.filename = os.sep + '上载测试 %d-%d.dat' % ( time.time(), random.randint(0, 10000) ) - reactor.connectTCP(info['server_ip'], info['server_port'], factory) - return factory.d diff --git a/python3/tests/SMBTwistedTests/util.py b/python3/tests/SMBTwistedTests/util.py deleted file mode 100644 index 37ff2f2..0000000 --- a/python3/tests/SMBTwistedTests/util.py +++ /dev/null @@ -1,19 +0,0 @@ - -import os -from configparser import SafeConfigParser - -def getConnectionInfo(): - config_filename = os.path.join(os.path.dirname(__file__), os.path.pardir, 'connection.ini') - cp = SafeConfigParser() - cp.read(config_filename) - - info = { - 'server_name': cp.get('server', 'name'), - 'server_ip': cp.get('server', 'ip'), - 'server_port': cp.getint('server', 'port'), - 'client_name': cp.get('client', 'name'), - 'user': cp.get('user', 'name'), - 'password': cp.get('user', 'password'), - } - return info - diff --git a/python3/tests/connection.ini b/python3/tests/connection.ini index 96d2652..d8d249d 100644 --- a/python3/tests/connection.ini +++ b/python3/tests/connection.ini @@ -3,6 +3,7 @@ name = SERVER ip = 192.168.1.1 port = 139 +direct_port = 445 [client] name = TESTCLIENT diff --git a/python3/tests/smbtest.7z b/python3/tests/smbtest.7z deleted file mode 100644 index c5c9f42..0000000 Binary files a/python3/tests/smbtest.7z and /dev/null differ diff --git a/python3/tests/test_security_descriptors.py b/python3/tests/test_security_descriptors.py new file mode 100644 index 0000000..7a87a84 --- /dev/null +++ b/python3/tests/test_security_descriptors.py @@ -0,0 +1,139 @@ +import binascii + +from smb import security_descriptors as sd +from smb import smb_constants as sc + + +def test_sid_string_representation(): + sid = sd.SID(1, 5, [2, 3, 4]) + assert str(sid) == "S-1-5-2-3-4" + sid = sd.SID(1, 2**32 + 3, []) + assert str(sid) == "S-1-0x100000003" + sid = sd.SID(1, 2**32, [3, 2, 1]) + assert str(sid) == "S-1-0x100000000-3-2-1" + + +def test_sid_binary_parsing(): + raw_sid = binascii.unhexlify(b""" + 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a + 2a 4f da ca c1 79 a6 32 b1 04 00 00 + """.translate(None, b' \n')) + assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" + raw_sid += b"garbage" + assert str(sd.SID.from_bytes(raw_sid)) == "S-1-5-21-717312990-3403304746-849770945-1201" + sid, tail = sd.SID.from_bytes(raw_sid, return_tail=True) + assert str(sid) == "S-1-5-21-717312990-3403304746-849770945-1201" + assert tail == b"garbage" + + +def test_ace_binary_parsing(): + raw_ace = binascii.unhexlify(b""" + 00 10 24 00 ff 01 1f 00 01 05 00 00 00 00 00 05 + 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 + 6e 04 00 00 + """.translate(None, b' \n')) + ace = sd.ACE.from_bytes(raw_ace) + assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1134" + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert ace.flags == sd.ACE_FLAG_INHERITED + assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC + | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA + | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA + | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE + | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES + | sc.FILE_WRITE_ATTRIBUTES) + assert not ace.additional_data + + raw_ace = binascii.unhexlify(b""" + 00 13 18 00 a9 00 12 00 01 02 00 00 00 00 00 05 + 20 00 00 00 21 02 00 00 + """.translate(None, b' \n')) + ace = sd.ACE.from_bytes(raw_ace) + assert str(ace.sid) == "S-1-5-32-545" + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert ace.flags == (sd.ACE_FLAG_INHERITED | sd.ACE_FLAG_CONTAINER_INHERIT + | sd.ACE_FLAG_OBJECT_INHERIT) + assert ace.mask == (sc.SYNCHRONIZE | sc.READ_CONTROL | sc.FILE_READ_DATA + | sc.FILE_READ_EA | sc.FILE_EXECUTE + | sc.FILE_READ_ATTRIBUTES) + assert not ace.additional_data + + raw_ace = binascii.unhexlify(b""" + 01 03 24 00 a9 00 02 00 01 05 00 00 00 00 00 05 + 15 00 00 00 de 53 c1 2a 2a 4f da ca c1 79 a6 32 + 6c 04 00 00 + """.translate(None, b' \n')) + ace = sd.ACE.from_bytes(raw_ace) + assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1132" + assert ace.type == sd.ACE_TYPE_ACCESS_DENIED + assert ace.flags == (sd.ACE_FLAG_CONTAINER_INHERIT + | sd.ACE_FLAG_OBJECT_INHERIT) + assert ace.mask == (sc.READ_CONTROL | sc.FILE_READ_DATA | sc.FILE_READ_EA + | sc.FILE_EXECUTE | sc.FILE_READ_ATTRIBUTES) + assert not ace.additional_data + + +def test_acl_binary_parsing(): + raw_acl = binascii.unhexlify(b""" + 02 00 70 00 04 00 00 00 00 10 18 00 89 00 10 00 + 01 02 00 00 00 00 00 05 20 00 00 00 21 02 00 00 + 00 10 14 00 ff 01 1f 00 01 01 00 00 00 00 00 05 + 12 00 00 00 00 10 18 00 ff 01 1f 00 01 02 00 00 + 00 00 00 05 20 00 00 00 20 02 00 00 00 10 24 00 + ff 01 1f 00 01 05 00 00 00 00 00 05 15 00 00 00 + de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 + """.translate(None, b' \n')) + acl = sd.ACL.from_bytes(raw_acl) + assert acl.revision == 2 + assert len(acl.aces) == 4 + + ace = acl.aces[0] + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert str(ace.sid) == "S-1-5-32-545" + assert ace.flags == sd.ACE_FLAG_INHERITED + assert ace.mask == (sc.SYNCHRONIZE | sc.FILE_READ_DATA | sc.FILE_READ_EA + | sc.FILE_READ_ATTRIBUTES) + + ace = acl.aces[3] + assert ace.type == sd.ACE_TYPE_ACCESS_ALLOWED + assert str(ace.sid) == "S-1-5-21-717312990-3403304746-849770945-1201" + assert ace.flags == sd.ACE_FLAG_INHERITED + assert ace.mask == (sc.SYNCHRONIZE | sc.WRITE_OWNER | sc.WRITE_DAC + | sc.READ_CONTROL | sc.DELETE | sc.FILE_READ_DATA + | sc.FILE_WRITE_DATA | sc.FILE_APPEND_DATA + | sc.FILE_READ_EA | sc.FILE_WRITE_EA | sc.FILE_EXECUTE + | sc.FILE_DELETE_CHILD | sc.FILE_READ_ATTRIBUTES + | sc.FILE_WRITE_ATTRIBUTES) + + +def test_descriptor_binary_parsing(): + raw_descriptor = binascii.unhexlify(b""" + 01 00 04 84 14 00 00 00 30 00 00 00 00 00 00 00 + 4c 00 00 00 01 05 00 00 00 00 00 05 15 00 00 00 + de 53 c1 2a 2a 4f da ca c1 79 a6 32 b1 04 00 00 + 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a + 2a 4f da ca c1 79 a6 32 01 02 00 00 02 00 70 00 + 04 00 00 00 00 10 18 00 89 00 10 00 01 02 00 00 + 00 00 00 05 20 00 00 00 21 02 00 00 00 10 14 00 + ff 01 1f 00 01 01 00 00 00 00 00 05 12 00 00 00 + 00 10 18 00 ff 01 1f 00 01 02 00 00 00 00 00 05 + 20 00 00 00 20 02 00 00 00 10 24 00 ff 01 1f 00 + 01 05 00 00 00 00 00 05 15 00 00 00 de 53 c1 2a + 2a 4f da ca c1 79 a6 32 b1 04 00 00 + """.translate(None, b' \n')) + descriptor = sd.SecurityDescriptor.from_bytes(raw_descriptor) + assert descriptor.flags == (sd.SECURITY_DESCRIPTOR_SELF_RELATIVE + | sd.SECURITY_DESCRIPTOR_DACL_PRESENT + | sd.SECURITY_DESCRIPTOR_DACL_AUTO_INHERITED) + assert descriptor.dacl is not None + assert descriptor.sacl is None + assert str(descriptor.owner) == "S-1-5-21-717312990-3403304746-849770945-1201" + assert str(descriptor.group) == "S-1-5-21-717312990-3403304746-849770945-513" + + acl = descriptor.dacl + assert acl.revision == 2 + assert len(acl.aces) == 4 + assert str(acl.aces[0].sid) == sd.SID_BUILTIN_USERS + assert str(acl.aces[1].sid) == sd.SID_LOCAL_SYSTEM + assert str(acl.aces[2].sid) == sd.SID_BUILTIN_ADMINISTRATORS + assert str(acl.aces[3].sid) == "S-1-5-21-717312990-3403304746-849770945-1201" diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..8bfd5a1 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,4 @@ +[egg_info] +tag_build = +tag_date = 0 + diff --git a/setup.py b/setup.py index e9093d7..550d972 100644 --- a/setup.py +++ b/setup.py @@ -8,7 +8,7 @@ setup( name = "pysmb", - version = "1.1.19", + version = "1.2.7", author = "Michael Teo", author_email = "miketeo@miketeo.net", license = "zlib/libpng", diff --git a/sphinx/requirements.txt b/sphinx/requirements.txt new file mode 100644 index 0000000..c14b1c8 --- /dev/null +++ b/sphinx/requirements.txt @@ -0,0 +1,2 @@ +twisted>=15.0.0 +pyasn1>=0.3.0 diff --git a/sphinx/source/api/smb_SMBHandler.rst b/sphinx/source/api/smb_SMBHandler.rst index da106fe..9300de1 100644 --- a/sphinx/source/api/smb_SMBHandler.rst +++ b/sphinx/source/api/smb_SMBHandler.rst @@ -6,8 +6,12 @@ Notes ----- -* Note that you need to pass in a valid hostname or IP address for the host component of the URL. - Do not use the Windows/NetBIOS machine name for the host component. +* The host component of the URL must be one of the following: + + * A fully-qualified hostname that can be resolved by your local DNS service. Example: myserver.test.com + * An IP address. Example: 192.168.1.1 + * A comma-separated string "," where ** is the Windows/NetBIOS machine name for remote SMB service, and ** is the service's IP address. Example: MYSERVER,192.168.1.1 + * The first component of the path in the URL points to the name of the shared folder. Subsequent path components will point to the directory/folder of the file. * You can retrieve and upload files, but you cannot delete files/folders or create folders. @@ -16,7 +20,7 @@ Example ------- -The following code snippet illustrates file retrieval.:: +The following code snippet illustrates file retrieval with Python 2.:: # -*- coding: utf-8 -*- import urllib2 @@ -34,7 +38,7 @@ # Process fh2 like a file-like object and then close it. fh2.close() -The following code snippet illustrates file upload. You need to provide a file-like object for the *data* parameter in the *open()* method:: +The following code snippet illustrates file upload with Python 2. You need to provide a file-like object for the *data* parameter in the *open()* method:: import urllib2 from smb.SMBHandler import SMBHandler @@ -46,3 +50,34 @@ # Reading from fh will only return an empty string fh.close() + + +The following code snippet illustrates file retrieval with Python 3.:: + + import urllib + from smb.SMBHandler import SMBHandler + + director = urllib.request.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/rfc1001.txt') + + # Process fh like a file-like object and then close it. + fh.close() + + # For paths/files with unicode characters, simply pass in the URL as an unicode string + fh2 = director.open(u'smb://myuserID:mypassword@192.168.1.1/sharedfolder/测试文件夹/垃圾文件.dat') + + # Process fh2 like a file-like object and then close it. + fh2.close() + +The following code snippet illustrates file upload with Python 3. You need to provide a file-like object for the *data* parameter in the *open()* method:: + + import urllib + from smb.SMBHandler import SMBHandler + + file_fh = open('local_file.dat', 'rb') + + director = urllib.request.build_opener(SMBHandler) + fh = director.open('smb://myuserID:mypassword@192.168.1.1/sharedfolder/upload_file.dat', data = file_fh) + + # Reading from fh will only return an empty string + fh.close() diff --git a/sphinx/source/api/smb_security_descriptors.rst b/sphinx/source/api/smb_security_descriptors.rst new file mode 100644 index 0000000..0f048fe --- /dev/null +++ b/sphinx/source/api/smb_security_descriptors.rst @@ -0,0 +1,23 @@ + +Security Descriptors +==================== + +.. module:: smb.security_descriptors + :synopsis: Data structures used in Windows security descriptors. + +This module implements security descriptors, and associated data +structures, as specified in `[MS-DTYP]`_. + +.. autoclass:: SID + :members: + +.. autoclass:: ACE + :members: + +.. autoclass:: ACL + :members: + +.. autoclass:: SecurityDescriptor + :members: + +.. _[MS-DTYP]: https://msdn.microsoft.com/en-us/library/cc230273.aspx diff --git a/sphinx/source/conf.py b/sphinx/source/conf.py index 12ec1b9..c3a7815 100644 --- a/sphinx/source/conf.py +++ b/sphinx/source/conf.py @@ -1,12 +1,4 @@ # -*- coding: utf-8 -*- -# -# pysmb documentation build configuration file, created by -# sphinx-quickstart on Sun Dec 18 15:54:40 2011. -# -# This file is execfile()d with the current directory set to its containing dir. -# -# Note that not all possible configuration values are present in this -# autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. @@ -17,7 +9,7 @@ # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) -sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'python2')) +sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'python3')) # -- General configuration ----------------------------------------------------- @@ -42,16 +34,16 @@ # General information about the project. project = u'pysmb' -copyright = u'2001-2015, Michael Teo http://miketeo.net/' +copyright = u'2001-2021, Michael Teo https://miketeo.net/' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. -version = '1.1.18' +version = '1.2.7' # The full version, including alpha/beta/rc tags. -release = '1.1.18' +release = '1.2.7' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/sphinx/source/extending.rst b/sphinx/source/extending.rst index 9945212..c39572c 100644 --- a/sphinx/source/extending.rst +++ b/sphinx/source/extending.rst @@ -14,6 +14,7 @@ 3. Write your own loop handling method to read data from the socket. Once data have been read, call *feedData* method with the parameter. The *feedData* method has its own internal buffer, so it can accept incomplete NetBIOS session packet data. 4. Override + * *onAuthOK* method to include your own operations to perform when authentication is successful. You can initiate file operations in this method. * *onAuthFailed* method to include your own processing on what to do when authentication fails. You can report this as an error, or to try a different NTLM authentication algorithm (*use_ntlm_v2* parameter in the constructor). * *onNMBSessionFailed* method to include your own processing on what to do when pysmb fails to setup the NetBIOS session with the remote server. Usually, this is due to a wrong *remote_name* parameter in the constructor. diff --git a/sphinx/source/index.rst b/sphinx/source/index.rst index 7638fcd..b872dec 100644 --- a/sphinx/source/index.rst +++ b/sphinx/source/index.rst @@ -1,16 +1,11 @@ -.. pysmb documentation master file, created by - sphinx-quickstart on Sun Dec 18 15:54:40 2011. - You can adapt this file completely to your liking, but it should at least - contain the root `toctree` directive. - Welcome to pysmb's documentation! ================================= pysmb is a pure Python implementation of the client-side SMB/CIFS protocol (SMB1 and SMB2) which is the underlying protocol that facilitates file sharing and printing between Windows machines, as well as with Linux machines via the Samba server application. -pysmb is developed in Python 2.4.6, Python 2.7.1 and Python 3.2.3 and has been tested against shared folders on Windows XP SP3, Windows Vista, Windows 7 and Samba 3.x. +pysmb is developed in Python 2.7.x and Python 3.8.x and has been tested against shared folders on Windows 7, Windows 10 and Samba 4.x. -The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. +The latest version of pysmb is always available at the pysmb project page at `miketeo.net `_. License ------- @@ -90,6 +85,8 @@ As a software developer who is looking to modify pysmb so that you can integrate it to other network frameworks: * Read :doc:`extending` +If you are upgrading from older pysmb versions: + * Read :doc:`upgrading` Indices and tables @@ -101,6 +98,7 @@ api/* extending + upgrading * :ref:`genindex` * :ref:`search` diff --git a/sphinx/source/upgrading.rst b/sphinx/source/upgrading.rst new file mode 100644 index 0000000..8d5e7cd --- /dev/null +++ b/sphinx/source/upgrading.rst @@ -0,0 +1,63 @@ +Upgrading from older pysmb versions +==================================== + +This page documents the improvements and changes to the API that could be incompatible with previous releases. + +pysmb 1.2.0 +----------- +- Add new `delete_matching_folders` parameter to `deleteFiles()` method in SMBProtocolFactory and SMBConnection + class to support deletion of sub-folders. If you are passing timeout parameter to the `deleteFiles()` method + in your application, please switch to using named parameter for timeout. + +pysmb 1.1.28 +------------ +- SharedFile instances returned from the `listPath()` method now has a new property + `file_id` attribute which represents the file reference number given by the remote SMB server. + +pysmb 1.1.26 +------------ +- SMBConnection class can now be used as a context manager + +pysmb 1.1.25 +------------ +- SharedFile class has a new property `isNormal` which will be True if the file is a + 'normal' file. pysmb defines a 'normal' file as a file entry that is not + read-only, not hidden, not system, not archive and not a directory; + it ignores other attributes like compression, indexed, sparse, temporary and encryption. +- `listPath()` method in SMBProtocolFactory and SMBConnection class will now include + 'normal' files by default if you do not specify the `search` parameter. + +pysmb 1.1.20 +------------ +- A new method `getSecurity()` was added to SMBConnection and SMBProtocolFactory class. + +pysmb 1.1.15 +------------ +- Add new `truncate` parameter to `storeFileFromOffset()` in SMBProtocolFactory and SMBConnection + class to support truncation of the file before writing. If you are passing timeout parameter + to the `storeFileFromOffset()` method in your application, please switch to using named parameter for timeout. + +pysmb 1.1.11 +------------ +- A new method `storeFileFromOffset()` was added to SMBConnection and SMBProtocolFactory class. + +pysmb 1.1.10 +------------ +- A new method `getAttributes()` was added to SMBConnection and SMBProtocolFactory class +- SharedFile class has a new property `isReadOnly` to indicate the file is read-only on the remote filesystem. + +pysmb 1.1.2 +----------- +- `queryIPForName()` method in nmb.NetBIOS and nmb.NBNSProtocol class will now return only the server machine name and ignore workgroup names. + +pysmb 1.0.3 +----------- +- Two new methods were added to NBNSProtocol class: `queryIPForName()` and `NetBIOS.queryIPForName()` + to support querying for a machine's NetBIOS name at the given IP address. +- A new method `retrieveFileFromOffset()` was added to SMBProtocolFactory and SMBConnection + to support finer control of file retrieval operation. + +pysmb 1.0.0 +----------- +pysmb was completely rewritten in version 1.0.0. +If you are upgrading from pysmb 0.x, you most likely have to rewrite your application for the new 1.x API.