/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: 2019-08-30 21:10:13 UTC
  • Revision ID: teddy@recompile.se-20190830211013-7bt0qseq97dpt7oy
Update Python 3 compatibility

* mandos (rfc3339_duration_to_delta): Change doctest string to not
                                      depend on exact repr() string
                                      representation of values and
                                      instead do value comparisons.
  (string_to_delta): - '' -

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
#!/usr/bin/python
2
 
# -*- mode: python; coding: utf-8 -*-
 
2
# -*- mode: python; after-save-hook: (lambda () (let ((command (if (fboundp 'file-local-name) (file-local-name (buffer-file-name)) (or (file-remote-p (buffer-file-name) 'localname) (buffer-file-name))))) (if (= (progn (if (get-buffer "*Test*") (kill-buffer "*Test*")) (process-file-shell-command (format "%s --check" (shell-quote-argument command)) nil "*Test*")) 0) (let ((w (get-buffer-window "*Test*"))) (if w (delete-window w))) (progn (with-current-buffer "*Test*" (compilation-mode)) (display-buffer "*Test*" '(display-buffer-in-side-window)))))); coding: utf-8 -*-
3
3
#
4
4
# Mandos server - give out binary blobs to connecting clients.
5
5
#
77
77
import itertools
78
78
import collections
79
79
import codecs
 
80
import unittest
80
81
 
81
82
import dbus
82
83
import dbus.service
91
92
if sys.version_info.major == 2:
92
93
    __metaclass__ = type
93
94
 
 
95
# Show warnings by default
 
96
if not sys.warnoptions:
 
97
    import warnings
 
98
    warnings.simplefilter("default")
 
99
 
94
100
# Try to find the value of SO_BINDTODEVICE:
95
101
try:
96
102
    # This is where SO_BINDTODEVICE is in Python 3.3 (or 3.4?) and
122
128
if sys.version_info < (3, 2):
123
129
    configparser.Configparser = configparser.SafeConfigParser
124
130
 
125
 
version = "1.8.7"
 
131
version = "1.8.8"
126
132
stored_state_file = "clients.pickle"
127
133
 
128
134
logger = logging.getLogger()
 
135
logging.captureWarnings(True)   # Show warnings via the logging system
129
136
syslogger = None
130
137
 
131
138
try:
1143
1150
                kwargs=popen_args)
1144
1151
            self.checker.start()
1145
1152
            self.checker_callback_tag = GLib.io_add_watch(
1146
 
                pipe[0].fileno(), GLib.IO_IN,
 
1153
                GLib.IOChannel.unix_new(pipe[0].fileno()),
 
1154
                GLib.PRIORITY_DEFAULT, GLib.IO_IN,
1147
1155
                self.checker_callback, pipe[0], command)
1148
1156
        # Re-run this periodically if run by GLib.timeout_add
1149
1157
        return True
2673
2681
    def add_pipe(self, parent_pipe, proc):
2674
2682
        # Call "handle_ipc" for both data and EOF events
2675
2683
        GLib.io_add_watch(
2676
 
            parent_pipe.fileno(),
2677
 
            GLib.IO_IN | GLib.IO_HUP,
 
2684
            GLib.IOChannel.unix_new(parent_pipe.fileno()),
 
2685
            GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2678
2686
            functools.partial(self.handle_ipc,
2679
2687
                              parent_pipe=parent_pipe,
2680
2688
                              proc=proc))
2718
2726
                return False
2719
2727
 
2720
2728
            GLib.io_add_watch(
2721
 
                parent_pipe.fileno(),
2722
 
                GLib.IO_IN | GLib.IO_HUP,
 
2729
                GLib.IOChannel.unix_new(parent_pipe.fileno()),
 
2730
                GLib.PRIORITY_DEFAULT, GLib.IO_IN | GLib.IO_HUP,
2723
2731
                functools.partial(self.handle_ipc,
2724
2732
                                  parent_pipe=parent_pipe,
2725
2733
                                  proc=proc,
2757
2765
def rfc3339_duration_to_delta(duration):
2758
2766
    """Parse an RFC 3339 "duration" and return a datetime.timedelta
2759
2767
 
2760
 
    >>> rfc3339_duration_to_delta("P7D")
2761
 
    datetime.timedelta(7)
2762
 
    >>> rfc3339_duration_to_delta("PT60S")
2763
 
    datetime.timedelta(0, 60)
2764
 
    >>> rfc3339_duration_to_delta("PT60M")
2765
 
    datetime.timedelta(0, 3600)
2766
 
    >>> rfc3339_duration_to_delta("PT24H")
2767
 
    datetime.timedelta(1)
2768
 
    >>> rfc3339_duration_to_delta("P1W")
2769
 
    datetime.timedelta(7)
2770
 
    >>> rfc3339_duration_to_delta("PT5M30S")
2771
 
    datetime.timedelta(0, 330)
2772
 
    >>> rfc3339_duration_to_delta("P1DT3M20S")
2773
 
    datetime.timedelta(1, 200)
 
2768
    >>> rfc3339_duration_to_delta("P7D") == datetime.timedelta(7)
 
2769
    True
 
2770
    >>> rfc3339_duration_to_delta("PT60S") == datetime.timedelta(0, 60)
 
2771
    True
 
2772
    >>> rfc3339_duration_to_delta("PT60M") == datetime.timedelta(0, 3600)
 
2773
    True
 
2774
    >>> rfc3339_duration_to_delta("PT24H") == datetime.timedelta(1)
 
2775
    True
 
2776
    >>> rfc3339_duration_to_delta("P1W") == datetime.timedelta(7)
 
2777
    True
 
2778
    >>> rfc3339_duration_to_delta("PT5M30S") == datetime.timedelta(0, 330)
 
2779
    True
 
2780
    >>> rfc3339_duration_to_delta("P1DT3M20S") == datetime.timedelta(1, 200)
 
2781
    True
2774
2782
    """
2775
2783
 
2776
2784
    # Parsing an RFC 3339 duration with regular expressions is not
2856
2864
def string_to_delta(interval):
2857
2865
    """Parse a string and return a datetime.timedelta
2858
2866
 
2859
 
    >>> string_to_delta('7d')
2860
 
    datetime.timedelta(7)
2861
 
    >>> string_to_delta('60s')
2862
 
    datetime.timedelta(0, 60)
2863
 
    >>> string_to_delta('60m')
2864
 
    datetime.timedelta(0, 3600)
2865
 
    >>> string_to_delta('24h')
2866
 
    datetime.timedelta(1)
2867
 
    >>> string_to_delta('1w')
2868
 
    datetime.timedelta(7)
2869
 
    >>> string_to_delta('5m 30s')
2870
 
    datetime.timedelta(0, 330)
 
2867
    >>> string_to_delta('7d') == datetime.timedelta(7)
 
2868
    True
 
2869
    >>> string_to_delta('60s') == datetime.timedelta(0, 60)
 
2870
    True
 
2871
    >>> string_to_delta('60m') == datetime.timedelta(0, 3600)
 
2872
    True
 
2873
    >>> string_to_delta('24h') == datetime.timedelta(1)
 
2874
    True
 
2875
    >>> string_to_delta('1w') == datetime.timedelta(7)
 
2876
    True
 
2877
    >>> string_to_delta('5m 30s') == datetime.timedelta(0, 330)
 
2878
    True
2871
2879
    """
2872
2880
 
2873
2881
    try:
2975
2983
 
2976
2984
    options = parser.parse_args()
2977
2985
 
2978
 
    if options.check:
2979
 
        import doctest
2980
 
        fail_count, test_count = doctest.testmod()
2981
 
        sys.exit(os.EX_OK if fail_count == 0 else 1)
2982
 
 
2983
2986
    # Default values for config file for server-global settings
2984
2987
    if gnutls.has_rawpk:
2985
2988
        priority = ("SECURE128:!CTYPE-X.509:+CTYPE-RAWPK:!RSA"
3600
3603
                sys.exit(1)
3601
3604
            # End of Avahi example code
3602
3605
 
3603
 
        GLib.io_add_watch(tcp_server.fileno(), GLib.IO_IN,
3604
 
                          lambda *args, **kwargs:
3605
 
                          (tcp_server.handle_request
3606
 
                           (*args[2:], **kwargs) or True))
 
3606
        GLib.io_add_watch(
 
3607
            GLib.IOChannel.unix_new(tcp_server.fileno()),
 
3608
            GLib.PRIORITY_DEFAULT, GLib.IO_IN,
 
3609
            lambda *args, **kwargs: (tcp_server.handle_request
 
3610
                                     (*args[2:], **kwargs) or True))
3607
3611
 
3608
3612
        logger.debug("Starting main loop")
3609
3613
        main_loop.run()
3619
3623
    # Must run before the D-Bus bus name gets deregistered
3620
3624
    cleanup()
3621
3625
 
 
3626
 
 
3627
def should_only_run_tests():
 
3628
    parser = argparse.ArgumentParser(add_help=False)
 
3629
    parser.add_argument("--check", action='store_true')
 
3630
    args, unknown_args = parser.parse_known_args()
 
3631
    run_tests = args.check
 
3632
    if run_tests:
 
3633
        # Remove --check argument from sys.argv
 
3634
        sys.argv[1:] = unknown_args
 
3635
    return run_tests
 
3636
 
 
3637
# Add all tests from doctest strings
 
3638
def load_tests(loader, tests, none):
 
3639
    import doctest
 
3640
    tests.addTests(doctest.DocTestSuite())
 
3641
    return tests
3622
3642
 
3623
3643
if __name__ == '__main__':
3624
 
    main()
 
3644
    try:
 
3645
        if should_only_run_tests():
 
3646
            # Call using ./mandos --check [--verbose]
 
3647
            unittest.main()
 
3648
        else:
 
3649
            main()
 
3650
    finally:
 
3651
        logging.shutdown()