source: trunk/packages/xen-3.1/xen-3.1/tools/python/xen/web/tcp.py @ 34

Last change on this file since 34 was 34, checked in by hartmans, 18 years ago

Add xen and xen-common

File size: 2.4 KB
Line 
1#============================================================================
2# This library is free software; you can redistribute it and/or
3# modify it under the terms of version 2.1 of the GNU Lesser General Public
4# License as published by the Free Software Foundation.
5#
6# This library is distributed in the hope that it will be useful,
7# but WITHOUT ANY WARRANTY; without even the implied warranty of
8# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
9# Lesser General Public License for more details.
10#
11# You should have received a copy of the GNU Lesser General Public
12# License along with this library; if not, write to the Free Software
13# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
14#============================================================================
15# Copyright (C) 2005 Mike Wray <mike.wray@hp.com>
16# Copyright (C) 2005 XenSource Ltd.
17#============================================================================
18
19
20import errno
21import re
22import socket
23import time
24
25import connection
26
27from xen.xend.XendLogging import log
28
29
30class TCPListener(connection.SocketListener):
31
32    def __init__(self, protocol_class, port, interface, hosts_allow):
33        self.port = port
34        self.interface = interface
35        self.hosts_allow = hosts_allow
36        connection.SocketListener.__init__(self, protocol_class)
37
38
39    def createSocket(self):
40        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
41        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
42
43        # SO_REUSEADDR does not always ensure that we do not get an address
44        # in use error when restarted quickly
45        # we implement a timeout to try and avoid failing unnecessarily
46        timeout = time.time() + 30
47        while True:
48            try:
49                sock.bind((self.interface, self.port))
50                return sock
51            except socket.error, (_errno, strerrno):
52                if _errno == errno.EADDRINUSE and time.time() < timeout:
53                    time.sleep(0.5)
54                else:
55                    raise
56
57
58    def acceptConnection(self, sock, addrport):
59        addr = addrport[0]
60        if connection.hostAllowed(addrport, self.hosts_allow):
61            connection.SocketServerConnection(sock, self.protocol_class)
62        else:
63            try:
64                sock.close()
65            except:
66                pass
Note: See TracBrowser for help on using the repository browser.