535
506
# Pretend that we have a GnuTLS module
537
"""This isn't so much a class as it is a module-like namespace."""
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."""
539
511
library = ctypes.util.find_library("gnutls")
540
512
if library is None:
541
513
library = ctypes.util.find_library("gnutls-deb0")
542
514
_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))
545
526
# Unless otherwise indicated, the constants and types below are
546
527
# all from the gnutls/gnutls.h C header file.
590
571
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.
591
576
def __init__(self, message=None, code=None, args=()):
592
577
# Default usage is by a message string, but if a return
593
578
# code is passed, convert it to a string with
594
579
# gnutls.strerror()
596
581
if message is None and code is not None:
597
message = gnutls.strerror(code).decode(
598
"utf-8", errors="replace")
599
return super(gnutls.Error, self).__init__(
582
message = GnuTLS.strerror(code)
583
return super(GnuTLS.Error, self).__init__(
602
586
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_
631
class Credentials(With_from_param):
590
class Credentials(object):
632
591
def __init__(self):
633
self._as_parameter_ = gnutls.certificate_credentials_t()
634
gnutls.certificate_allocate_credentials(self)
592
self._c_object = gnutls.certificate_credentials_t()
593
gnutls.certificate_allocate_credentials(
594
ctypes.byref(self._c_object))
635
595
self.type = gnutls.CRD_CERTIFICATE
637
597
def __del__(self):
638
gnutls.certificate_free_credentials(self)
598
gnutls.certificate_free_credentials(self._c_object)
640
class ClientSession(With_from_param):
600
class ClientSession(object):
641
601
def __init__(self, socket, credentials=None):
642
self._as_parameter_ = gnutls.session_t()
602
self._c_object = gnutls.session_t()
643
603
gnutls_flags = gnutls.CLIENT
644
if gnutls.check_version(b"3.5.6"):
604
if gnutls.check_version("3.5.6"):
645
605
gnutls_flags |= gnutls.NO_TICKETS
646
606
if gnutls.has_rawpk:
647
607
gnutls_flags |= gnutls.ENABLE_RAWPK
648
gnutls.init(self, gnutls_flags)
608
gnutls.init(ctypes.byref(self._c_object), gnutls_flags)
650
gnutls.set_default_priority(self)
651
gnutls.transport_set_ptr(self, socket.fileno())
652
gnutls.handshake_set_private_extensions(self, True)
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,
653
614
self.socket = socket
654
615
if credentials is None:
655
616
credentials = gnutls.Credentials()
656
gnutls.credentials_set(self, credentials.type,
617
gnutls.credentials_set(self._c_object, credentials.type,
618
ctypes.cast(credentials._c_object,
658
620
self.credentials = credentials
660
622
def __del__(self):
623
gnutls.deinit(self._c_object)
663
625
def handshake(self):
664
return gnutls.handshake(self)
626
return gnutls.handshake(self._c_object)
666
628
def send(self, data):
667
629
data = bytes(data)
668
630
data_len = len(data)
669
631
while data_len > 0:
670
data_len -= gnutls.record_send(self, data[-data_len:],
632
data_len -= gnutls.record_send(self._c_object,
674
return gnutls.bye(self, gnutls.SHUT_RDWR)
637
return gnutls.bye(self._c_object, gnutls.SHUT_RDWR)
676
639
# Error handling functions
677
640
def _error_code(result):
678
641
"""A function to raise exceptions on errors, suitable
679
642
for the 'restype' attribute on ctypes functions"""
680
if result >= gnutls.E_SUCCESS:
682
645
if result == gnutls.E_NO_CERTIFICATE_FOUND:
683
646
raise gnutls.CertificateSecurityError(code=result)
684
647
raise gnutls.Error(code=result)
686
def _retry_on_error(result, func, arguments,
687
_error_code=_error_code):
649
def _retry_on_error(result, func, arguments):
688
650
"""A function to retry on some errors, suitable
689
651
for the 'errcheck' attribute on ctypes functions"""
690
while result < gnutls.E_SUCCESS:
691
653
if result not in (gnutls.E_INTERRUPTED, gnutls.E_AGAIN):
692
654
return _error_code(result)
693
655
result = func(*arguments)
700
662
priority_set_direct = _library.gnutls_priority_set_direct
701
priority_set_direct.argtypes = [ClientSession, ctypes.c_char_p,
663
priority_set_direct.argtypes = [session_t, ctypes.c_char_p,
702
664
ctypes.POINTER(ctypes.c_char_p)]
703
665
priority_set_direct.restype = _error_code
705
667
init = _library.gnutls_init
706
init.argtypes = [PointerTo(ClientSession), ctypes.c_int]
668
init.argtypes = [ctypes.POINTER(session_t), ctypes.c_int]
707
669
init.restype = _error_code
709
671
set_default_priority = _library.gnutls_set_default_priority
710
set_default_priority.argtypes = [ClientSession]
672
set_default_priority.argtypes = [session_t]
711
673
set_default_priority.restype = _error_code
713
675
record_send = _library.gnutls_record_send
714
record_send.argtypes = [ClientSession, ctypes.c_void_p,
676
record_send.argtypes = [session_t, ctypes.c_void_p,
716
678
record_send.restype = ctypes.c_ssize_t
717
679
record_send.errcheck = _retry_on_error
719
681
certificate_allocate_credentials = (
720
682
_library.gnutls_certificate_allocate_credentials)
721
683
certificate_allocate_credentials.argtypes = [
722
PointerTo(Credentials)]
684
ctypes.POINTER(certificate_credentials_t)]
723
685
certificate_allocate_credentials.restype = _error_code
725
687
certificate_free_credentials = (
726
688
_library.gnutls_certificate_free_credentials)
727
certificate_free_credentials.argtypes = [Credentials]
689
certificate_free_credentials.argtypes = [
690
certificate_credentials_t]
728
691
certificate_free_credentials.restype = None
730
693
handshake_set_private_extensions = (
731
694
_library.gnutls_handshake_set_private_extensions)
732
handshake_set_private_extensions.argtypes = [ClientSession,
695
handshake_set_private_extensions.argtypes = [session_t,
734
697
handshake_set_private_extensions.restype = None
736
699
credentials_set = _library.gnutls_credentials_set
737
credentials_set.argtypes = [ClientSession, credentials_type_t,
738
CastToVoidPointer(Credentials)]
700
credentials_set.argtypes = [session_t, credentials_type_t,
739
702
credentials_set.restype = _error_code
741
704
strerror = _library.gnutls_strerror
760
723
global_set_log_function.restype = None
762
725
deinit = _library.gnutls_deinit
763
deinit.argtypes = [ClientSession]
726
deinit.argtypes = [session_t]
764
727
deinit.restype = None
766
729
handshake = _library.gnutls_handshake
767
handshake.argtypes = [ClientSession]
768
handshake.restype = ctypes.c_int
730
handshake.argtypes = [session_t]
731
handshake.restype = _error_code
769
732
handshake.errcheck = _retry_on_error
771
734
transport_set_ptr = _library.gnutls_transport_set_ptr
772
transport_set_ptr.argtypes = [ClientSession, transport_ptr_t]
735
transport_set_ptr.argtypes = [session_t, transport_ptr_t]
773
736
transport_set_ptr.restype = None
775
738
bye = _library.gnutls_bye
776
bye.argtypes = [ClientSession, close_request_t]
777
bye.restype = ctypes.c_int
739
bye.argtypes = [session_t, close_request_t]
740
bye.restype = _error_code
778
741
bye.errcheck = _retry_on_error
780
743
check_version = _library.gnutls_check_version
781
744
check_version.argtypes = [ctypes.c_char_p]
782
745
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"
790
747
has_rawpk = bool(check_version(_tls_rawpk_version))
2813
2758
def rfc3339_duration_to_delta(duration):
2814
2759
"""Parse an RFC 3339 "duration" and return a datetime.timedelta
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)
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)
2834
2777
# Parsing an RFC 3339 duration with regular expressions is not
2914
2857
def string_to_delta(interval):
2915
2858
"""Parse a string and return a datetime.timedelta
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)
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)