/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

  • Committer: Teddy Hogeborn
  • Date: 2010-09-25 23:52:17 UTC
  • Revision ID: teddy@fukt.bsnet.se-20100925235217-4hhqfryz1ste6uw3
* mandos (ClientDBus.__init__): Bug fix: Translate "-" in client names
                                to "_" in D-Bus object paths.
  (MandosServer.handle_ipc): Bug fix: Send only address string to
                             D-Bus signal, not whole tuple.

* mandos-ctl: New options "--approve-by-default", "--deny-by-default",
              "--approval-delay", and "--approval-duration".
* mandos-ctl.xml (SYNOPSIS, OPTIONS): Document new options.

* mandos-monitor (MandosClientWidget.update): Fix spelling.

Show diffs side-by-side

added added

removed removed

Lines of Context:
165
165
                                u' %%(levelname)s: %%(message)s'
166
166
                                % self.name))
167
167
        self.remove()
168
 
        self.add()
 
168
        try:
 
169
            self.add()
 
170
        except dbus.exceptions.DBusException, error:
 
171
            logger.critical(u"DBusException: %s", error)
 
172
            self.cleanup()
 
173
            os._exit(1)
169
174
        self.rename_count += 1
170
175
    def remove(self):
171
176
        """Derived from the Avahi example code"""
235
240
    """A representation of a client host served by this server.
236
241
    
237
242
    Attributes:
238
 
    name:       string; from the config file, used in log messages and
239
 
                        D-Bus identifiers
240
 
    fingerprint: string (40 or 32 hexadecimal digits); used to
241
 
                 uniquely identify the client
242
 
    secret:     bytestring; sent verbatim (over TLS) to client
243
 
    host:       string; available for use by the checker command
244
 
    created:    datetime.datetime(); (UTC) object creation
245
 
    last_enabled: datetime.datetime(); (UTC)
246
 
    enabled:    bool()
247
 
    last_checked_ok: datetime.datetime(); (UTC) or None
248
 
    timeout:    datetime.timedelta(); How long from last_checked_ok
249
 
                                      until this client is disabled
250
 
    interval:   datetime.timedelta(); How often to start a new checker
251
 
    disable_hook:  If set, called by disable() as disable_hook(self)
 
243
    _approved:   bool(); 'None' if not yet approved/disapproved
 
244
    approval_delay: datetime.timedelta(); Time to wait for approval
 
245
    approval_duration: datetime.timedelta(); Duration of one approval
252
246
    checker:    subprocess.Popen(); a running checker process used
253
247
                                    to see if the client lives.
254
248
                                    'None' if no process is running.
255
 
    checker_initiator_tag: a gobject event source tag, or None
256
 
    disable_initiator_tag: - '' -
257
249
    checker_callback_tag:  - '' -
258
 
    checker_command: string; External command which is run to check if
259
 
                     client lives.  %() expansions are done at
 
250
    checker_command: string; External command which is run to check
 
251
                     if client lives.  %() expansions are done at
260
252
                     runtime with vars(self) as dict, so that for
261
253
                     instance %(name)s can be used in the command.
 
254
    checker_initiator_tag: a gobject event source tag, or None
 
255
    created:    datetime.datetime(); (UTC) object creation
262
256
    current_checker_command: string; current running checker_command
263
 
    approved_delay: datetime.timedelta(); Time to wait for approval
264
 
    _approved:   bool(); 'None' if not yet approved/disapproved
265
 
    approved_duration: datetime.timedelta(); Duration of one approval
 
257
    disable_hook:  If set, called by disable() as disable_hook(self)
 
258
    disable_initiator_tag: - '' -
 
259
    enabled:    bool()
 
260
    fingerprint: string (40 or 32 hexadecimal digits); used to
 
261
                 uniquely identify the client
 
262
    host:       string; available for use by the checker command
 
263
    interval:   datetime.timedelta(); How often to start a new checker
 
264
    last_checked_ok: datetime.datetime(); (UTC) or None
 
265
    last_enabled: datetime.datetime(); (UTC)
 
266
    name:       string; from the config file, used in log messages and
 
267
                        D-Bus identifiers
 
268
    secret:     bytestring; sent verbatim (over TLS) to client
 
269
    timeout:    datetime.timedelta(); How long from last_checked_ok
 
270
                                      until this client is disabled
 
271
    runtime_expansions: Allowed attributes for runtime expansion.
266
272
    """
267
273
    
 
274
    runtime_expansions = (u"approval_delay", u"approval_duration",
 
275
                          u"created", u"enabled", u"fingerprint",
 
276
                          u"host", u"interval", u"last_checked_ok",
 
277
                          u"last_enabled", u"name", u"timeout")
 
278
    
268
279
    @staticmethod
269
280
    def _timedelta_to_milliseconds(td):
270
281
        "Convert a datetime.timedelta() to milliseconds"
280
291
        "Return the 'interval' attribute in milliseconds"
281
292
        return self._timedelta_to_milliseconds(self.interval)
282
293
 
283
 
    def approved_delay_milliseconds(self):
284
 
        return self._timedelta_to_milliseconds(self.approved_delay)
 
294
    def approval_delay_milliseconds(self):
 
295
        return self._timedelta_to_milliseconds(self.approval_delay)
285
296
    
286
297
    def __init__(self, name = None, disable_hook=None, config=None):
287
298
        """Note: the 'checker' key in 'config' sets the
326
337
        self.approved_by_default = config.get(u"approved_by_default",
327
338
                                              True)
328
339
        self.approvals_pending = 0
329
 
        self.approved_delay = string_to_delta(
330
 
            config[u"approved_delay"])
331
 
        self.approved_duration = string_to_delta(
332
 
            config[u"approved_duration"])
 
340
        self.approval_delay = string_to_delta(
 
341
            config[u"approval_delay"])
 
342
        self.approval_duration = string_to_delta(
 
343
            config[u"approval_duration"])
333
344
        self.changedstate = multiprocessing_manager.Condition(multiprocessing_manager.Lock())
334
345
    
335
346
    def send_changedstate(self):
445
456
                command = self.checker_command % self.host
446
457
            except TypeError:
447
458
                # Escape attributes for the shell
448
 
                escaped_attrs = dict((key,
449
 
                                      re.escape(unicode(str(val),
450
 
                                                        errors=
451
 
                                                        u'replace')))
452
 
                                     for key, val in
453
 
                                     vars(self).iteritems())
 
459
                escaped_attrs = dict(
 
460
                    (attr,
 
461
                     re.escape(unicode(str(getattr(self, attr, u"")),
 
462
                                       errors=
 
463
                                       u'replace')))
 
464
                    for attr in
 
465
                    self.runtime_expansions)
 
466
 
454
467
                try:
455
468
                    command = self.checker_command % escaped_attrs
456
469
                except TypeError, error:
698
711
    dbus_object_path: dbus.ObjectPath
699
712
    bus: dbus.SystemBus()
700
713
    """
 
714
    
 
715
    runtime_expansions = (Client.runtime_expansions
 
716
                          + (u"dbus_object_path",))
 
717
    
701
718
    # dbus.service.Object doesn't use super(), so we can't either.
702
719
    
703
720
    def __init__(self, bus = None, *args, **kwargs):
706
723
        Client.__init__(self, *args, **kwargs)
707
724
        # Only now, when this client is initialized, can it show up on
708
725
        # the D-Bus
 
726
        client_object_name = unicode(self.name).translate(
 
727
            {ord(u"."): ord(u"_"),
 
728
             ord(u"-"): ord(u"_")})
709
729
        self.dbus_object_path = (dbus.ObjectPath
710
 
                                 (u"/clients/"
711
 
                                  + self.name.replace(u".", u"_")))
 
730
                                 (u"/clients/" + client_object_name))
712
731
        DBusObjectWithProperties.__init__(self, self.bus,
713
732
                                          self.dbus_object_path)
714
 
 
 
733
        
715
734
    def _get_approvals_pending(self):
716
735
        return self._approvals_pending
717
736
    def _set_approvals_pending(self, value):
721
740
        if (hasattr(self, "dbus_object_path")
722
741
            and bval is not bool(old_value)):
723
742
            dbus_bool = dbus.Boolean(bval, variant_level=1)
724
 
            self.PropertyChanged(dbus.String(u"approved_pending"),
 
743
            self.PropertyChanged(dbus.String(u"ApprovalPending"),
725
744
                                 dbus_bool)
726
745
 
727
746
    approvals_pending = property(_get_approvals_pending,
739
758
        r = Client.enable(self)
740
759
        if oldstate != self.enabled:
741
760
            # Emit D-Bus signals
742
 
            self.PropertyChanged(dbus.String(u"enabled"),
 
761
            self.PropertyChanged(dbus.String(u"Enabled"),
743
762
                                 dbus.Boolean(True, variant_level=1))
744
763
            self.PropertyChanged(
745
 
                dbus.String(u"last_enabled"),
 
764
                dbus.String(u"LastEnabled"),
746
765
                self._datetime_to_dbus(self.last_enabled,
747
766
                                       variant_level=1))
748
767
        return r
752
771
        r = Client.disable(self, quiet=quiet)
753
772
        if not quiet and oldstate != self.enabled:
754
773
            # Emit D-Bus signal
755
 
            self.PropertyChanged(dbus.String(u"enabled"),
 
774
            self.PropertyChanged(dbus.String(u"Enabled"),
756
775
                                 dbus.Boolean(False, variant_level=1))
757
776
        return r
758
777
    
770
789
        self.checker_callback_tag = None
771
790
        self.checker = None
772
791
        # Emit D-Bus signal
773
 
        self.PropertyChanged(dbus.String(u"checker_running"),
 
792
        self.PropertyChanged(dbus.String(u"CheckerRunning"),
774
793
                             dbus.Boolean(False, variant_level=1))
775
794
        if os.WIFEXITED(condition):
776
795
            exitstatus = os.WEXITSTATUS(condition)
791
810
        r = Client.checked_ok(self, *args, **kwargs)
792
811
        # Emit D-Bus signal
793
812
        self.PropertyChanged(
794
 
            dbus.String(u"last_checked_ok"),
 
813
            dbus.String(u"LastCheckedOK"),
795
814
            (self._datetime_to_dbus(self.last_checked_ok,
796
815
                                    variant_level=1)))
797
816
        return r
809
828
            # Emit D-Bus signal
810
829
            self.CheckerStarted(self.current_checker_command)
811
830
            self.PropertyChanged(
812
 
                dbus.String(u"checker_running"),
 
831
                dbus.String(u"CheckerRunning"),
813
832
                dbus.Boolean(True, variant_level=1))
814
833
        return r
815
834
    
818
837
        r = Client.stop_checker(self, *args, **kwargs)
819
838
        if (old_checker is not None
820
839
            and getattr(self, u"checker", None) is None):
821
 
            self.PropertyChanged(dbus.String(u"checker_running"),
 
840
            self.PropertyChanged(dbus.String(u"CheckerRunning"),
822
841
                                 dbus.Boolean(False, variant_level=1))
823
842
        return r
824
843
 
829
848
    def approve(self, value=True):
830
849
        self.send_changedstate()
831
850
        self._approved = value
832
 
        gobject.timeout_add(self._timedelta_to_milliseconds(self.approved_duration),
 
851
        gobject.timeout_add(self._timedelta_to_milliseconds
 
852
                            (self.approval_duration),
833
853
                            self._reset_approved)
834
854
    
835
855
    
872
892
        pass
873
893
    
874
894
    # NeedApproval - signal
875
 
    @dbus.service.signal(_interface, signature=u"db")
 
895
    @dbus.service.signal(_interface, signature=u"tb")
876
896
    def NeedApproval(self, timeout, default):
877
897
        "D-Bus signal"
878
898
        pass
914
934
    
915
935
    ## Properties
916
936
    
917
 
    # approved_pending - property
 
937
    # ApprovalPending - property
918
938
    @dbus_service_property(_interface, signature=u"b", access=u"read")
919
 
    def approved_pending_dbus_property(self):
 
939
    def ApprovalPending_dbus_property(self):
920
940
        return dbus.Boolean(bool(self.approvals_pending))
921
941
    
922
 
    # approved_by_default - property
 
942
    # ApprovedByDefault - property
923
943
    @dbus_service_property(_interface, signature=u"b",
924
944
                           access=u"readwrite")
925
 
    def approved_by_default_dbus_property(self):
926
 
        return dbus.Boolean(self.approved_by_default)
927
 
    
928
 
    # approved_delay - property
929
 
    @dbus_service_property(_interface, signature=u"t",
930
 
                           access=u"readwrite")
931
 
    def approved_delay_dbus_property(self):
932
 
        return dbus.UInt64(self.approved_delay_milliseconds())
933
 
    
934
 
    # approved_duration - property
935
 
    @dbus_service_property(_interface, signature=u"t",
936
 
                           access=u"readwrite")
937
 
    def approved_duration_dbus_property(self):
938
 
        return dbus.UInt64(self._timedelta_to_milliseconds(
939
 
                self.approved_duration))
940
 
    
941
 
    # name - property
 
945
    def ApprovedByDefault_dbus_property(self, value=None):
 
946
        if value is None:       # get
 
947
            return dbus.Boolean(self.approved_by_default)
 
948
        self.approved_by_default = bool(value)
 
949
        # Emit D-Bus signal
 
950
        self.PropertyChanged(dbus.String(u"ApprovedByDefault"),
 
951
                             dbus.Boolean(value, variant_level=1))
 
952
    
 
953
    # ApprovalDelay - property
 
954
    @dbus_service_property(_interface, signature=u"t",
 
955
                           access=u"readwrite")
 
956
    def ApprovalDelay_dbus_property(self, value=None):
 
957
        if value is None:       # get
 
958
            return dbus.UInt64(self.approval_delay_milliseconds())
 
959
        self.approval_delay = datetime.timedelta(0, 0, 0, value)
 
960
        # Emit D-Bus signal
 
961
        self.PropertyChanged(dbus.String(u"ApprovalDelay"),
 
962
                             dbus.UInt64(value, variant_level=1))
 
963
    
 
964
    # ApprovalDuration - property
 
965
    @dbus_service_property(_interface, signature=u"t",
 
966
                           access=u"readwrite")
 
967
    def ApprovalDuration_dbus_property(self, value=None):
 
968
        if value is None:       # get
 
969
            return dbus.UInt64(self._timedelta_to_milliseconds(
 
970
                    self.approval_duration))
 
971
        self.approval_duration = datetime.timedelta(0, 0, 0, value)
 
972
        # Emit D-Bus signal
 
973
        self.PropertyChanged(dbus.String(u"ApprovalDuration"),
 
974
                             dbus.UInt64(value, variant_level=1))
 
975
    
 
976
    # Name - property
942
977
    @dbus_service_property(_interface, signature=u"s", access=u"read")
943
 
    def name_dbus_property(self):
 
978
    def Name_dbus_property(self):
944
979
        return dbus.String(self.name)
945
980
    
946
 
    # fingerprint - property
 
981
    # Fingerprint - property
947
982
    @dbus_service_property(_interface, signature=u"s", access=u"read")
948
 
    def fingerprint_dbus_property(self):
 
983
    def Fingerprint_dbus_property(self):
949
984
        return dbus.String(self.fingerprint)
950
985
    
951
 
    # host - property
 
986
    # Host - property
952
987
    @dbus_service_property(_interface, signature=u"s",
953
988
                           access=u"readwrite")
954
 
    def host_dbus_property(self, value=None):
 
989
    def Host_dbus_property(self, value=None):
955
990
        if value is None:       # get
956
991
            return dbus.String(self.host)
957
992
        self.host = value
958
993
        # Emit D-Bus signal
959
 
        self.PropertyChanged(dbus.String(u"host"),
 
994
        self.PropertyChanged(dbus.String(u"Host"),
960
995
                             dbus.String(value, variant_level=1))
961
996
    
962
 
    # created - property
 
997
    # Created - property
963
998
    @dbus_service_property(_interface, signature=u"s", access=u"read")
964
 
    def created_dbus_property(self):
 
999
    def Created_dbus_property(self):
965
1000
        return dbus.String(self._datetime_to_dbus(self.created))
966
1001
    
967
 
    # last_enabled - property
 
1002
    # LastEnabled - property
968
1003
    @dbus_service_property(_interface, signature=u"s", access=u"read")
969
 
    def last_enabled_dbus_property(self):
 
1004
    def LastEnabled_dbus_property(self):
970
1005
        if self.last_enabled is None:
971
1006
            return dbus.String(u"")
972
1007
        return dbus.String(self._datetime_to_dbus(self.last_enabled))
973
1008
    
974
 
    # enabled - property
 
1009
    # Enabled - property
975
1010
    @dbus_service_property(_interface, signature=u"b",
976
1011
                           access=u"readwrite")
977
 
    def enabled_dbus_property(self, value=None):
 
1012
    def Enabled_dbus_property(self, value=None):
978
1013
        if value is None:       # get
979
1014
            return dbus.Boolean(self.enabled)
980
1015
        if value:
982
1017
        else:
983
1018
            self.disable()
984
1019
    
985
 
    # last_checked_ok - property
 
1020
    # LastCheckedOK - property
986
1021
    @dbus_service_property(_interface, signature=u"s",
987
1022
                           access=u"readwrite")
988
 
    def last_checked_ok_dbus_property(self, value=None):
 
1023
    def LastCheckedOK_dbus_property(self, value=None):
989
1024
        if value is not None:
990
1025
            self.checked_ok()
991
1026
            return
994
1029
        return dbus.String(self._datetime_to_dbus(self
995
1030
                                                  .last_checked_ok))
996
1031
    
997
 
    # timeout - property
 
1032
    # Timeout - property
998
1033
    @dbus_service_property(_interface, signature=u"t",
999
1034
                           access=u"readwrite")
1000
 
    def timeout_dbus_property(self, value=None):
 
1035
    def Timeout_dbus_property(self, value=None):
1001
1036
        if value is None:       # get
1002
1037
            return dbus.UInt64(self.timeout_milliseconds())
1003
1038
        self.timeout = datetime.timedelta(0, 0, 0, value)
1004
1039
        # Emit D-Bus signal
1005
 
        self.PropertyChanged(dbus.String(u"timeout"),
 
1040
        self.PropertyChanged(dbus.String(u"Timeout"),
1006
1041
                             dbus.UInt64(value, variant_level=1))
1007
1042
        if getattr(self, u"disable_initiator_tag", None) is None:
1008
1043
            return
1022
1057
            self.disable_initiator_tag = (gobject.timeout_add
1023
1058
                                          (time_to_die, self.disable))
1024
1059
    
1025
 
    # interval - property
 
1060
    # Interval - property
1026
1061
    @dbus_service_property(_interface, signature=u"t",
1027
1062
                           access=u"readwrite")
1028
 
    def interval_dbus_property(self, value=None):
 
1063
    def Interval_dbus_property(self, value=None):
1029
1064
        if value is None:       # get
1030
1065
            return dbus.UInt64(self.interval_milliseconds())
1031
1066
        self.interval = datetime.timedelta(0, 0, 0, value)
1032
1067
        # Emit D-Bus signal
1033
 
        self.PropertyChanged(dbus.String(u"interval"),
 
1068
        self.PropertyChanged(dbus.String(u"Interval"),
1034
1069
                             dbus.UInt64(value, variant_level=1))
1035
1070
        if getattr(self, u"checker_initiator_tag", None) is None:
1036
1071
            return
1040
1075
                                      (value, self.start_checker))
1041
1076
        self.start_checker()    # Start one now, too
1042
1077
 
1043
 
    # checker - property
 
1078
    # Checker - property
1044
1079
    @dbus_service_property(_interface, signature=u"s",
1045
1080
                           access=u"readwrite")
1046
 
    def checker_dbus_property(self, value=None):
 
1081
    def Checker_dbus_property(self, value=None):
1047
1082
        if value is None:       # get
1048
1083
            return dbus.String(self.checker_command)
1049
1084
        self.checker_command = value
1050
1085
        # Emit D-Bus signal
1051
 
        self.PropertyChanged(dbus.String(u"checker"),
 
1086
        self.PropertyChanged(dbus.String(u"Checker"),
1052
1087
                             dbus.String(self.checker_command,
1053
1088
                                         variant_level=1))
1054
1089
    
1055
 
    # checker_running - property
 
1090
    # CheckerRunning - property
1056
1091
    @dbus_service_property(_interface, signature=u"b",
1057
1092
                           access=u"readwrite")
1058
 
    def checker_running_dbus_property(self, value=None):
 
1093
    def CheckerRunning_dbus_property(self, value=None):
1059
1094
        if value is None:       # get
1060
1095
            return dbus.Boolean(self.checker is not None)
1061
1096
        if value:
1063
1098
        else:
1064
1099
            self.stop_checker()
1065
1100
    
1066
 
    # object_path - property
 
1101
    # ObjectPath - property
1067
1102
    @dbus_service_property(_interface, signature=u"o", access=u"read")
1068
 
    def object_path_dbus_property(self):
 
1103
    def ObjectPath_dbus_property(self):
1069
1104
        return self.dbus_object_path # is already a dbus.ObjectPath
1070
1105
    
1071
 
    # secret = property
 
1106
    # Secret = property
1072
1107
    @dbus_service_property(_interface, signature=u"ay",
1073
1108
                           access=u"write", byte_arrays=True)
1074
 
    def secret_dbus_property(self, value):
 
1109
    def Secret_dbus_property(self, value):
1075
1110
        self.secret = str(value)
1076
1111
    
1077
1112
    del _interface
1175
1210
                except KeyError:
1176
1211
                    return
1177
1212
                
1178
 
                if client.approved_delay:
1179
 
                    delay = client.approved_delay
 
1213
                if client.approval_delay:
 
1214
                    delay = client.approval_delay
1180
1215
                    client.approvals_pending += 1
1181
1216
                    approval_required = True
1182
1217
                
1189
1224
                            client.Rejected("Disabled")                    
1190
1225
                        return
1191
1226
                    
1192
 
                    if client._approved or not client.approved_delay:
 
1227
                    if client._approved or not client.approval_delay:
1193
1228
                        #We are approved or approval is disabled
1194
1229
                        break
1195
1230
                    elif client._approved is None:
1196
 
                        logger.info(u"Client %s need approval",
 
1231
                        logger.info(u"Client %s needs approval",
1197
1232
                                    client.name)
1198
1233
                        if self.server.use_dbus:
1199
1234
                            # Emit D-Bus signal
1200
1235
                            client.NeedApproval(
1201
 
                                client.approved_delay_milliseconds(),
 
1236
                                client.approval_delay_milliseconds(),
1202
1237
                                client.approved_by_default)
1203
1238
                    else:
1204
1239
                        logger.warning(u"Client %s was not approved",
1205
1240
                                       client.name)
1206
1241
                        if self.server.use_dbus:
1207
1242
                            # Emit D-Bus signal
1208
 
                            client.Rejected("Disapproved")
 
1243
                            client.Rejected("Denied")
1209
1244
                        return
1210
1245
                    
1211
1246
                    #wait until timeout or approved
1222
1257
                                           client.name)
1223
1258
                            if self.server.use_dbus:
1224
1259
                                # Emit D-Bus signal
1225
 
                                client.Rejected("Time out")
 
1260
                                client.Rejected("Approval timed out")
1226
1261
                            return
1227
1262
                        else:
1228
1263
                            break
1254
1289
                try:
1255
1290
                    session.bye()
1256
1291
                except (gnutls.errors.GNUTLSError), error:
1257
 
                    logger.warning("gnutls bye failed")
 
1292
                    logger.warning("GnuTLS bye failed")
1258
1293
    
1259
1294
    @staticmethod
1260
1295
    def peer_certificate(session):
1466
1501
                                       for cond, name in
1467
1502
                                       condition_names.iteritems()
1468
1503
                                       if cond & condition)
1469
 
        logger.debug(u"Handling IPC: FD = %d, condition = %s", source,
1470
 
                     conditions_string)
1471
 
 
1472
1504
        # error or the other end of multiprocessing.Pipe has closed
1473
1505
        if condition & (gobject.IO_ERR | condition & gobject.IO_HUP):
1474
1506
            return False
1475
1507
        
1476
1508
        # Read a request from the child
1477
1509
        request = parent_pipe.recv()
1478
 
        logger.debug(u"IPC request: %s", repr(request))
1479
1510
        command = request[0]
1480
1511
        
1481
1512
        if command == 'init':
1491
1522
                               u"dress: %s", fpr, address)
1492
1523
                if self.use_dbus:
1493
1524
                    # Emit D-Bus signal
1494
 
                    mandos_dbus_service.ClientNotFound(fpr, address)
 
1525
                    mandos_dbus_service.ClientNotFound(fpr, address[0])
1495
1526
                parent_pipe.send(False)
1496
1527
                return False
1497
1528
            
1715
1746
                        u"interval": u"5m",
1716
1747
                        u"checker": u"fping -q -- %%(host)s",
1717
1748
                        u"host": u"",
1718
 
                        u"approved_delay": u"0s",
1719
 
                        u"approved_duration": u"1s",
 
1749
                        u"approval_delay": u"0s",
 
1750
                        u"approval_duration": u"1s",
1720
1751
                        }
1721
1752
    client_config = configparser.SafeConfigParser(client_defaults)
1722
1753
    client_config.read(os.path.join(server_settings[u"configdir"],
1728
1759
    tcp_server = MandosServer((server_settings[u"address"],
1729
1760
                               server_settings[u"port"]),
1730
1761
                              ClientHandler,
1731
 
                              interface=server_settings[u"interface"],
 
1762
                              interface=(server_settings[u"interface"]
 
1763
                                         or None),
1732
1764
                              use_ipv6=use_ipv6,
1733
1765
                              gnutls_priority=
1734
1766
                              server_settings[u"priority"],
1735
1767
                              use_dbus=use_dbus)
1736
 
    pidfilename = u"/var/run/mandos.pid"
1737
 
    try:
1738
 
        pidfile = open(pidfilename, u"w")
1739
 
    except IOError:
1740
 
        logger.error(u"Could not open file %r", pidfilename)
 
1768
    if not debug:
 
1769
        pidfilename = u"/var/run/mandos.pid"
 
1770
        try:
 
1771
            pidfile = open(pidfilename, u"w")
 
1772
        except IOError:
 
1773
            logger.error(u"Could not open file %r", pidfilename)
1741
1774
    
1742
1775
    try:
1743
1776
        uid = pwd.getpwnam(u"_mandos").pw_uid
1760
1793
        if error[0] != errno.EPERM:
1761
1794
            raise error
1762
1795
    
1763
 
    # Enable all possible GnuTLS debugging
1764
 
 
1765
 
 
1766
1796
    if not debug and not debuglevel:
1767
1797
        syslogger.setLevel(logging.WARNING)
1768
1798
        console.setLevel(logging.WARNING)
1772
1802
        console.setLevel(level)
1773
1803
 
1774
1804
    if debug:
 
1805
        # Enable all possible GnuTLS debugging
 
1806
        
1775
1807
        # "Use a log level over 10 to enable all debugging options."
1776
1808
        # - GnuTLS manual
1777
1809
        gnutls.library.functions.gnutls_global_set_log_level(11)
1782
1814
        
1783
1815
        (gnutls.library.functions
1784
1816
         .gnutls_global_set_log_function(debug_gnutls))
1785
 
 
 
1817
        
1786
1818
        # Redirect stdin so all checkers get /dev/null
1787
1819
        null = os.open(os.path.devnull, os.O_NOCTTY | os.O_RDWR)
1788
1820
        os.dup2(null, sys.stdin.fileno())
1791
1823
    else:
1792
1824
        # No console logging
1793
1825
        logger.removeHandler(console)
1794
 
 
 
1826
    
1795
1827
    
1796
1828
    global main_loop
1797
1829
    # From the Avahi example code
1846
1878
    if not tcp_server.clients:
1847
1879
        logger.warning(u"No clients defined")
1848
1880
        
1849
 
    try:
1850
 
        with pidfile:
1851
 
            pid = os.getpid()
1852
 
            pidfile.write(str(pid) + "\n")
1853
 
        del pidfile
1854
 
    except IOError:
1855
 
        logger.error(u"Could not write to file %r with PID %d",
1856
 
                     pidfilename, pid)
1857
 
    except NameError:
1858
 
        # "pidfile" was never created
1859
 
        pass
1860
 
    del pidfilename
1861
 
    
1862
1881
    if not debug:
 
1882
        try:
 
1883
            with pidfile:
 
1884
                pid = os.getpid()
 
1885
                pidfile.write(str(pid) + "\n")
 
1886
            del pidfile
 
1887
        except IOError:
 
1888
            logger.error(u"Could not write to file %r with PID %d",
 
1889
                         pidfilename, pid)
 
1890
        except NameError:
 
1891
            # "pidfile" was never created
 
1892
            pass
 
1893
        del pidfilename
 
1894
        
1863
1895
        signal.signal(signal.SIGINT, signal.SIG_IGN)
 
1896
 
1864
1897
    signal.signal(signal.SIGHUP, lambda signum, frame: sys.exit())
1865
1898
    signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit())
1866
1899