Browse code

A few fixes for python3

* socket interfaces take bytes so convert text strings to bytes when
using them.
* Use b64encode() instead of str.encode('base64')

(cherry picked from commit 56086f3b9ecad43d5daae654c0ac29094b1d572d)

Toshio Kuratomi authored on 2016/10/25 10:43:16
Showing 1 changed files
... ...
@@ -105,8 +105,6 @@ import platform
105 105
 import tempfile
106 106
 import base64
107 107
 
108
-from ansible.module_utils.basic import get_distribution, get_exception
109
-
110 108
 try:
111 109
     import httplib
112 110
 except ImportError:
... ...
@@ -115,7 +113,9 @@ except ImportError:
115 115
 
116 116
 import ansible.module_utils.six.moves.urllib.request as urllib_request
117 117
 import ansible.module_utils.six.moves.urllib.error as urllib_error
118
+from ansible.module_utils.basic import get_distribution, get_exception
118 119
 from ansible.module_utils.six import b
120
+from ansible.module_utils._text import to_bytes
119 121
 
120 122
 try:
121 123
     # python3
... ...
@@ -672,10 +672,10 @@ class SSLValidationHandler(urllib_request.BaseHandler):
672 672
                     s.sendall(self.CONNECT_COMMAND % (self.hostname, self.port))
673 673
                     if proxy_parts.get('username'):
674 674
                         credentials = "%s:%s" % (proxy_parts.get('username',''), proxy_parts.get('password',''))
675
-                        s.sendall('Proxy-Authorization: Basic %s\r\n' % credentials.encode('base64').strip())
676
-                    s.sendall('\r\n')
677
-                    connect_result = ""
678
-                    while connect_result.find("\r\n\r\n") <= 0:
675
+                        s.sendall(b('Proxy-Authorization: Basic %s\r\n') % base64.b64encode(to_bytes(credentials, errors='surrogate_or_strict')).strip())
676
+                    s.sendall(b('\r\n'))
677
+                    connect_result = b("")
678
+                    while connect_result.find(b("\r\n\r\n")) <= 0:
679 679
                         connect_result += s.recv(4096)
680 680
                         # 128 kilobytes of headers should be enough for everyone.
681 681
                         if len(connect_result) > 131072:
... ...
@@ -883,7 +883,10 @@ def open_url(url, data=None, headers=None, method=None, use_proxy=True,
883 883
 
884 884
 
885 885
 def basic_auth_header(username, password):
886
-    return "Basic %s" % base64.b64encode("%s:%s" % (username, password))
886
+    """Takes a username and password and returns a byte string suitable for
887
+    using as value of an Authorization header to do basic auth.
888
+    """
889
+    return b("Basic %s") % base64.b64encode(to_bytes("%s:%s" % (username, password), errors='surrogate_or_strict'))
887 890
 
888 891
 
889 892
 def url_argument_spec():