506
535
# Pretend that we have a GnuTLS module
507
class GnuTLS(object):
508
"""This isn't so much a class as it is a module-like namespace.
509
It is instantiated once, and simulates having a GnuTLS module."""
537
"""This isn't so much a class as it is a module-like namespace."""
511
539
library = ctypes.util.find_library("gnutls")
512
540
if library is None:
513
541
library = ctypes.util.find_library("gnutls-deb0")
514
542
_library = ctypes.cdll.LoadLibrary(library)
516
_need_version = b"3.3.0"
517
_tls_rawpk_version = b"3.6.6"
520
# Need to use "self" here, since this method is called before
521
# the assignment to the "gnutls" global variable happens.
522
if self.check_version(self._need_version) is None:
523
raise self.Error("Needs GnuTLS {} or later"
524
.format(self._need_version))
526
545
# Unless otherwise indicated, the constants and types below are
527
546
# all from the gnutls/gnutls.h C header file.
571
590
class Error(Exception):
572
# We need to use the class name "GnuTLS" here, since this
573
# exception might be raised from within GnuTLS.__init__,
574
# which is called before the assignment to the "gnutls"
575
# global variable has happened.
576
591
def __init__(self, message=None, code=None, args=()):
577
592
# Default usage is by a message string, but if a return
578
593
# code is passed, convert it to a string with
579
594
# gnutls.strerror()
581
596
if message is None and code is not None:
582
message = GnuTLS.strerror(code)
583
return super(GnuTLS.Error, self).__init__(
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
599
return super(gnutls.Error, self).__init__(
586
602
class CertificateSecurityError(Error):
606
def __init__(self, cls):
609
def from_param(self, obj):
610
if not isinstance(obj, self.cls):
611
raise TypeError("Not of type {}: {!r}"
612
.format(self.cls.__name__, obj))
613
return ctypes.byref(obj.from_param(obj))
615
class CastToVoidPointer:
616
def __init__(self, cls):
619
def from_param(self, obj):
620
if not isinstance(obj, self.cls):
621
raise TypeError("Not of type {}: {!r}"
622
.format(self.cls.__name__, obj))
623
return ctypes.cast(obj.from_param(obj), ctypes.c_void_p)
625
class With_from_param:
627
def from_param(cls, obj):
628
return obj._as_parameter_
590
class Credentials(object):
631
class Credentials(With_from_param):
591
632
def __init__(self):
592
self._c_object = gnutls.certificate_credentials_t()
593
gnutls.certificate_allocate_credentials(
594
ctypes.byref(self._c_object))
633
self._as_parameter_ = gnutls.certificate_credentials_t()
634
gnutls.certificate_allocate_credentials(self)
595
635
self.type = gnutls.CRD_CERTIFICATE
597
637
def __del__(self):
598
gnutls.certificate_free_credentials(self._c_object)
638
gnutls.certificate_free_credentials(self)
600
class ClientSession(object):
640
class ClientSession(With_from_param):
601
641
def __init__(self, socket, credentials=None):
602
self._c_object = gnutls.session_t()
642
self._as_parameter_ = gnutls.session_t()
603
643
gnutls_flags = gnutls.CLIENT
604
if gnutls.check_version("3.5.6"):
644
if gnutls.check_version(b"3.5.6"):
605
645
gnutls_flags |= gnutls.NO_TICKETS
606
646
if gnutls.has_rawpk:
607
647
gnutls_flags |= gnutls.ENABLE_RAWPK
608
gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
648
gnutls.init(self, gnutls_flags)
610
gnutls.set_default_priority(self._c_object)
611
gnutls.transport_set_ptr(self._c_object, socket.fileno())
612
gnutls.handshake_set_private_extensions(self._c_object,
650
gnutls.set_default_priority(self)
651
gnutls.transport_set_ptr(self, socket.fileno())
652
gnutls.handshake_set_private_extensions(self, True)
614
653
self.socket = socket
615
654
if credentials is None:
616
655
credentials = gnutls.Credentials()
617
gnutls.credentials_set(self._c_object, credentials.type,
618
ctypes.cast(credentials._c_object,
656
gnutls.credentials_set(self, credentials.type,
620
658
self.credentials = credentials
622
660
def __del__(self):
623
gnutls.deinit(self._c_object)
625
663
def handshake(self):
626
return gnutls.handshake(self._c_object)
664
return gnutls.handshake(self)
628
666
def send(self, data):
629
667
data = bytes(data)
630
668
data_len = len(data)
631
669
while data_len > 0:
632
data_len -= gnutls.record_send(self._c_object,
670
data_len -= gnutls.record_send(self, data[-data_len:],
637
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
639
676
# Error handling functions
640
677
def _error_code(result):
641
678
"""A function to raise exceptions on errors, suitable
642
679
for the 'restype' attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
645
682
if result == gnutls.E_NO_CERTIFICATE_FOUND:
646
683
raise gnutls.CertificateSecurityError(code=result)
647
684
raise gnutls.Error(code=result)
649
def _retry_on_error(result, func, arguments):
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
650
688
"""A function to retry on some errors, suitable
651
689
for the 'errcheck' attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
653
691
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
654
692
return _error_code(result)
655
693
result = func(*arguments)
662
700
priority_set_direct = _library.gnutls_priority_set_direct
663
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
664
702
ctypes.POINTER(ctypes.c_char_p)]
665
703
priority_set_direct.restype = _error_code
667
705
init = _library.gnutls_init
668
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
669
707
init.restype = _error_code
671
709
set_default_priority = _library.gnutls_set_default_priority
672
set_default_priority.argtypes = [session_t]
710
set_default_priority.argtypes = [ClientSession]
673
711
set_default_priority.restype = _error_code
675
713
record_send = _library.gnutls_record_send
676
record_send.argtypes = [session_t, ctypes.c_void_p,
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
678
716
record_send.restype = ctypes.c_ssize_t
679
717
record_send.errcheck = _retry_on_error
681
719
certificate_allocate_credentials = (
682
720
_library.gnutls_certificate_allocate_credentials)
683
721
certificate_allocate_credentials.argtypes = [
684
ctypes.POINTER(certificate_credentials_t)]
722
PointerTo(Credentials)]
685
723
certificate_allocate_credentials.restype = _error_code
687
725
certificate_free_credentials = (
688
726
_library.gnutls_certificate_free_credentials)
689
certificate_free_credentials.argtypes = [
690
certificate_credentials_t]
727
certificate_free_credentials.argtypes = [Credentials]
691
728
certificate_free_credentials.restype = None
693
730
handshake_set_private_extensions = (
694
731
_library.gnutls_handshake_set_private_extensions)
695
handshake_set_private_extensions.argtypes = [session_t,
732
handshake_set_private_extensions.argtypes = [ClientSession,
697
734
handshake_set_private_extensions.restype = None
699
736
credentials_set = _library.gnutls_credentials_set
700
credentials_set.argtypes = [session_t, credentials_type_t,
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
702
739
credentials_set.restype = _error_code
704
741
strerror = _library.gnutls_strerror
723
760
global_set_log_function.restype = None
725
762
deinit = _library.gnutls_deinit
726
deinit.argtypes = [session_t]
763
deinit.argtypes = [ClientSession]
727
764
deinit.restype = None
729
766
handshake = _library.gnutls_handshake
730
handshake.argtypes = [session_t]
731
handshake.restype = _error_code
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
732
769
handshake.errcheck = _retry_on_error
734
771
transport_set_ptr = _library.gnutls_transport_set_ptr
735
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
736
773
transport_set_ptr.restype = None
738
775
bye = _library.gnutls_bye
739
bye.argtypes = [session_t, close_request_t]
740
bye.restype = _error_code
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
741
778
bye.errcheck = _retry_on_error
743
780
check_version = _library.gnutls_check_version
744
781
check_version.argtypes = [ctypes.c_char_p]
745
782
check_version.restype = ctypes.c_char_p
784
_need_version = b"3.3.0"
785
if check_version(_need_version) is None:
786
raise self.Error("Needs GnuTLS {} or later"
787
.format(_need_version))
789
_tls_rawpk_version = b"3.6.6"
747
790
has_rawpk = bool(check_version(_tls_rawpk_version))
2758
2813
def rfc3339_duration_to_delta(duration):
2759
2814
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
2761
>>> rfc3339_duration_to_delta("P7D")
2762
datetime.timedelta(7)
2763
>>> rfc3339_duration_to_delta("PT60S")
2764
datetime.timedelta(0, 60)
2765
>>> rfc3339_duration_to_delta("PT60M")
2766
datetime.timedelta(0, 3600)
2767
>>> rfc3339_duration_to_delta("PT24H")
2768
datetime.timedelta(1)
2769
>>> rfc3339_duration_to_delta("P1W")
2770
datetime.timedelta(7)
2771
>>> rfc3339_duration_to_delta("PT5M30S")
2772
datetime.timedelta(0, 330)
2773
>>> rfc3339_duration_to_delta("P1DT3M20S")
2774
datetime.timedelta(1, 200)
2816
>>> timedelta = datetime.timedelta
2817
>>> rfc3339_duration_to_delta("P7D") == timedelta(7)
2819
>>> rfc3339_duration_to_delta("PT60S") == timedelta(0, 60)
2821
>>> rfc3339_duration_to_delta("PT60M") == timedelta(0, 3600)
2823
>>> rfc3339_duration_to_delta("PT24H") == timedelta(1)
2825
>>> rfc3339_duration_to_delta("P1W") == timedelta(7)
2827
>>> rfc3339_duration_to_delta("PT5M30S") == timedelta(0, 330)
2829
>>> rfc3339_duration_to_delta("P1DT3M20S") == timedelta(1, 200)
2777
2834
# Parsing an RFC 3339 duration with regular expressions is not
2857
2914
def string_to_delta(interval):
2858
2915
"""Parse a string and return a datetime.timedelta
2860
>>> string_to_delta('7d')
2861
datetime.timedelta(7)
2862
>>> string_to_delta('60s')
2863
datetime.timedelta(0, 60)
2864
>>> string_to_delta('60m')
2865
datetime.timedelta(0, 3600)
2866
>>> string_to_delta('24h')
2867
datetime.timedelta(1)
2868
>>> string_to_delta('1w')
2869
datetime.timedelta(7)
2870
>>> string_to_delta('5m 30s')
2871
datetime.timedelta(0, 330)
2917
>>> string_to_delta('7d') == datetime.timedelta(7)
2919
>>> string_to_delta('60s') == datetime.timedelta(0, 60)
2921
>>> string_to_delta('60m') == datetime.timedelta(0, 3600)
2923
>>> string_to_delta('24h') == datetime.timedelta(1)
2925
>>> string_to_delta('1w') == datetime.timedelta(7)
2927
>>> string_to_delta('5m 30s') == datetime.timedelta(0, 330)