/mandos/trunk

To get this branch, use:
bzr branch http://bzr.recompile.se/loggerhead/mandos/trunk

« back to all changes in this revision

Viewing changes to server.py

  • Committer: Teddy Hogeborn
  • Date: 2007-12-19 07:58:13 UTC
  • Revision ID: teddy@fukt.bsnet.se-20071219075813-5u1w3gujvttj83qs
* server.py (Client.created, Client.next_check): New.
  (string_to_delta): New.
  (main): New options "--check" and "--interval".  Use string_to_delta to
  parse arguments to "--timeout" and "--interval".

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
import gnutls.errors
12
12
import ConfigParser
13
13
import sys
14
 
import re
15
 
import os
16
 
import signal
17
14
 
18
15
class Client(object):
19
 
    def __init__(self, name=None, options=None, dn=None,
20
 
                 password=None, passfile=None, fqdn=None,
21
 
                 timeout=None, interval=-1):
 
16
    def __init__(self, name=None, dn=None, password=None,
 
17
                 passfile=None, fqdn=None, timeout=None,
 
18
                 interval=-1):
22
19
        self.name = name
23
20
        self.dn = dn
24
21
        if password:
29
26
            print "No Password or Passfile in client config file"
30
27
            # raise RuntimeError XXX
31
28
            self.password = "gazonk"
32
 
        self.fqdn = fqdn                # string
 
29
        self.fqdn = fqdn
33
30
        self.created = datetime.datetime.now()
34
 
        self.last_seen = None           # datetime.datetime()
 
31
        self.last_seen = None
35
32
        if timeout is None:
36
 
            timeout = options.timeout
37
 
        self.timeout = timeout          # datetime.timedelta()
 
33
            timeout = self.server.options.timeout
 
34
        self.timeout = timeout
38
35
        if interval == -1:
39
 
            interval = options.interval
40
 
        self.interval = interval        # datetime.timedelta()
41
 
        self.next_check = datetime.datetime.now() # datetime.datetime()
42
 
        self.checker = None             # or a subprocess.Popen()
43
 
    def check_action(self, now=None):
44
 
        """The checker said something and might have completed.
45
 
        Check if is has, and take appropriate actions."""
46
 
        if self.checker.poll() is None:
47
 
            # False alarm, no result yet
48
 
            #self.checker.read()
49
 
            return
50
 
        if now is None:
51
 
            now = datetime.datetime.now()
52
 
        if self.checker.returncode == 0:
53
 
            self.last_seen = now
54
 
        while self.next_check <= now:
55
 
            self.next_check += self.interval
56
 
    handle_request = check_action
57
 
    def start_checker(self):
58
 
        self.stop_checker()
 
36
            interval = self.server.options.interval
 
37
        self.interval = interval
 
38
        self.next_check = datetime.datetime.now()
 
39
 
 
40
def server_bind(self):
 
41
    if self.options.interface:
 
42
        if not hasattr(socket, "SO_BINDTODEVICE"):
 
43
            # From /usr/include/asm-i486/socket.h
 
44
            socket.SO_BINDTODEVICE = 25
59
45
        try:
60
 
            self.checker = subprocess.Popen("sleep 1; fping -q -- %s"
61
 
                                            % re.escape(self.fqdn),
62
 
                                            stdout=subprocess.PIPE,
63
 
                                            close_fds=True,
64
 
                                            shell=True, cwd="/")
65
 
        except subprocess.OSError, e:
66
 
            print "Failed to start subprocess:", e
67
 
    def stop_checker(self):
68
 
        if self.checker is None:
69
 
            return
70
 
        os.kill(self.checker.pid, signal.SIGTERM)
71
 
        if self.checker.poll() is None:
72
 
            os.kill(self.checker.pid, signal.SIGKILL)
73
 
        self.checker = None
74
 
    __del__ = stop_checker
75
 
    def fileno(self):
76
 
        if self.checker is None:
77
 
            return None
78
 
        return self.checker.stdout.fileno()
79
 
    def next_stop(self):
80
 
        """The time when something must be done about this client"""
81
 
        return min(self.last_seen + self.timeout, self.next_check)
82
 
    def still_valid(self, now=None):
83
 
        """Has this client's timeout not passed?"""
84
 
        if now is None:
85
 
            now = datetime.datetime.now()
86
 
        return now < (self.last_seen + timeout)
87
 
    def it_is_time_to_check(self, now=None):
88
 
        if now is None:
89
 
            now = datetime.datetime.now()
90
 
        return self.next_check <= now
91
 
 
92
 
 
93
 
class server_metaclass(type):
94
 
    "Common behavior for the UDP and TCP server classes"
95
 
    def __new__(cls, name, bases, attrs):
96
 
        attrs["address_family"] = socket.AF_INET6
97
 
        attrs["allow_reuse_address"] = True
98
 
        def server_bind(self):
99
 
            if self.options.interface:
100
 
                if not hasattr(socket, "SO_BINDTODEVICE"):
101
 
                    # From /usr/include/asm-i486/socket.h
102
 
                    socket.SO_BINDTODEVICE = 25
103
 
                try:
104
 
                    self.socket.setsockopt(socket.SOL_SOCKET,
105
 
                                           socket.SO_BINDTODEVICE,
106
 
                                           self.options.interface)
107
 
                except socket.error, error:
108
 
                    if error[0] == errno.EPERM:
109
 
                        print "Warning: No permission to bind to interface", \
110
 
                              self.options.interface
111
 
                    else:
112
 
                        raise error
113
 
            return super(type(self), self).server_bind()
114
 
        attrs["server_bind"] = server_bind
115
 
        def init(self, *args, **kwargs):
116
 
            if "options" in kwargs:
117
 
                self.options = kwargs["options"]
118
 
                del kwargs["options"]
119
 
            if "clients" in kwargs:
120
 
                self.clients = kwargs["clients"]
121
 
                del kwargs["clients"]
122
 
            if "credentials" in kwargs:
123
 
                self.credentials = kwargs["credentials"]
124
 
                del kwargs["credentials"]
125
 
            return super(type(self), self).__init__(*args, **kwargs)
126
 
        attrs["__init__"] = init
127
 
        return type.__new__(cls, name, bases, attrs)
 
46
            self.socket.setsockopt(socket.SOL_SOCKET,
 
47
                                   socket.SO_BINDTODEVICE,
 
48
                                   self.options.interface)
 
49
        except socket.error, error:
 
50
            if error[0] == errno.EPERM:
 
51
                print "Warning: Denied permission to bind to interface", \
 
52
                      self.options.interface
 
53
            else:
 
54
                raise error
 
55
    return super(type(self), self).server_bind()
 
56
 
 
57
 
 
58
def init_with_options(self, *args, **kwargs):
 
59
    if "options" in kwargs:
 
60
        self.options = kwargs["options"]
 
61
        del kwargs["options"]
 
62
    if "clients" in kwargs:
 
63
        self.clients = kwargs["clients"]
 
64
        del kwargs["clients"]
 
65
    if "credentials" in kwargs:
 
66
        self.credentials = kwargs["credentials"]
 
67
        del kwargs["credentials"]
 
68
    return super(type(self), self).__init__(*args, **kwargs)
128
69
 
129
70
 
130
71
class udp_handler(SocketServer.DatagramRequestHandler, object):
134
75
 
135
76
 
136
77
class IPv6_UDPServer(SocketServer.UDPServer, object):
137
 
    __metaclass__ = server_metaclass
 
78
    __init__ = init_with_options
 
79
    address_family = socket.AF_INET6
 
80
    allow_reuse_address = True
 
81
    server_bind = server_bind
138
82
    def verify_request(self, request, client_address):
139
83
        print "UDP request came"
140
84
        return request[0] == "Marco"
166
110
            # Log maybe? XXX
167
111
        session.bye()
168
112
 
169
 
 
170
113
class IPv6_TCPServer(SocketServer.ForkingTCPServer, object):
171
 
    __metaclass__ = server_metaclass
 
114
    __init__ = init_with_options
 
115
    address_family = socket.AF_INET6
 
116
    allow_reuse_address = True
172
117
    request_queue_size = 1024
 
118
    server_bind = server_bind
173
119
 
174
120
 
175
121
in6addr_any = "::"
176
122
 
 
123
cred = None
 
124
 
177
125
def string_to_delta(interval):
178
126
    """Parse a string and return a datetime.timedelta
179
127
 
207
155
        raise ValueError
208
156
    return delta
209
157
 
210
 
 
211
158
def main():
212
159
    parser = OptionParser()
213
160
    parser.add_option("-i", "--interface", type="string",
265
212
    defaults = {}
266
213
    client_config_object = ConfigParser.SafeConfigParser(defaults)
267
214
    client_config_object.read("mandos-clients.conf")
268
 
    clients = [Client(name=section, options=options,
 
215
    clients = [Client(name=section,
269
216
                      **(dict(client_config_object.items(section))))
270
217
               for section in client_config_object.sections()]
271
218
    
280
227
                                credentials=cred)
281
228
    
282
229
    while True:
283
 
        try:
284
 
            input, out, err = select.select((udp_server,
285
 
                                             tcp_server), (), ())
286
 
            if not input:
287
 
                pass
288
 
            else:
289
 
                for obj in input:
290
 
                    obj.handle_request()
291
 
        except KeyboardInterrupt:
292
 
            break
293
 
    
294
 
    # Cleanup here
295
 
    for client in clients:
296
 
        client.stop_checker()
 
230
        in_, out, err = select.select((udp_server,
 
231
                                       tcp_server), (), ())
 
232
        for server in in_:
 
233
            server.handle_request()
297
234
 
298
235
 
299
236
if __name__ == "__main__":