File: timeout_socket.py

package info (click to toggle)
pyftpd 0.8.5%2Bnmu1
  • links: PTS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch
  • size: 484 kB
  • ctags: 470
  • sloc: python: 2,804; sh: 55; makefile: 42
file content (249 lines) | stat: -rw-r--r-- 7,844 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
""" Sockets with timeouts.

Defines a "timeout_socket" class for connections that can potentially
cause the server to hang.  It uses select, and is based on code originally
from Scott Cotton.

The following people have contributed to the development of this module:

        Scott Cotton <scott@chronis.pobox.com>
        Lloyd Zusman <ljz@asfast.com
        Phil Mayes <pmayes@olivebr.com>
        Piers Lauder <piers@cs.su.oz.au>

Here are examples using smtplib.py and poplib.py by inheriting:

class timeout_POP3(poplib.POP3):
    def __init__(self, host, port = poplib.POP3_PORT):
        self.host = host
        self.port = port
        self.sock = timeout_socket.timeout_socket()
        self.sock.connect(self.host, self.port)
        self.file = self.sock.makefile('rb') # same as poplib.POP3
        self._debugging = 0
        self.welcome = self._getresp()

class timeout_SMTP(smtplib.SMTP):
    def connect(self, host='localhost', port = 0):
        '''Connect to a host on a given port.
        Override the std SMTP connect in order to use a timeout_socket.
        '''
        if not port:
            i = string.find(host, ':')
            if i >= 0:
                host, port = host[:i], host[i+1:]
                try: port = string.atoi(port)
                except string.atoi_error:
                    raise socket.error, "nonnumeric port"
        if not port: port = smtplib.SMTP_PORT
        self.sock = timeout_socket.timeout_socket()
        if self.debuglevel > 0: print 'connect:', (host, port)
        self.sock.connect(host, port)
        (code,msg)=self.getreply()
        if self.debuglevel >0 : print "connect:", msg
        return (code,msg)

This allows one to use poplib.py & smtplib.py unchanged.
"""

__version__ = "1.7"
__author__ = "Scott Cotton <scott@chronis.pobox.com>"


import socket
import errno
import select
import string
_TIMEOUT = 20.0

class Timeout(Exception):
    pass

class timeout_socket:

    """ Instantiate with:

                timeout_socket(timeout=20, sock=None)

        where `timeout' is the desired timeout in seconds (default 20),
        and `sock' is a pre-existing socket (default: one is created).
    """

    def __init__(self, timeout=_TIMEOUT, sock=None):
        self.ndups = 0
        self.timeout(timeout)
        self.inbuf = ''
        if sock is None:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.s = sock
        self.ndups = 1
        self.s.setblocking(0)

    # destructor notes: socket.socket will close when destroyed

    def __getattr__(self, name):
         return getattr(self.s, name)   # Other socket methods

    def accept(self):
        timeout = self._timeout
        s = self.s
        try:
            # Non-blocking mode
            s.setblocking(1)
            sa = s.accept()
            s.setblocking(timeout != 0)
            return sa
        except socket.error,why:
            if not timeout:
                raise
            s.setblocking(1)
            # The exception arguments can be (string) or (int,string)
            if len(why.args) == 1:
                code = 0
            else:
                code,why = why
            if code not in (errno.EAGAIN, errno.EWOULDBLOCK):
                raise
            # Ok, then wait...
            r,w,e = select.select([s],[],[],timeout)
            if r:
                try:
                    sa = s.accept()
                    return sa
                except socket.error,why:
                    # This can throw string or (int,string)
                    if len(why.args) == 1:
                        code = 0
                    else:
                        code,why = why
                    raise

        msg = 'accept timed out after %s seconds' % self._timeout
        raise Timeout(msg)

    def connect(self, *addr):
        timeout = self._timeout
        s = self.s
        try:
            # Non-blocking mode
            s.setblocking(0)
            apply(s.connect, addr)
            s.setblocking(timeout != 0)
            return 1
        except socket.error,why:
            if not timeout:
                raise
            s.setblocking(1)
            # The exception arguments can be (string) or (int,string)
            if len(why.args) == 1:
                code = 0
            else:
                code,why = why
            if code not in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK): # WSAEWOULDBLOCK
                raise
            # Ok, then wait...
            r,w,e = select.select([],[s],[],timeout)
            if w:
                try:
                    apply(s.connect, addr)
                    return 1
                except socket.error,why:
                    # This can throw string or (int,string)
                    if len(why.args) == 1:
                        code = 0
                    else:
                        code,why = why
                    if code == errno.EISCONN:
                        return 1
                    raise

        msg = 'connect to %s timed out after %s seconds' % (str(addr), self._timeout)
        raise Timeout(msg)

    def send(self, data, flags=0):
        next = 0
        t = self._timeout
        total = len(data)
        while 1:
            try:
                r,w,e = select.select([],[self.s], [], t)
            except ValueError:
                raise Timeout("valueerror in select")
            if w:
                buf = data[next:next+8192]
                sent = self.s.send(buf, flags)
                next = next + sent
                if next == total:
                    return
            else:
                raise Timeout('timeout while sending "%.20s...": %d sec' % (data, t))

    def recv(self, amt, flags=0):
        r,w,e = select.select([self.s], [], [], self._timeout)
        if r:
            recvd = self.s.recv(amt, flags)
            return recvd
        raise Timeout("timeout while receiving from %s: %d sec" % (`self.s.getpeername()`, self._timeout))

    def makefile(self, flags="r", buffsize=-1):
        # makefile needs parameters
        # Just return ourself - watch out for multiple close(), and
        # provide read and readline methods expected by makefile result below.
        self.ndups = self.ndups+1 # nubmer or dupped descriptors
        return self


    def close(self):
        #if self.s.fileno() >= 0:
        self.ndups = self.ndups-1
        #print self.ndups
        if self.ndups == 0:
            #print "closing", self.s
            self.s.close()

    # New (non-standard socket) methods to support `makefile'.

    def read(self, amt):
        """ This only returns when amt has been read or socket times out """
        while len(self.inbuf) < amt:
            self.inbuf = self.inbuf + self.recv(4096)
        data = self.inbuf[:amt]
        self.inbuf = self.inbuf[amt:]
        return data

    def readline(self):
        """ readine for socket - buffers data """
        # Much slower than built-in method!
        while 1:
            lf = string.find(self.inbuf, '\n')
            if lf >= 0:
                break
            r = self.recv(4096)
            if not r: 
                # connection broken
                # without this readline would enter infinite loop
                break
            self.inbuf = self.inbuf + r
        lf = lf + 1
        data = self.inbuf[:lf]
        self.inbuf = self.inbuf[lf:]
        return data


    # Other new methods

    def recvpending(self, timeout=0):
        """ returns 1/0 """
        return [] != select.select([self.s], [], [], int(timeout) or self._timeout)[0]

    def timeout(self, newtimo):
        """ change socket timeout """
        self._timeout = int(newtimo)

    def flush(self):
        # TCPServer needs this
        pass

    def write(self, data):
        self.send(data)