1
2import os, logging, time
3from twisted.internet import reactor, defer
4from twisted.internet.protocol import ClientFactory, Protocol
5from .smb_constants import *
6from .smb_structs import *
7from .base import SMB, NotConnectedError, NotReadyError, SMBTimeout
8
9
10__all__ = [ 'SMBProtocolFactory', 'NotConnectedError', 'NotReadyError' ]
11
12
13class SMBProtocol(Protocol, SMB):
14
15    log = logging.getLogger('SMB.SMBProtocol')
16
17    #
18    # Protocol Methods
19    #
20
21    def connectionMade(self):
22        self.factory.instance = self
23        if not self.is_direct_tcp:
24            self.requestNMBSession()
25        else:
26            self.onNMBSessionOK()
27
28
29    def connectionLost(self, reason):
30        if self.factory.instance == self:
31            self.instance = None
32
33    def dataReceived(self, data):
34        self.feedData(data)
35
36    #
37    # SMB (and its superclass) Methods
38    #
39
40    def write(self, data):
41        self.transport.write(data)
42
43    def onAuthOK(self):
44        if self.factory.instance == self:
45            self.factory.onAuthOK()
46            reactor.callLater(1, self._cleanupPendingRequests)
47
48    def onAuthFailed(self):
49        if self.factory.instance == self:
50            self.factory.onAuthFailed()
51
52    def onNMBSessionFailed(self):
53        self.log.error('Cannot establish NetBIOS session. You might have provided a wrong remote_name')
54
55    #
56    # Protected Methods
57    #
58
59    def _cleanupPendingRequests(self):
60        if self.factory.instance == self:
61            now = time.time()
62            to_remove = []
63            for mid, r in self.pending_requests.items():
64                if r.expiry_time < now:
65                    try:
66                        r.errback(SMBTimeout())
67                    except Exception: pass
68                    to_remove.append(mid)
69
70            for mid in to_remove:
71                del self.pending_requests[mid]
72
73            reactor.callLater(1, self._cleanupPendingRequests)
74
75
76class SMBProtocolFactory(ClientFactory):
77
78    protocol = SMBProtocol
79    log = logging.getLogger('SMB.SMBFactory')
80
81    #: SMB messages will never be signed regardless of remote server's configurations; access errors will occur if the remote server requires signing.
82    SIGN_NEVER = 0
83    #: SMB messages will be signed when remote server supports signing but not requires signing.
84    SIGN_WHEN_SUPPORTED = 1
85    #: SMB messages will only be signed when remote server requires signing.
86    SIGN_WHEN_REQUIRED = 2
87
88    def __init__(self, username, password, my_name, remote_name, domain = '', use_ntlm_v2 = True, sign_options = SIGN_WHEN_REQUIRED, is_direct_tcp = False):
89        """
90        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.
91        Note that the default TCP port for most SMB/CIFS servers using NetBIOS over TCP/IP is 139.
92        Some newer server installations might also support Direct hosting of SMB over TCP/IP; for these servers, the default TCP port is 445.
93
94        *username* and *password* are the user credentials required to authenticate the underlying SMB connection with the remote server.
95        File operations can only be proceeded after the connection has been authenticated successfully.
96
97        :param string my_name: The local NetBIOS machine name that will identify where this connection is originating from.
98                               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 ``\/:*?";|+``
99        :param string remote_name: The NetBIOS machine name of the remote server.
100                                   On windows, you can find out the machine name by right-clicking on the "My Computer" and selecting "Properties".
101                                   This parameter must be the same as what has been configured on the remote server, or else the connection will be rejected.
102        :param string domain: The network domain. On windows, it is known as the workgroup. Usually, it is safe to leave this parameter as an empty string.
103        :param boolean use_ntlm_v2: Indicates whether pysmb should be NTLMv1 or NTLMv2 authentication algorithm for authentication.
104                                    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.
105                                    Hence, we can only "guess" or try both algorithms.
106                                    On Sambda, Windows Vista and Windows 7, NTLMv2 is enabled by default. On Windows XP, we can use NTLMv1 before NTLMv2.
107        :param int sign_options: Determines whether SMB messages will be signed. Default is *SIGN_WHEN_REQUIRED*.
108                                 If *SIGN_WHEN_REQUIRED* (value=2), SMB messages will only be signed when remote server requires signing.
109                                 If *SIGN_WHEN_SUPPORTED* (value=1), SMB messages will be signed when remote server supports signing but not requires signing.
110                                 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.
111        :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.
112                                      The default parameter is False which will use NetBIOS over TCP/IP for wider compatibility (TCP port: 139).
113        """
114        self.username = username
115        self.password = password
116        self.my_name = my_name
117        self.remote_name = remote_name
118        self.domain = domain
119        self.use_ntlm_v2 = use_ntlm_v2
120        self.sign_options = sign_options
121        self.is_direct_tcp = is_direct_tcp
122        self.instance = None    #: The single SMBProtocol instance for each SMBProtocolFactory instance. Usually, you should not need to touch this attribute directly.
123
124    #
125    # Public Property
126    #
127
128    @property
129    def isReady(self):
130        """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."""
131        return bool(self.instance and self.instance.has_authenticated)
132
133    @property
134    def isUsingSMB2(self):
135        """A convenient property to return True if the underlying SMB connection is using SMB2 protocol."""
136        return self.instance and self.instance.is_using_smb2
137
138    #
139    # Public Methods for Callbacks
140    #
141
142    def onAuthOK(self):
143        """
144        Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling.
145        This method will be called when the server has replied that the SMB connection has been successfully authenticated.
146        File operations can proceed when this method has been called.
147        """
148        pass
149
150    def onAuthFailed(self):
151        """
152        Override this method in your *SMBProtocolFactory* subclass to add in post-authentication handling.
153        This method will be called when the server has replied that the SMB connection has been successfully authenticated.
154
155        If you want to retry authenticating from this method,
156         1. Disconnect the underlying SMB connection (call ``self.instance.transport.loseConnection()``)
157         2. Create a new SMBProtocolFactory subclass instance with different user credientials or different NTLM algorithm flag.
158         3. Call ``reactor.connectTCP`` with the new instance to re-establish the SMB connection
159        """
160        pass
161
162    #
163    # Public Methods
164    #
165
166    def listShares(self, timeout = 30):
167        """
168        Retrieve a list of shared resources on remote server.
169
170        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
171        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedDevice<smb_SharedDevice>` instances.
172        """
173        if not self.instance:
174            raise NotConnectedError('Not connected to server')
175
176        d = defer.Deferred()
177        self.instance._listShares(d.callback, d.errback, timeout)
178        return d
179
180    def listPath(self, service_name, path,
181                 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,
182                 pattern = '*', timeout = 30):
183        """
184        Retrieve a directory listing of files/folders at *path*
185
186        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.
187        It ignores other attributes like compression, indexed, sparse, temporary and encryption.
188
189        Note that the default search parameter will query for all read-only (SMB_FILE_ATTRIBUTE_READONLY), hidden (SMB_FILE_ATTRIBUTE_HIDDEN),
190        system (SMB_FILE_ATTRIBUTE_SYSTEM), archive (SMB_FILE_ATTRIBUTE_ARCHIVE), normal (SMB_FILE_ATTRIBUTE_INCL_NORMAL) files
191        and directories (SMB_FILE_ATTRIBUTE_DIRECTORY).
192        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.
193        SMB_FILE_ATTRIBUTE_NORMAL should be used by itself and not be used with other bit constants.
194
195        :param string/unicode service_name: the name of the shared folder for the *path*
196        :param string/unicode path: path relative to the *service_name* where we are interested to learn about its files/sub-folders.
197        :param integer search: integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py).
198        :param string/unicode pattern: the filter to apply to the results before returning to the client.
199        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
200        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of :doc:`smb.base.SharedFile<smb_SharedFile>` instances.
201        """
202        if not self.instance:
203            raise NotConnectedError('Not connected to server')
204
205        d = defer.Deferred()
206        self.instance._listPath(service_name, path, d.callback, d.errback, search = search, pattern = pattern, timeout = timeout)
207        return d
208
209    def listSnapshots(self, service_name, path, timeout = 30):
210        """
211        Retrieve a list of available snapshots (a.k.a. shadow copies) for *path*.
212
213        Note that snapshot features are only supported on Windows Vista Business, Enterprise and Ultimate, and on all Windows 7 editions.
214
215        :param string/unicode service_name: the name of the shared folder for the *path*
216        :param string/unicode path: path relative to the *service_name* where we are interested in the list of available snapshots
217        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a list of python *datetime.DateTime*
218                 instances in GMT/UTC time zone
219        """
220        if not self.instance:
221            raise NotConnectedError('Not connected to server')
222
223        d = defer.Deferred()
224        self.instance._listSnapshots(service_name, path, d.callback, d.errback, timeout = timeout)
225        return d
226
227    def getAttributes(self, service_name, path, timeout = 30):
228        """
229        Retrieve information about the file at *path* on the *service_name*.
230
231        :param string/unicode service_name: the name of the shared folder for the *path*
232        :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.
233        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a :doc:`smb.base.SharedFile<smb_SharedFile>` instance containing the attributes of the file.
234        """
235        if not self.instance:
236            raise NotConnectedError('Not connected to server')
237
238        d = defer.Deferred()
239        self.instance._getAttributes(service_name, path, d.callback, d.errback, timeout = timeout)
240        return d
241
242    def retrieveFile(self, service_name, path, file_obj, timeout = 30):
243        """
244        Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*.
245
246        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*.
247
248        The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size
249        of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes).
250        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.
251
252        :param string/unicode service_name: the name of the shared folder for the *path*
253        :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.
254        :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.
255        :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* ).
256                 The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py)
257        """
258        return self.retrieveFileFromOffset(service_name, path, file_obj, 0, -1, timeout)
259
260    def retrieveFileFromOffset(self, service_name, path, file_obj, offset = 0, max_length = -1, timeout = 30):
261        """
262        Retrieve the contents of the file at *path* on the *service_name* and write these contents to the provided *file_obj*.
263
264        The meaning of the *timeout* parameter will be different from other file operation methods. As the downloaded file usually exceeeds the maximum size
265        of each SMB/CIFS data message, it will be packetized into a series of request messages (each message will request about about 60kBytes).
266        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.
267
268        :param string/unicode service_name: the name of the shared folder for the *path*
269        :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.
270        :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.
271        :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.
272        :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.
273                                        If zero, the *Deferred* callback is invoked immediately after the file is opened successfully for reading.
274        :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* ).
275                 The file attributes is an integer value made up from a bitwise-OR of *SMB_FILE_ATTRIBUTE_xxx* bits (see smb_constants.py)
276        """
277        if not self.instance:
278            raise NotConnectedError('Not connected to server')
279
280        d = defer.Deferred()
281        self.instance._retrieveFileFromOffset(service_name, path, file_obj, d.callback, d.errback, offset, max_length, timeout = timeout)
282        return d
283
284    def storeFile(self, service_name, path, file_obj, timeout = 30):
285        """
286        Store the contents of the *file_obj* at *path* on the *service_name*.
287
288        The meaning of the *timeout* parameter will be different from other file operation methods. As the uploaded file usually exceeeds the maximum size
289        of each SMB/CIFS data message, it will be packetized into a series of messages (usually about 60kBytes).
290        The *timeout* parameter is an integer/float value that specifies the timeout interval for these individual SMB/CIFS message to be transmitted and acknowledged
291        by the remote SMB/CIFS server.
292
293        :param string/unicode service_name: the name of the shared folder for the *path*
294        :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.
295                                    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.
296        :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.
297        :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 ).
298        """
299        if not self.instance:
300            raise NotConnectedError('Not connected to server')
301
302        d = defer.Deferred()
303        self.instance._storeFile(service_name, path, file_obj, d.callback, d.errback, timeout = timeout)
304        return d
305
306    def deleteFiles(self, service_name, path_file_pattern, timeout = 30):
307        """
308        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.
309
310        :param string/unicode service_name: Contains the name of the shared folder.
311        :param string/unicode path_file_pattern: The pathname of the file(s) to be deleted, relative to the service_name.
312                                                 Wildcards may be used in th filename component of the path.
313                                                 If your path/filename contains non-English characters, you must pass in an unicode string.
314        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
315        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path_file_pattern* parameter.
316        """
317        if not self.instance:
318            raise NotConnectedError('Not connected to server')
319
320        d = defer.Deferred()
321        self.instance._deleteFiles(service_name, path_file_pattern, d.callback, d.errback, timeout = timeout)
322        return d
323
324    def createDirectory(self, service_name, path):
325        """
326        Creates a new directory *path* on the *service_name*.
327
328        :param string/unicode service_name: Contains the name of the shared folder.
329        :param string/unicode path: The path of the new folder (relative to) the shared folder.
330                                    If the path contains non-English characters, an unicode string must be used to pass in the path.
331        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
332        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter.
333        """
334        if not self.instance:
335            raise NotConnectedError('Not connected to server')
336
337        d = defer.Deferred()
338        self.instance._createDirectory(service_name, path, d.callback, d.errback)
339        return d
340
341    def deleteDirectory(self, service_name, path):
342        """
343        Delete the empty folder at *path* on *service_name*
344
345        :param string/unicode service_name: Contains the name of the shared folder.
346        :param string/unicode path: The path of the to-be-deleted folder (relative to) the shared folder.
347                                    If the path contains non-English characters, an unicode string must be used to pass in the path.
348        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
349        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *path* parameter.
350        """
351        if not self.instance:
352            raise NotConnectedError('Not connected to server')
353
354        d = defer.Deferred()
355        self.instance._deleteDirectory(service_name, path, d.callback, d.errback)
356        return d
357
358    def rename(self, service_name, old_path, new_path):
359        """
360        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
361
362        *old_path* and *new_path* are string/unicode referring to the old and new path of the renamed resources (relative to) the shared folder.
363        If the path contains non-English characters, an unicode string must be used to pass in the path.
364
365        :param string/unicode service_name: Contains the name of the shared folder.
366        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
367        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with a 2-element tuple of ( *old_path*, *new_path* ).
368        """
369        if not self.instance:
370            raise NotConnectedError('Not connected to server')
371
372        d = defer.Deferred()
373        self.instance._rename(service_name, old_path, new_path, d.callback, d.errback)
374        return d
375
376    def echo(self, data, timeout = 10):
377        """
378        Send an echo command containing *data* to the remote SMB/CIFS server. The remote SMB/CIFS will reply with the same *data*.
379
380        :param bytes data: Data to send to the remote server. Must be a bytes object.
381        :param integer/float timeout: Number of seconds that pysmb will wait before raising *SMBTimeout* via the returned *Deferred* instance's *errback* method.
382        :return: A *twisted.internet.defer.Deferred* instance. The callback function will be called with the *data* parameter.
383        """
384        if not self.instance:
385            raise NotConnectedError('Not connected to server')
386
387        d = defer.Deferred()
388        self.instance._echo(data, d.callback, d.errback, timeout)
389        return d
390
391    def closeConnection(self):
392        """
393        Disconnect from the remote SMB/CIFS server. The TCP connection will be closed at the earliest opportunity after this method returns.
394
395        :return: None
396        """
397        if not self.instance:
398            raise NotConnectedError('Not connected to server')
399
400        self.instance.transport.loseConnection()
401
402    #
403    # ClientFactory methods
404    # (Do not touch these unless you know what you are doing)
405    #
406
407    def buildProtocol(self, addr):
408        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)
409        p.factory = self
410        return p
411