/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 mandos

Merge threading/seg fault fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
11
11
# "AvahiService" class, and some lines in "main".
12
12
13
13
# Everything else is
14
 
# Copyright © 2008-2012 Teddy Hogeborn
15
 
# Copyright © 2008-2012 Björn Påhlsson
 
14
# Copyright © 2008-2011 Teddy Hogeborn
 
15
# Copyright © 2008-2011 Björn Påhlsson
16
16
17
17
# This program is free software: you can redistribute it and/or modify
18
18
# it under the terms of the GNU General Public License as published by
85
85
    except ImportError:
86
86
        SO_BINDTODEVICE = None
87
87
 
88
 
version = "1.5.1"
 
88
version = "1.4.1"
89
89
stored_state_file = "clients.pickle"
90
90
 
91
91
logger = logging.getLogger()
110
110
        return interface_index
111
111
 
112
112
 
113
 
def initlogger(debug, level=logging.WARNING):
 
113
def initlogger(level=logging.WARNING):
114
114
    """init logger and add loglevel"""
115
115
    
116
116
    syslogger.setFormatter(logging.Formatter
118
118
                            ' %(message)s'))
119
119
    logger.addHandler(syslogger)
120
120
    
121
 
    if debug:
122
 
        console = logging.StreamHandler()
123
 
        console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
124
 
                                               ' [%(process)d]:'
125
 
                                               ' %(levelname)s:'
126
 
                                               ' %(message)s'))
127
 
        logger.addHandler(console)
 
121
    console = logging.StreamHandler()
 
122
    console.setFormatter(logging.Formatter('%(asctime)s %(name)s'
 
123
                                           ' [%(process)d]:'
 
124
                                           ' %(levelname)s:'
 
125
                                           ' %(message)s'))
 
126
    logger.addHandler(console)
128
127
    logger.setLevel(level)
129
128
 
130
129
 
142
141
        self.gnupg.options.meta_interactive = False
143
142
        self.gnupg.options.homedir = self.tempdir
144
143
        self.gnupg.options.extra_args.extend(['--force-mdc',
145
 
                                              '--quiet',
146
 
                                              '--no-use-agent'])
 
144
                                              '--quiet'])
147
145
    
148
146
    def __enter__(self):
149
147
        return self
460
458
 
461
459
    @staticmethod
462
460
    def config_parser(config):
463
 
        """Construct a new dict of client settings of this form:
 
461
        """ Construct a new dict of client settings of this form:
464
462
        { client_name: {setting_name: value, ...}, ...}
465
 
        with exceptions for any special settings as defined above.
466
 
        NOTE: Must be a pure function. Must return the same result
467
 
        value given the same arguments.
468
 
        """
 
463
        with exceptions for any special settings as defined above"""
469
464
        settings = {}
470
465
        for client_name in config.sections():
471
466
            section = dict(config.items(client_name))
475
470
            # Reformat values from string types to Python types
476
471
            client["approved_by_default"] = config.getboolean(
477
472
                client_name, "approved_by_default")
478
 
            client["enabled"] = config.getboolean(client_name,
479
 
                                                  "enabled")
 
473
            client["enabled"] = config.getboolean(client_name, "enabled")
480
474
            
481
475
            client["fingerprint"] = (section["fingerprint"].upper()
482
476
                                     .replace(" ", ""))
502
496
            client["last_approval_request"] = None
503
497
            client["last_checked_ok"] = None
504
498
            client["last_checker_status"] = None
505
 
        
 
499
            if client["enabled"]:
 
500
                client["last_enabled"] = datetime.datetime.utcnow()
 
501
                client["expires"] = (datetime.datetime.utcnow()
 
502
                                     + client["timeout"])
 
503
            else:
 
504
                client["last_enabled"] = None
 
505
                client["expires"] = None
 
506
 
506
507
        return settings
507
508
        
508
509
        
515
516
        for setting, value in settings.iteritems():
516
517
            setattr(self, setting, value)
517
518
        
518
 
        if self.enabled:
519
 
            if not hasattr(self, "last_enabled"):
520
 
                self.last_enabled = datetime.datetime.utcnow()
521
 
            if not hasattr(self, "expires"):
522
 
                self.expires = (datetime.datetime.utcnow()
523
 
                                + self.timeout)
524
 
        else:
525
 
            self.last_enabled = None
526
 
            self.expires = None
527
 
       
528
519
        logger.debug("Creating client %r", self.name)
529
520
        # Uppercase and remove spaces from fingerprint for later
530
521
        # comparison purposes with return value from the fingerprint()
531
522
        # function
532
523
        logger.debug("  Fingerprint: %s", self.fingerprint)
533
 
        self.created = settings.get("created",
534
 
                                    datetime.datetime.utcnow())
 
524
        self.created = settings.get("created", datetime.datetime.utcnow())
535
525
 
536
526
        # attributes specific for this server instance
537
527
        self.checker = None
850
840
            # signatures other than "ay".
851
841
            if prop._dbus_signature != "ay":
852
842
                raise ValueError
853
 
            value = dbus.ByteArray(b''.join(chr(byte)
854
 
                                            for byte in value))
 
843
            value = dbus.ByteArray(''.join(unichr(byte)
 
844
                                           for byte in value))
855
845
        prop(value)
856
846
    
857
847
    @dbus.service.method(dbus.PROPERTIES_IFACE, in_signature="s",
1367
1357
        if value is None:       # get
1368
1358
            return dbus.UInt64(self.timeout_milliseconds())
1369
1359
        self.timeout = datetime.timedelta(0, 0, 0, value)
 
1360
        if getattr(self, "disable_initiator_tag", None) is None:
 
1361
            return
1370
1362
        # Reschedule timeout
1371
 
        if self.enabled:
1372
 
            now = datetime.datetime.utcnow()
1373
 
            time_to_die = timedelta_to_milliseconds(
1374
 
                (self.last_checked_ok + self.timeout) - now)
1375
 
            if time_to_die <= 0:
1376
 
                # The timeout has passed
1377
 
                self.disable()
1378
 
            else:
1379
 
                self.expires = (now +
1380
 
                                datetime.timedelta(milliseconds =
1381
 
                                                   time_to_die))
1382
 
                if (getattr(self, "disable_initiator_tag", None)
1383
 
                    is None):
1384
 
                    return
1385
 
                gobject.source_remove(self.disable_initiator_tag)
1386
 
                self.disable_initiator_tag = (gobject.timeout_add
1387
 
                                              (time_to_die,
1388
 
                                               self.disable))
 
1363
        gobject.source_remove(self.disable_initiator_tag)
 
1364
        self.disable_initiator_tag = None
 
1365
        self.expires = None
 
1366
        time_to_die = timedelta_to_milliseconds((self
 
1367
                                                 .last_checked_ok
 
1368
                                                 + self.timeout)
 
1369
                                                - datetime.datetime
 
1370
                                                .utcnow())
 
1371
        if time_to_die <= 0:
 
1372
            # The timeout has passed
 
1373
            self.disable()
 
1374
        else:
 
1375
            self.expires = (datetime.datetime.utcnow()
 
1376
                            + datetime.timedelta(milliseconds =
 
1377
                                                 time_to_die))
 
1378
            self.disable_initiator_tag = (gobject.timeout_add
 
1379
                                          (time_to_die, self.disable))
1389
1380
    
1390
1381
    # ExtendedTimeout - property
1391
1382
    @dbus_service_property(_interface, signature="t",
2087
2078
                                     stored_state_file)
2088
2079
    
2089
2080
    if debug:
2090
 
        initlogger(debug, logging.DEBUG)
 
2081
        initlogger(logging.DEBUG)
2091
2082
    else:
2092
2083
        if not debuglevel:
2093
 
            initlogger(debug)
 
2084
            initlogger()
2094
2085
        else:
2095
2086
            level = getattr(logging, debuglevel.upper())
2096
 
            initlogger(debug, level)
 
2087
            initlogger(level)
2097
2088
    
2098
2089
    if server_settings["servicename"] != "Mandos":
2099
2090
        syslogger.setFormatter(logging.Formatter
2102
2093
                                % server_settings["servicename"]))
2103
2094
    
2104
2095
    # Parse config file with clients
2105
 
    client_config = configparser.SafeConfigParser(Client
2106
 
                                                  .client_defaults)
 
2096
    client_config = configparser.SafeConfigParser(Client.client_defaults)
2107
2097
    client_config.read(os.path.join(server_settings["configdir"],
2108
2098
                                    "clients.conf"))
2109
2099
    
2166
2156
        os.dup2(null, sys.stdin.fileno())
2167
2157
        if null > 2:
2168
2158
            os.close(null)
 
2159
    else:
 
2160
        # No console logging
 
2161
        logger.removeHandler(console)
2169
2162
    
2170
2163
    # Need to fork before connecting to D-Bus
2171
2164
    if not debug:
2225
2218
                           .format(e))
2226
2219
            if e.errno != errno.ENOENT:
2227
2220
                raise
2228
 
        except EOFError as e:
2229
 
            logger.warning("Could not load persistent state: "
2230
 
                           "EOFError: {0}".format(e))
2231
2221
    
2232
2222
    with PGPEngine() as pgp:
2233
2223
        for client_name, client in clients_data.iteritems():
2271
2261
                        client["expires"] = (datetime.datetime
2272
2262
                                             .utcnow()
2273
2263
                                             + client["timeout"])
2274
 
                        logger.debug("Last checker succeeded,"
2275
 
                                     " keeping {0} enabled"
2276
 
                                     .format(client["name"]))
 
2264
                    
2277
2265
            try:
2278
2266
                client["secret"] = (
2279
2267
                    pgp.decrypt(client["encrypted_secret"],
2288
2276
 
2289
2277
    
2290
2278
    # Add/remove clients based on new changes made to config
2291
 
    for client_name in (set(old_client_settings)
2292
 
                        - set(client_settings)):
 
2279
    for client_name in set(old_client_settings) - set(client_settings):
2293
2280
        del clients_data[client_name]
2294
 
    for client_name in (set(client_settings)
2295
 
                        - set(old_client_settings)):
 
2281
    for client_name in set(client_settings) - set(old_client_settings):
2296
2282
        clients_data[client_name] = client_settings[client_name]
2297
2283
 
2298
2284
    # Create clients all clients
2416
2402
                del client_settings[client.name]["secret"]
2417
2403
        
2418
2404
        try:
2419
 
            tempfd, tempname = tempfile.mkstemp(suffix=".pickle",
2420
 
                                                prefix="clients-",
2421
 
                                                dir=os.path.dirname
2422
 
                                                (stored_state_path))
2423
 
            with os.fdopen(tempfd, "wb") as stored_state:
 
2405
            with os.fdopen(os.open(stored_state_path,
 
2406
                                   os.O_CREAT|os.O_WRONLY|os.O_TRUNC,
 
2407
                                   0600), "wb") as stored_state:
2424
2408
                pickle.dump((clients, client_settings), stored_state)
2425
 
            os.rename(tempname, stored_state_path)
2426
2409
        except (IOError, OSError) as e:
2427
2410
            logger.warning("Could not save persistent state: {0}"
2428
2411
                           .format(e))
2429
 
            if not debug:
2430
 
                try:
2431
 
                    os.remove(tempname)
2432
 
                except NameError:
2433
 
                    pass
2434
 
            if e.errno not in set((errno.ENOENT, errno.EACCES,
2435
 
                                   errno.EEXIST)):
2436
 
                raise e
 
2412
            if e.errno not in (errno.ENOENT, errno.EACCES):
 
2413
                raise
2437
2414
        
2438
2415
        # Delete all clients, and settings from config
2439
2416
        while tcp_server.clients: