Debian Codegraph @

lib/ansible/module_utils/urls.py

raw
1 # -*- coding: utf-8 -*-
2 # This code is part of Ansible, but is an independent component.
3 # This particular file snippet, and this file snippet only, is BSD licensed.
4 # Modules you write using this snippet, which is embedded dynamically by Ansible
5 # still belong to the author of the module, and may assign their own license
6 # to the complete work.
7 #
8 # Copyright (c), Michael DeHaan <[email protected]>, 2012-2013
9 # Copyright (c), Toshio Kuratomi <[email protected]>, 2015
10 # Copyright: Contributors to the Ansible project
11 #
12 # Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
13
14
15 """
16 The **urls** utils module offers a replacement for the urllib python library.
17
18 urllib is the python stdlib way to retrieve files from the Internet but it
19 lacks some security features (around verifying SSL certificates) that users
20 should care about in most situations. Using the functions in this module corrects
21 deficiencies in the urllib module wherever possible.
22
23 There are also third-party libraries (for instance, requests) which can be used
24 to replace urllib with a more secure library. However, all third party libraries
25 require that the library be installed on the managed machine. That is an extra step
26 for users making use of a module. If possible, avoid third party libraries by using
27 this code instead.
28 """
29
30 from __future__ import annotations
31
32 import base64
33 import binascii
34 import collections.abc as _c
35 import http.client
36 import io
37 import mimetypes
38 import netrc
39 import os
40 import platform
41 import re
42 import socket
43 import tempfile
44 import traceback
45 import types # pylint: disable=unused-import
46 import urllib.error
47 import urllib.request
48
49 from contextlib import contextmanager
50 from functools import partial
51 from http import cookiejar
52 from urllib.parse import unquote, urlparse, urlunparse
53 from urllib.request import BaseHandler
54
55 try:
56 import gzip
57 HAS_GZIP = True
58 GZIP_IMP_ERR = None
59 except ImportError:
60 HAS_GZIP = False
61 GZIP_IMP_ERR = traceback.format_exc()
62 GzipFile = object
63 else:
64 GzipFile = gzip.GzipFile # type: ignore[assignment,misc]
65
66 from ansible.module_utils.basic import missing_required_lib
67 from ansible.module_utils.common.collections import Mapping, OrderedSet, is_sequence
68 from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text
69 from ansible.module_utils.compat import typing as _t
70
71 try:
72 import ssl
73 HAS_SSL = True
74 except Exception:
75 HAS_SSL = False
76
77 HAS_CRYPTOGRAPHY = True
78 try:
79 from cryptography import x509
80 from cryptography.hazmat.backends import default_backend
81 from cryptography.hazmat.primitives import hashes
82 from cryptography.exceptions import UnsupportedAlgorithm
83 except ImportError:
84 HAS_CRYPTOGRAPHY = False
85
86 # Old import for GSSAPI authentication, this is not used in urls.py but kept for backwards compatibility.
87 try:
88 import urllib_gssapi # pylint: disable=unused-import
89 HAS_GSSAPI = True
90 except ImportError:
91 HAS_GSSAPI = False
92
93 GSSAPI_IMP_ERR = None
94 try:
95 import gssapi
96
97 class HTTPGSSAPIAuthHandler(BaseHandler):
98 """ Handles Negotiate/Kerberos support through the gssapi library. """
99
100 AUTH_HEADER_PATTERN = re.compile(r'(?:.*)\s*(Negotiate|Kerberos)\s*([^,]*),?', re.I)
101 handler_order = 480 # Handle before Digest authentication
102
103 def __init__(self, username=None, password=None):
104 self.username = username
105 self.password = password
106 self._context = None
107
108 def get_auth_value(self, headers):
109 auth_match = self.AUTH_HEADER_PATTERN.search(headers.get('www-authenticate', ''))
110 if auth_match:
111 return auth_match.group(1), base64.b64decode(auth_match.group(2))
112
113 def http_error_401(self, req, fp, code, msg, headers):
114 # If we've already attempted the auth and we've reached this again then there was a failure.
115 if self._context:
116 return
117
118 parsed = urlparse(req.get_full_url())
119
120 auth_header = self.get_auth_value(headers)
121 if not auth_header:
122 return
123 auth_protocol, in_token = auth_header
124
125 username = None
126 if self.username:
127 username = gssapi.Name(self.username, name_type=gssapi.NameType.user)
128
129 if username and self.password:
130 if not hasattr(gssapi.raw, 'acquire_cred_with_password'):
131 raise NotImplementedError("Platform GSSAPI library does not support "
132 "gss_acquire_cred_with_password, cannot acquire GSSAPI credential with "
133 "explicit username and password.")
134
135 b_password = to_bytes(self.password, errors='surrogate_or_strict')
136 cred = gssapi.raw.acquire_cred_with_password(username, b_password, usage='initiate').creds
137
138 else:
139 cred = gssapi.Credentials(name=username, usage='initiate')
140
141 # Get the peer certificate for the channel binding token if possible (HTTPS). A bug on macOS causes the
142 # authentication to fail when the CBT is present. Just skip that platform.
143 cbt = None
144 cert = getpeercert(fp, True)
145 if cert and platform.system() != 'Darwin':
146 cert_hash = get_channel_binding_cert_hash(cert)
147 if cert_hash:
148 cbt = gssapi.raw.ChannelBindings(application_data=b"tls-server-end-point:" + cert_hash)
149
150 # TODO: We could add another option that is set to include the port in the SPN if desired in the future.
151 target = gssapi.Name("HTTP@%s" % parsed.hostname, gssapi.NameType.hostbased_service)
152 self._context = gssapi.SecurityContext(usage="initiate", name=target, creds=cred, channel_bindings=cbt)
153
154 resp = None
155 while not self._context.complete:
156 out_token = self._context.step(in_token)
157 if not out_token:
158 break
159
160 auth_header = '%s %s' % (auth_protocol, to_native(base64.b64encode(out_token)))
161 req.add_unredirected_header('Authorization', auth_header)
162 resp = self.parent.open(req)
163
164 # The response could contain a token that the client uses to validate the server
165 auth_header = self.get_auth_value(resp.headers)
166 if not auth_header:
167 break
168 in_token = auth_header[1]
169
170 return resp
171
172 except ImportError:
173 GSSAPI_IMP_ERR = traceback.format_exc()
174 HTTPGSSAPIAuthHandler = None # type: types.ModuleType | None # type: ignore[no-redef]
175
176
177 PEM_CERT_RE = re.compile(
178 r'^-----BEGIN CERTIFICATE-----\n.+?-----END CERTIFICATE-----$',
179 flags=re.M | re.S
180 )
181
182 #
183 # Exceptions
184 #
185
186
187 class ConnectionError(Exception):
188 """Failed to connect to the server"""
189 pass
190
191
192 class ProxyError(ConnectionError):
193 """Failure to connect because of a proxy"""
194 pass
195
196
197 class SSLValidationError(ConnectionError):
198 """Failure to connect due to SSL validation failing
199
200 No longer used, but kept for backwards compatibility
201 """
202 pass
203
204
205 class NoSSLError(SSLValidationError):
206 """Needed to connect to an HTTPS url but no ssl library available to verify the certificate
207
208 No longer used, but kept for backwards compatibility
209 """
210 pass
211
212
213 class MissingModuleError(Exception):
214 """Failed to import 3rd party module required by the caller"""
215 def __init__(self, message, import_traceback, module=None):
216 super().__init__(message)
217 self.import_traceback = import_traceback
218 self.module = module
219
220
221 UnixHTTPSHandler = None
222 UnixHTTPSConnection = None
223 if HAS_SSL:
224 @contextmanager
225 def unix_socket_patch_httpconnection_connect():
226 """Monkey patch ``http.client.HTTPConnection.connect`` to be ``UnixHTTPConnection.connect``
227 so that when calling ``super(UnixHTTPSConnection, self).connect()`` we get the
228 correct behavior of creating self.sock for the unix socket
229 """
230 _connect = http.client.HTTPConnection.connect
231 http.client.HTTPConnection.connect = UnixHTTPConnection.connect
232 yield
233 http.client.HTTPConnection.connect = _connect
234
235 class UnixHTTPSConnection(http.client.HTTPSConnection): # type: ignore[no-redef]
236 def __init__(self, unix_socket):
237 self._unix_socket = unix_socket
238
239 def connect(self):
240 # This method exists simply to ensure we monkeypatch
241 # http.client.HTTPConnection.connect to call UnixHTTPConnection.connect
242 with unix_socket_patch_httpconnection_connect():
243 # Disable pylint check for the super() call. It complains about UnixHTTPSConnection
244 # being a NoneType because of the initial definition above, but it won't actually
245 # be a NoneType when this code runs
246 super().connect()
247
248 def __call__(self, *args, **kwargs):
249 super().__init__(*args, **kwargs)
250 return self
251
252 class UnixHTTPSHandler(urllib.request.HTTPSHandler): # type: ignore[no-redef]
253 def __init__(self, unix_socket, **kwargs):
254 super().__init__(**kwargs)
255 self._unix_socket = unix_socket
256
257 def https_open(self, req):
258 kwargs = {}
259 try:
260 # deprecated: description='deprecated check_hostname' python_version='3.12'
261 kwargs['check_hostname'] = self._check_hostname
262 except AttributeError:
263 pass
264 return self.do_open(
265 UnixHTTPSConnection(self._unix_socket),
266 req,
267 context=self._context,
268 **kwargs
269 )
270
271
272 class UnixHTTPConnection(http.client.HTTPConnection):
273 """Handles http requests to a unix socket file"""
274
275 def __init__(self, unix_socket):
276 self._unix_socket = unix_socket
277
278 def connect(self):
279 self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
280 try:
281 self.sock.connect(self._unix_socket)
282 except OSError as e:
283 raise OSError('Invalid Socket File (%s): %s' % (self._unix_socket, e))
284 if self.timeout is not socket._GLOBAL_DEFAULT_TIMEOUT:
285 self.sock.settimeout(self.timeout)
286
287 def __call__(self, *args, **kwargs):
288 super().__init__(*args, **kwargs)
289 return self
290
291
292 class UnixHTTPHandler(urllib.request.HTTPHandler):
293 """Handler for Unix urls"""
294
295 def __init__(self, unix_socket, **kwargs):
296 super().__init__(**kwargs)
297 self._unix_socket = unix_socket
298
299 def http_open(self, req):
300 return self.do_open(UnixHTTPConnection(self._unix_socket), req)
301
302
303 class ParseResultDottedDict(dict):
304 """
305 A dict that acts similarly to the ParseResult named tuple from urllib
306 """
307 def __init__(self, *args, **kwargs):
308 super().__init__(*args, **kwargs)
309 self.__dict__ = self
310
311 def as_list(self):
312 """
313 Generate a list from this dict, that looks like the ParseResult named tuple
314 """
315 return [self.get(k, None) for k in ('scheme', 'netloc', 'path', 'params', 'query', 'fragment')]
316
317
318 def mask_url(url: str) -> str:
319 """
320 Safely display a url by masking confidential data
321 from a string or the result from urlparse/split
322 """
323 if (parsed_url := urlparse(url)) and not parsed_url.username and not parsed_url.password:
324 return url
325
326 netloc: str
327 mask = '****'
328 if parsed_url.password:
329 netloc = parsed_url.netloc.replace(f'{parsed_url.username}:{parsed_url.password}@', f'{mask}:{mask}@')
330 else:
331 netloc = parsed_url.netloc.replace(f'{parsed_url.username}@', f'{mask}@')
332
333 return urlunparse(parsed_url._replace(netloc=netloc))
334
335
336 def generic_urlparse(parts):
337 """
338 Returns a dictionary of url parts as parsed by urlparse,
339 but accounts for the fact that older versions of that
340 library do not support named attributes (ie. .netloc)
341
342 This method isn't of much use any longer, but is kept
343 in a minimal state for backwards compat.
344 """
345 result = ParseResultDottedDict(parts._asdict())
346 result.update({
347 'username': parts.username,
348 'password': parts.password,
349 'hostname': parts.hostname,
350 'port': parts.port,
351 })
352 return result
353
354
355 def extract_pem_certs(data):
356 for match in PEM_CERT_RE.finditer(data):
357 yield match.group(0)
358
359
360 def get_response_filename(response):
361 if filename := response.headers.get_param('filename', header='content-disposition'):
362 filename = os.path.basename(filename)
363 else:
364 url = response.geturl()
365 path = urlparse(url)[2]
366 filename = os.path.basename(path.rstrip('/')) or None
367 if filename:
368 filename = unquote(filename)
369
370 return filename
371
372
373 def parse_content_type(response):
374 get_type = response.headers.get_content_type
375 get_param = response.headers.get_param
376 content_type = (get_type() or 'application/octet-stream').split(',')[0]
377 main_type, sub_type = content_type.split('/')
378 charset = (get_param('charset') or 'utf-8').split(',')[0]
379 return content_type, main_type, sub_type, charset
380
381
382 class GzipDecodedReader(GzipFile):
383 """A file-like object to decode a response encoded with the gzip
384 method, as described in RFC 1952.
385
386 Largely copied from ``xmlrpclib``/``xmlrpc.client``
387 """
388 def __init__(self, fp):
389 if not HAS_GZIP:
390 raise MissingModuleError(self.missing_gzip_error(), import_traceback=GZIP_IMP_ERR)
391
392 self._io = fp
393 super().__init__(mode='rb', fileobj=self._io)
394
395 def close(self):
396 try:
397 gzip.GzipFile.close(self)
398 finally:
399 self._io.close()
400
401 @staticmethod
402 def missing_gzip_error():
403 return missing_required_lib(
404 'gzip',
405 reason='to decompress gzip encoded responses. '
406 'Set "decompress" to False, to prevent attempting auto decompression'
407 )
408
409
410 class HTTPRedirectHandler(urllib.request.HTTPRedirectHandler):
411 """This is an implementation of a RedirectHandler to match the
412 functionality provided by httplib2. It will utilize the value of
413 ``follow_redirects`` to determine how redirects should be handled in
414 urllib.
415 """
416
417 def __init__(self, follow_redirects=None):
418 self.follow_redirects = follow_redirects
419
420 def __call__(self, *args, **kwargs):
421 super().__init__(*args, **kwargs)
422 return self
423
424 try:
425 urllib.request.HTTPRedirectHandler.http_error_308 # type: ignore[attr-defined]
426 except AttributeError:
427 # deprecated: description='urllib http 308 support' python_version='3.11'
428 http_error_308 = urllib.request.HTTPRedirectHandler.http_error_302
429
430 def redirect_request(self, req, fp, code, msg, headers, newurl):
431 follow_redirects = self.follow_redirects
432
433 # Preserve urllib2 compatibility
434 if follow_redirects in ('urllib2', 'urllib'):
435 return urllib.request.HTTPRedirectHandler.redirect_request(self, req, fp, code, msg, headers, newurl)
436
437 # Handle disabled redirects
438 elif follow_redirects in ('none', False):
439 raise urllib.error.HTTPError(newurl, code, msg, headers, fp)
440
441 method = req.get_method()
442
443 # Handle non-redirect HTTP status or invalid follow_redirects
444 if follow_redirects in ('all', True):
445 if code < 300 or code >= 400:
446 raise urllib.error.HTTPError(req.get_full_url(), code, msg, headers, fp)
447 elif follow_redirects == 'safe':
448 if code < 300 or code >= 400 or method not in ('GET', 'HEAD'):
449 raise urllib.error.HTTPError(req.get_full_url(), code, msg, headers, fp)
450 else:
451 raise urllib.error.HTTPError(req.get_full_url(), code, msg, headers, fp)
452
453 data = req.data
454 origin_req_host = req.origin_req_host
455
456 # Be conciliant with URIs containing a space
457 newurl = newurl.replace(' ', '%20')
458
459 # Support redirect with payload and original headers
460 if code in (307, 308):
461 # Preserve payload and headers
462 req_headers = req.headers
463 else:
464 # Do not preserve payload and filter headers
465 data = None
466 req_headers = {k: v for k, v in req.headers.items()
467 if k.lower() not in ("content-length", "content-type", "transfer-encoding")}
468
469 # http://tools.ietf.org/html/rfc7231#section-6.4.4
470 if code == 303 and method != 'HEAD':
471 method = 'GET'
472
473 # Do what the browsers do, despite standards...
474 # First, turn 302s into GETs.
475 if code == 302 and method != 'HEAD':
476 method = 'GET'
477
478 # Second, if a POST is responded to with a 301, turn it into a GET.
479 if code == 301 and method == 'POST':
480 method = 'GET'
481
482 return urllib.request.Request(
483 newurl,
484 data=data,
485 headers=req_headers,
486 origin_req_host=origin_req_host,
487 unverifiable=True,
488 method=method.upper(),
489 )
490
491
492 def make_context(cafile=None, cadata=None, capath=None, ciphers=None, validate_certs=True, client_cert=None,
493 client_key=None):
494 if ciphers is None:
495 ciphers = []
496
497 if not is_sequence(ciphers):
498 raise TypeError('Ciphers must be a list. Got %s.' % ciphers.__class__.__name__)
499
500 context = ssl.create_default_context(cafile=cafile)
501
502 if not validate_certs:
503 context.options |= ssl.OP_NO_SSLv3
504 context.check_hostname = False
505 context.verify_mode = ssl.CERT_NONE
506
507 # If cafile is passed, we are only using that for verification,
508 # don't add additional ca certs
509 if validate_certs and not cafile:
510 if not cadata:
511 cadata = bytearray()
512 cadata.extend(get_ca_certs(capath=capath)[0])
513 if cadata:
514 context.load_verify_locations(cadata=cadata)
515
516 if ciphers:
517 context.set_ciphers(':'.join(map(to_native, ciphers)))
518
519 if client_cert:
520 # TLS 1.3 needs this to be set to True to allow post handshake cert
521 # authentication. This functionality was added in Python 3.8 and was
522 # backported to 3.6.7, and 3.7.1 so needs a check for now.
523 if hasattr(context, "post_handshake_auth"):
524 context.post_handshake_auth = True
525
526 context.load_cert_chain(client_cert, keyfile=client_key)
527
528 return context
529
530
531 def get_ca_certs(cafile=None, capath=None):
532 # tries to find a valid CA cert in one of the
533 # standard locations for the current distribution
534
535 # Not directly using a bytearray to avoid duplicates with fast lookup
536 cadata = OrderedSet()
537
538 # If cafile is passed, we are only using that for verification,
539 # don't add additional ca certs
540 if cafile:
541 paths_checked = [cafile]
542 with open(to_bytes(cafile, errors='surrogate_or_strict'), 'r', errors='surrogateescape') as f:
543 for pem in extract_pem_certs(f.read()):
544 b_der = ssl.PEM_cert_to_DER_cert(pem)
545 cadata.add(b_der)
546 return bytearray().join(cadata), paths_checked
547
548 default_verify_paths = ssl.get_default_verify_paths()
549 default_capath = default_verify_paths.capath
550 paths_checked = {default_capath or default_verify_paths.cafile}
551
552 if capath:
553 paths_checked.add(capath)
554
555 system = to_text(platform.system(), errors='surrogate_or_strict')
556 # build a list of paths to check for .crt/.pem files
557 # based on the platform type
558 if system == u'Linux':
559 paths_checked.add('/etc/pki/ca-trust/extracted/pem')
560 paths_checked.add('/etc/pki/tls/certs')
561 paths_checked.add('/usr/share/ca-certificates/cacert.org')
562 elif system == u'FreeBSD':
563 paths_checked.add('/usr/local/share/certs')
564 elif system == u'OpenBSD':
565 paths_checked.add('/etc/ssl')
566 elif system == u'NetBSD':
567 paths_checked.add('/etc/openssl/certs')
568 elif system == u'SunOS':
569 paths_checked.add('/opt/local/etc/openssl/certs')
570 elif system == u'AIX':
571 paths_checked.add('/var/ssl/certs')
572 paths_checked.add('/opt/freeware/etc/ssl/certs')
573 elif system == u'Darwin':
574 paths_checked.add('/usr/local/etc/openssl')
575
576 # fall back to a user-deployed cert in a standard
577 # location if the OS platform one is not available
578 paths_checked.add('/etc/ansible')
579
580 # for all of the paths, find any .crt or .pem files
581 # and compile them into single temp file for use
582 # in the ssl check to speed up the test
583 for path in paths_checked:
584 if not path or path == default_capath or not os.path.isdir(path):
585 continue
586
587 for f in os.listdir(path):
588 full_path = os.path.join(path, f)
589 if os.path.isfile(full_path) and os.path.splitext(f)[1] in {'.pem', '.cer', '.crt'}:
590 try:
591 with open(full_path, 'r', errors='surrogateescape') as cert_file:
592 cert = cert_file.read()
593 try:
594 for pem in extract_pem_certs(cert):
595 b_der = ssl.PEM_cert_to_DER_cert(pem)
596 cadata.add(b_der)
597 except Exception:
598 continue
599 except OSError:
600 pass
601
602 # paths_checked isn't used any more, but is kept just for ease of debugging
603 return bytearray().join(cadata), list(paths_checked)
604
605
606 def getpeercert(response, binary_form=False):
607 """ Attempt to get the peer certificate of the response from urlopen. """
608 socket = response.fp.raw._sock
609
610 try:
611 return socket.getpeercert(binary_form)
612 except AttributeError:
613 pass # Not HTTPS
614
615
616 def get_channel_binding_cert_hash(certificate_der):
617 """ Gets the channel binding app data for a TLS connection using the peer cert. """
618 if not HAS_CRYPTOGRAPHY:
619 return
620
621 # Logic documented in RFC 5929 section 4 https://tools.ietf.org/html/rfc5929#section-4
622 cert = x509.load_der_x509_certificate(certificate_der, default_backend())
623
624 hash_algorithm = None
625 try:
626 hash_algorithm = cert.signature_hash_algorithm
627 except UnsupportedAlgorithm:
628 pass
629
630 # If the signature hash algorithm is unknown/unsupported or md5/sha1 we must use SHA256.
631 if not hash_algorithm or hash_algorithm.name in ('md5', 'sha1'):
632 hash_algorithm = hashes.SHA256()
633
634 digest = hashes.Hash(hash_algorithm, default_backend())
635 digest.update(certificate_der)
636 return digest.finalize()
637
638
639 def rfc2822_date_string(timetuple, zone='-0000'):
640 """Accepts a timetuple and optional zone which defaults to ``-0000``
641 and returns a date string as specified by RFC 2822, e.g.:
642
643 Fri, 09 Nov 2001 01:08:47 -0000
644
645 Copied from email.utils.formatdate and modified for separate use
646 """
647 return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
648 ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][timetuple[6]],
649 timetuple[2],
650 ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
651 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][timetuple[1] - 1],
652 timetuple[0], timetuple[3], timetuple[4], timetuple[5],
653 zone)
654
655
656 def _configure_auth(url, url_username, url_password, use_gssapi, force_basic_auth, use_netrc):
657 headers = {}
658 handlers = []
659
660 parsed = urlparse(url)
661 if parsed.scheme == 'ftp':
662 return url, headers, handlers
663
664 username = url_username
665 password = url_password
666
667 if username:
668 netloc = parsed.netloc
669 elif '@' in parsed.netloc:
670 credentials, netloc = parsed.netloc.split('@', 1)
671 if ':' in credentials:
672 username, password = credentials.split(':', 1)
673 else:
674 username = credentials
675 password = ''
676 username = unquote(username)
677 password = unquote(password)
678
679 # reconstruct url without credentials
680 url = urlunparse(parsed._replace(netloc=netloc))
681
682 if use_gssapi:
683 if HTTPGSSAPIAuthHandler: # type: ignore[truthy-function]
684 handlers.append(HTTPGSSAPIAuthHandler(username, password))
685 else:
686 imp_err_msg = missing_required_lib('gssapi', reason='for use_gssapi=True',
687 url='https://pypi.org/project/gssapi/')
688 raise MissingModuleError(imp_err_msg, import_traceback=GSSAPI_IMP_ERR)
689
690 elif username and not force_basic_auth:
691 passman = urllib.request.HTTPPasswordMgrWithDefaultRealm()
692
693 # this creates a password manager
694 passman.add_password(None, netloc, username, password)
695
696 # because we have put None at the start it will always
697 # use this username/password combination for urls
698 # for which `theurl` is a super-url
699 authhandler = urllib.request.HTTPBasicAuthHandler(passman)
700 digest_authhandler = urllib.request.HTTPDigestAuthHandler(passman)
701
702 # create the AuthHandler
703 handlers.append(authhandler)
704 handlers.append(digest_authhandler)
705
706 elif username and force_basic_auth:
707 headers["Authorization"] = basic_auth_header(username, password)
708
709 elif use_netrc:
710 try:
711 rc = netrc.netrc(os.environ.get('NETRC'))
712 login = rc.authenticators(parsed.hostname)
713 except OSError:
714 login = None
715
716 if login:
717 username, dummy, password = login
718 if username and password:
719 headers["Authorization"] = basic_auth_header(username, password)
720
721 return url, headers, handlers
722
723
724 class Request:
725 def __init__(self, headers=None, use_proxy=True, force=False, timeout=10, validate_certs=True,
726 url_username=None, url_password=None, http_agent=None, force_basic_auth=False,
727 follow_redirects='urllib2', client_cert=None, client_key=None, cookies=None, unix_socket=None,
728 ca_path=None, unredirected_headers=None, decompress=True, ciphers=None, use_netrc=True,
729 context=None):
730 """This class works somewhat similarly to the ``Session`` class of from requests
731 by defining a cookiejar that can be used across requests as well as cascaded defaults that
732 can apply to repeated requests
733
734 For documentation of params, see ``Request.open``
735
736 >>> from ansible.module_utils.urls import Request
737 >>> r = Request()
738 >>> r.open('GET', 'http://httpbin.org/cookies/set?k1=v1').read()
739 '{\n "cookies": {\n "k1": "v1"\n }\n}\n'
740 >>> r = Request(url_username='user', url_password='passwd')
741 >>> r.open('GET', 'http://httpbin.org/basic-auth/user/passwd').read()
742 '{\n "authenticated": true, \n "user": "user"\n}\n'
743 >>> r = Request(headers=dict(foo='bar'))
744 >>> r.open('GET', 'http://httpbin.org/get', headers=dict(baz='qux')).read()
745
746 """
747
748 self.headers = headers or {}
749 if not isinstance(self.headers, dict):
750 raise ValueError("headers must be a dict: %r" % self.headers)
751 self.use_proxy = use_proxy
752 self.force = force
753 self.timeout = timeout
754 self.validate_certs = validate_certs
755 self.url_username = url_username
756 self.url_password = url_password
757 self.http_agent = http_agent
758 self.force_basic_auth = force_basic_auth
759 self.follow_redirects = follow_redirects
760 self.client_cert = client_cert
761 self.client_key = client_key
762 self.unix_socket = unix_socket
763 self.ca_path = ca_path
764 self.unredirected_headers = unredirected_headers
765 self.decompress = decompress
766 self.ciphers = ciphers
767 self.use_netrc = use_netrc
768 self.context = context
769 if isinstance(cookies, cookiejar.CookieJar):
770 self.cookies = cookies
771 else:
772 self.cookies = cookiejar.CookieJar()
773
774 def _fallback(self, value, fallback):
775 if value is None:
776 return fallback
777 return value
778
779 def open(self, method, url, data=None, headers=None, use_proxy=None,
780 force=None, last_mod_time=None, timeout=None, validate_certs=None,
781 url_username=None, url_password=None, http_agent=None,
782 force_basic_auth=None, follow_redirects=None,
783 client_cert=None, client_key=None, cookies=None, use_gssapi=False,
784 unix_socket=None, ca_path=None, unredirected_headers=None, decompress=None,
785 ciphers=None, use_netrc=None, context=None):
786 """
787 Sends a request via HTTP(S) or FTP using urllib (Python3)
788
789 Does not require the module environment
790
791 Returns :class:`HTTPResponse` object.
792
793 :arg method: method for the request
794 :arg url: URL to request
795
796 :kwarg data: (optional) bytes, or file-like object to send
797 in the body of the request
798 :kwarg headers: (optional) Dictionary of HTTP Headers to send with the
799 request
800 :kwarg use_proxy: (optional) Boolean of whether or not to use proxy
801 :kwarg force: (optional) Boolean of whether or not to set `cache-control: no-cache` header
802 :kwarg last_mod_time: (optional) Datetime object to use when setting If-Modified-Since header
803 :kwarg timeout: (optional) How long to wait for the server to send
804 data before giving up, as a float
805 :kwarg validate_certs: (optional) Booleani that controls whether we verify
806 the server's TLS certificate
807 :kwarg url_username: (optional) String of the user to use when authenticating
808 :kwarg url_password: (optional) String of the password to use when authenticating
809 :kwarg http_agent: (optional) String of the User-Agent to use in the request
810 :kwarg force_basic_auth: (optional) Boolean determining if auth header should be sent in the initial request
811 :kwarg follow_redirects: (optional) String of urllib2, all, safe, none to determine how redirects are
812 followed, see HTTPRedirectHandler for more information
813 :kwarg client_cert: (optional) PEM formatted certificate chain file to be used for SSL client authentication.
814 This file can also include the key as well, and if the key is included, client_key is not required
815 :kwarg client_key: (optional) PEM formatted file that contains your private key to be used for SSL client
816 authentication. If client_cert contains both the certificate and key, this option is not required
817 :kwarg cookies: (optional) CookieJar object to send with the
818 request
819 :kwarg use_gssapi: (optional) Use GSSAPI handler of requests.
820 :kwarg unix_socket: (optional) String of file system path to unix socket file to use when establishing
821 connection to the provided url
822 :kwarg ca_path: (optional) String of file system path to CA cert bundle to use
823 :kwarg unredirected_headers: (optional) A list of headers to not attach on a redirected request
824 :kwarg decompress: (optional) Whether to attempt to decompress gzip content-encoded responses
825 :kwarg ciphers: (optional) List of ciphers to use
826 :kwarg use_netrc: (optional) Boolean determining whether to use credentials from ~/.netrc file
827 :kwarg context: (optional) ssl.Context object for SSL validation. When provided, all other SSL related
828 arguments are ignored. See make_context.
829 :returns: HTTPResponse. Added in Ansible 2.9
830 """
831
832 if headers is None:
833 headers = {}
834 elif not isinstance(headers, dict):
835 raise ValueError("headers must be a dict")
836 headers = dict(self.headers, **headers)
837
838 use_proxy = self._fallback(use_proxy, self.use_proxy)
839 force = self._fallback(force, self.force)
840 timeout = self._fallback(timeout, self.timeout)
841 validate_certs = self._fallback(validate_certs, self.validate_certs)
842 url_username = self._fallback(url_username, self.url_username)
843 url_password = self._fallback(url_password, self.url_password)
844 http_agent = self._fallback(http_agent, self.http_agent)
845 force_basic_auth = self._fallback(force_basic_auth, self.force_basic_auth)
846 follow_redirects = self._fallback(follow_redirects, self.follow_redirects)
847 client_cert = self._fallback(client_cert, self.client_cert)
848 client_key = self._fallback(client_key, self.client_key)
849 cookies = self._fallback(cookies, self.cookies)
850 unix_socket = self._fallback(unix_socket, self.unix_socket)
851 ca_path = self._fallback(ca_path, self.ca_path)
852 unredirected_headers = self._fallback(unredirected_headers, self.unredirected_headers)
853 decompress = self._fallback(decompress, self.decompress)
854 ciphers = self._fallback(ciphers, self.ciphers)
855 use_netrc = self._fallback(use_netrc, self.use_netrc)
856 context = self._fallback(context, self.context)
857
858 handlers = []
859
860 if unix_socket:
861 handlers.append(UnixHTTPHandler(unix_socket))
862
863 url, auth_headers, auth_handlers = _configure_auth(url, url_username, url_password, use_gssapi, force_basic_auth, use_netrc)
864 headers.update(auth_headers)
865 handlers.extend(auth_handlers)
866
867 if not use_proxy:
868 proxyhandler = urllib.request.ProxyHandler({})
869 handlers.append(proxyhandler)
870
871 if not context:
872 context = make_context(
873 cafile=ca_path,
874 ciphers=ciphers,
875 validate_certs=validate_certs,
876 client_cert=client_cert,
877 client_key=client_key,
878 )
879 if unix_socket:
880 ssl_handler = UnixHTTPSHandler(unix_socket=unix_socket, context=context)
881 else:
882 ssl_handler = urllib.request.HTTPSHandler(context=context)
883 handlers.append(ssl_handler)
884
885 handlers.append(HTTPRedirectHandler(follow_redirects))
886
887 # add some nicer cookie handling
888 if cookies is not None:
889 handlers.append(urllib.request.HTTPCookieProcessor(cookies))
890
891 opener = urllib.request.build_opener(*handlers)
892 urllib.request.install_opener(opener)
893
894 data = to_bytes(data, nonstring='passthru')
895 request = urllib.request.Request(url, data=data, method=method.upper())
896
897 # add the custom agent header, to help prevent issues
898 # with sites that block the default urllib agent string
899 if http_agent:
900 request.add_header('User-agent', http_agent)
901
902 # Cache control
903 # Either we directly force a cache refresh
904 if force:
905 request.add_header('cache-control', 'no-cache')
906 # or we do it if the original is more recent than our copy
907 elif last_mod_time:
908 tstamp = rfc2822_date_string(last_mod_time.timetuple(), 'GMT')
909 request.add_header('If-Modified-Since', tstamp)
910
911 # user defined headers now, which may override things we've set above
912 unredirected_headers = [h.lower() for h in (unredirected_headers or [])]
913 for header in headers:
914 if header.lower() in unredirected_headers:
915 request.add_unredirected_header(header, headers[header])
916 else:
917 request.add_header(header, headers[header])
918
919 r = urllib.request.urlopen(request, None, timeout)
920 if decompress and r.headers.get('content-encoding', '').lower() == 'gzip':
921 fp = GzipDecodedReader(r.fp)
922 r.fp = fp
923 # Content-Length does not match gzip decoded length
924 # Prevent ``r.read`` from stopping at Content-Length
925 r.length = None
926 return r
927
928 def get(self, url, **kwargs):
929 r"""Sends a GET request. Returns :class:`HTTPResponse` object.
930
931 :arg url: URL to request
932 :kwarg \*\*kwargs: Optional arguments that ``open`` takes.
933 :returns: HTTPResponse
934 """
935
936 return self.open('GET', url, **kwargs)
937
938 def options(self, url, **kwargs):
939 r"""Sends a OPTIONS request. Returns :class:`HTTPResponse` object.
940
941 :arg url: URL to request
942 :kwarg \*\*kwargs: Optional arguments that ``open`` takes.
943 :returns: HTTPResponse
944 """
945
946 return self.open('OPTIONS', url, **kwargs)
947
948 def head(self, url, **kwargs):
949 r"""Sends a HEAD request. Returns :class:`HTTPResponse` object.
950
951 :arg url: URL to request
952 :kwarg \*\*kwargs: Optional arguments that ``open`` takes.
953 :returns: HTTPResponse
954 """
955
956 return self.open('HEAD', url, **kwargs)
957
958 def post(self, url, data=None, **kwargs):
959 r"""Sends a POST request. Returns :class:`HTTPResponse` object.
960
961 :arg url: URL to request.
962 :kwarg data: (optional) bytes, or file-like object to send in the body of the request.
963 :kwarg \*\*kwargs: Optional arguments that ``open`` takes.
964 :returns: HTTPResponse
965 """
966
967 return self.open('POST', url, data=data, **kwargs)
968
969 def put(self, url, data=None, **kwargs):
970 r"""Sends a PUT request. Returns :class:`HTTPResponse` object.
971
972 :arg url: URL to request.
973 :kwarg data: (optional) bytes, or file-like object to send in the body of the request.
974 :kwarg \*\*kwargs: Optional arguments that ``open`` takes.
975 :returns: HTTPResponse
976 """
977
978 return self.open('PUT', url, data=data, **kwargs)
979
980 def patch(self, url, data=None, **kwargs):
981 r"""Sends a PATCH request. Returns :class:`HTTPResponse` object.
982
983 :arg url: URL to request.
984 :kwarg data: (optional) bytes, or file-like object to send in the body of the request.
985 :kwarg \*\*kwargs: Optional arguments that ``open`` takes.
986 :returns: HTTPResponse
987 """
988
989 return self.open('PATCH', url, data=data, **kwargs)
990
991 def delete(self, url, **kwargs):
992 r"""Sends a DELETE request. Returns :class:`HTTPResponse` object.
993
994 :arg url: URL to request
995 :kwargs \*\*kwargs: Optional arguments that ``open`` takes.
996 :returns: HTTPResponse
997 """
998
999 return self.open('DELETE', url, **kwargs)
1000
1001
1002 def open_url(url, data=None, headers=None, method=None, use_proxy=True,
1003 force=False, last_mod_time=None, timeout=10, validate_certs=True,
1004 url_username=None, url_password=None, http_agent=None,
1005 force_basic_auth=False, follow_redirects='urllib2',
1006 client_cert=None, client_key=None, cookies=None,
1007 use_gssapi=False, unix_socket=None, ca_path=None,
1008 unredirected_headers=None, decompress=True, ciphers=None, use_netrc=True):
1009 """
1010 Sends a request via HTTP(S) or FTP using urllib (Python3)
1011
1012 Does not require the module environment
1013 """
1014 method = method or ('POST' if data else 'GET')
1015 return Request().open(method, url, data=data, headers=headers, use_proxy=use_proxy,
1016 force=force, last_mod_time=last_mod_time, timeout=timeout, validate_certs=validate_certs,
1017 url_username=url_username, url_password=url_password, http_agent=http_agent,
1018 force_basic_auth=force_basic_auth, follow_redirects=follow_redirects,
1019 client_cert=client_cert, client_key=client_key, cookies=cookies,
1020 use_gssapi=use_gssapi, unix_socket=unix_socket, ca_path=ca_path,
1021 unredirected_headers=unredirected_headers, decompress=decompress, ciphers=ciphers, use_netrc=use_netrc)
1022
1023
1024 # deprecated: description='TypedDict Required/NotRequired' python_version='3.11'
1025 # TODO: When Python 3.11+ is the minimum, use Required/NotRequired to properly
1026 # enforce that at least one of filename or content is required
1027 class _MultipartField(_t.TypedDict, total=False):
1028 """TypedDict for multipart field configuration.
1029
1030 At least one of 'filename' or 'content' must be provided.
1031 """
1032 filename: str
1033 content: str
1034 mime_type: str
1035 multipart_encoding: _t.Literal['base64', '7or8bit']
1036
1037
1038 _CTE: _t.TypeAlias = _t.Literal[b'base64', b'7bit']
1039 _EncToCTEMap: dict[str, _CTE] = {
1040 'base64': b'base64',
1041 '7or8bit': b'7bit',
1042 }
1043
1044 # Constants for multipart generation
1045 _CHUNK_SIZE = 65536
1046 _DEFAULT_MIME_TYPE = b'application/octet-stream'
1047 _TEXT_CONTENT_TYPE = b'text/plain'
1048
1049
1050 class _MultipartReader(io.RawIOBase):
1051 """File-like reader for streaming multipart content without materializing in memory.
1052
1053 Wraps a generator that yields multipart chunks and provides read()/readinto()
1054 interface compatible with urllib and other file-like consumers.
1055 """
1056
1057 def __init__(self, generator: _t.Generator[bytes, None, None]) -> None:
1058 self._generator = generator
1059 self._buffer = bytearray()
1060 self._exhausted = False
1061
1062 def readable(self) -> bool:
1063 return True
1064
1065 def readinto(self, buffer: bytearray | memoryview) -> int: # type: ignore[override]
1066 """Read up to len(buffer) bytes into buffer. Returns number of bytes read."""
1067 size = len(buffer)
1068 data = self.read(size)
1069 n = len(data)
1070 buffer[:n] = data
1071 return n
1072
1073 def read(self, size: int = -1) -> bytes:
1074 """Read up to size bytes. If size is -1 or None, read all remaining data."""
1075 if self._exhausted and not self._buffer:
1076 return b''
1077
1078 if size is None or size < 0:
1079 all_data = bytearray(self._buffer)
1080 if not self._exhausted:
1081 for chunk in self._generator:
1082 all_data.extend(chunk)
1083 self._exhausted = True
1084 self._buffer.clear()
1085 return bytes(all_data)
1086
1087 while len(self._buffer) < size and not self._exhausted:
1088 try:
1089 chunk = next(self._generator)
1090 self._buffer.extend(chunk)
1091 except StopIteration:
1092 self._exhausted = True
1093 break
1094
1095 data = bytes(self._buffer[:size])
1096 del self._buffer[:size]
1097 return data
1098
1099
1100 class MultipartProtocol(_t.Protocol):
1101 """Protocol for multipart form-data generators.
1102
1103 This defines the public interface for multipart objects without
1104 exposing implementation details. Use this for type hints.
1105 """
1106
1107 @property
1108 def content_type(self) -> str:
1109 """Content-Type header value including boundary."""
1110
1111 def add(
1112 self,
1113 name: bytes,
1114 filename: bytes | None = None,
1115 filepath: bytes | None = None,
1116 content: bytes | None = None,
1117 cte: _CTE | None = None,
1118 ct: bytes = _DEFAULT_MIME_TYPE,
1119 ) -> None:
1120 """Add a field to the multipart body."""
1121
1122 def as_iter(self) -> _t.Generator[bytes, None, None]:
1123 """Generator yielding each multipart part as bytes, then the final boundary."""
1124
1125 def as_fp(self) -> _MultipartReader:
1126 """Return a file-like reader that streams multipart content."""
1127
1128 def as_bytes(self) -> bytes:
1129 """Return all multipart content as bytes."""
1130
1131
1132 class _Multipart:
1133 class _Part(_t.TypedDict):
1134 name: bytes
1135 filename: bytes | None
1136 filepath: bytes | None
1137 content: bytes | None
1138 cte: _CTE | None
1139 ct: bytes
1140
1141 def __init__(self) -> None:
1142 self._nl = b'\r\n'
1143 self._boundary = b'----AnsibleFormBoundary' + binascii.hexlify(os.urandom(16))
1144 self._parts: list[_Multipart._Part] = []
1145
1146 @property
1147 def content_type(self) -> str:
1148 return 'multipart/form-data; boundary=%s' % self._boundary.decode()
1149
1150 def add(
1151 self,
1152 name: bytes,
1153 filename: bytes | None = None,
1154 filepath: bytes | None = None,
1155 content: bytes | None = None,
1156 cte: _CTE | None = None,
1157 ct: bytes = _DEFAULT_MIME_TYPE,
1158 ) -> None:
1159 # deprecated: description='TypedDict Required/NotRequired for _MultipartField' python_version='3.11'
1160 if filepath and content:
1161 raise ValueError('only one of filepath or content can be supplied')
1162 if not filepath and not content:
1163 raise ValueError('one of filepath or content must be supplied')
1164 self._parts.append({
1165 'name': name,
1166 'filename': filename,
1167 'filepath': filepath,
1168 'content': content,
1169 'cte': cte,
1170 'ct': ct,
1171 })
1172
1173 def as_iter(self) -> _t.Generator[bytes, None, None]:
1174 """Generator yielding each multipart part as bytes, then the final boundary."""
1175 for part in self._parts:
1176 yield self._generate_header(part)
1177
1178 if part['cte']:
1179 if part['filepath']:
1180 with open(part['filepath'], 'rb') as f:
1181 yield from self._encode(f, part['cte'])
1182 else:
1183 yield from self._encode(io.BytesIO(part['content']), part['cte'])
1184 # encoders are expected to return their own trailing nl
1185 else:
1186 if part['filepath']:
1187 with open(part['filepath'], 'rb') as f:
1188 yield from iter(partial(f.read, _CHUNK_SIZE), b'')
1189 else:
1190 yield part['content']
1191 yield self._nl
1192
1193 yield b'--' + self._boundary + b'--' + self._nl
1194
1195 def as_fp(self) -> _MultipartReader:
1196 """Return a file-like reader that streams multipart content.
1197
1198 The returned reader supports read() and readinto() for streaming the
1199 multipart body without materializing it entirely in memory. This is
1200 useful for large file uploads (>2GB).
1201 """
1202 return _MultipartReader(self.as_iter())
1203
1204 def as_bytes(self) -> bytes:
1205 """Return all multipart content as bytes.
1206
1207 Warning: This materializes the entire multipart body in memory.
1208 For large files, use as_fp() instead to stream the content.
1209 """
1210 return self.as_fp().read()
1211
1212 def _generate_header(self, part: _Multipart._Part) -> bytes:
1213 buf = io.BytesIO()
1214 buf.write(b'--' + self._boundary + self._nl)
1215
1216 if part['cte']:
1217 buf.write(b'Content-Transfer-Encoding: ' + part['cte'] + self._nl)
1218 disposition = b'form-data; name="%s"' % part['name']
1219 if part['filename']:
1220 disposition += b'; filename="%s"' % part['filename']
1221 buf.write(b'Content-Type: ' + part['ct'] + self._nl)
1222 buf.write(b'Content-Disposition: ' + disposition + self._nl)
1223 buf.write(self._nl)
1224
1225 return buf.getvalue()
1226
1227 def _encode_base64(self, f: io.RawIOBase | io.BufferedIOBase) -> _t.Generator[bytes, None, None]:
1228 """Encode file-like object content as base64, yielding chunks."""
1229 # 57 bytes encodes to exactly 76 base64 chars (one line)
1230 for chunk in iter(partial(f.read, 57), b''):
1231 yield binascii.b2a_base64(chunk, newline=False) + self._nl
1232
1233 def _encode_passthru(self, f: io.RawIOBase | io.BufferedIOBase) -> _t.Generator[bytes, None, None]:
1234 """Read file-like object content as-is, yielding chunks."""
1235 yield from iter(partial(f.read, _CHUNK_SIZE), b'')
1236 yield self._nl
1237
1238 def _encode(self, f: io.RawIOBase | io.BufferedIOBase, cte: _CTE) -> _t.Generator[bytes, None, None]:
1239 if cte == b'base64':
1240 yield from self._encode_base64(f)
1241 else:
1242 yield from self._encode_passthru(f)
1243
1244
1245 def create_multipart(fields: _t.Mapping[str, str | _MultipartField]) -> MultipartProtocol:
1246 """Creates a ``MultipartProtocol`` instance from a fields mapping.
1247
1248 This function processes the fields mapping and returns a ``MultipartProtocol``
1249 object that can be used to generate ``multipart/form-data`` bodies.
1250 Use this function when you need streaming access to the multipart
1251 data (e.g., for large files). For most cases, use ``prepare_multipart()``
1252 instead.
1253
1254 For field format details, see ``prepare_multipart()``.
1255 """
1256
1257 if not isinstance(fields, Mapping):
1258 raise TypeError(
1259 'Mapping is required, cannot be type %s' % fields.__class__.__name__
1260 )
1261
1262 m = _Multipart()
1263 for field, value in sorted(fields.items()):
1264 if isinstance(value, str):
1265 m.add(
1266 name=to_bytes(field),
1267 content=to_bytes(value),
1268 ct=_TEXT_CONTENT_TYPE,
1269 )
1270 elif isinstance(value, Mapping):
1271 filename = value.get('filename')
1272 content = value.get('content')
1273 if not any((filename, content)):
1274 raise ValueError('at least one of filename or content must be provided')
1275
1276 mime: bytes = to_bytes(value.get('mime_type'), nonstring='passthru')
1277 if not mime:
1278 try:
1279 mime = to_bytes(
1280 mimetypes.guess_type(filename or '', strict=False)[0],
1281 nonstring='passthru'
1282 ) or _DEFAULT_MIME_TYPE
1283 except Exception:
1284 mime = _DEFAULT_MIME_TYPE
1285
1286 cte: _CTE | None
1287 if multipart_encoding := value.get('multipart_encoding'):
1288 try:
1289 cte = _EncToCTEMap[multipart_encoding]
1290 except KeyError:
1291 raise ValueError('multipart_encoding must be one of %s.' % repr(tuple(_EncToCTEMap)))
1292 else:
1293 cte = None
1294
1295 if filename and not content:
1296 b_filename = to_bytes(filename, errors='surrogate_or_strict')
1297 m.add(
1298 name=to_bytes(field),
1299 filename=os.path.basename(b_filename),
1300 filepath=b_filename,
1301 cte=cte,
1302 ct=mime,
1303 )
1304 else:
1305 m.add(
1306 name=to_bytes(field),
1307 filename=to_bytes(filename) if filename else None,
1308 content=to_bytes(content),
1309 cte=cte,
1310 ct=mime,
1311 )
1312 else:
1313 raise TypeError(
1314 'value must be a string, or mapping, cannot be type %s' % value.__class__.__name__
1315 )
1316
1317 return m
1318
1319
1320 def prepare_multipart(fields: _t.Mapping[str, str | _MultipartField]) -> tuple[str, bytes]:
1321 """Takes a mapping, and prepares a multipart/form-data body
1322
1323 Payload content from a file can optionally be encoded when
1324 ``multipart_encoding`` is set to 'base64' or '7or8bit'. Without
1325 encoding specified, files are sent as-is (binary). The appropriate
1326 ``Content-Transfer-Encoding`` and ``Content-Type`` headers will be
1327 included.
1328
1329 Example:
1330 {
1331 "file1": {
1332 "filename": "/bin/true",
1333 "mime_type": "application/octet-stream"
1334 },
1335 "file2": {
1336 "content": "text based file content",
1337 "filename": "fake.txt",
1338 "mime_type": "text/plain",
1339 },
1340 "text_form_field": "value"
1341 }
1342 """
1343 m = create_multipart(fields)
1344 return m.content_type, m.as_bytes()
1345
1346
1347 #
1348 # Module-related functions
1349 #
1350
1351 def basic_auth_header(username, password):
1352 """Takes a username and password and returns a byte string suitable for
1353 using as value of an Authorization header to do basic auth.
1354 """
1355 if password is None:
1356 password = ''
1357 return b"Basic %s" % base64.b64encode(to_bytes("%s:%s" % (username, password), errors='surrogate_or_strict'))
1358
1359
1360 def url_argument_spec():
1361 """
1362 Creates an argument spec that can be used with any module
1363 that will be requesting content via urllib/urllib2
1364 """
1365 return dict(
1366 url=dict(type='str'),
1367 force=dict(type='bool', default=False),
1368 http_agent=dict(type='str', default='ansible-httpget'),
1369 use_proxy=dict(type='bool', default=True),
1370 validate_certs=dict(type='bool', default=True),
1371 url_username=dict(type='str'),
1372 url_password=dict(type='str', no_log=True),
1373 force_basic_auth=dict(type='bool', default=False),
1374 client_cert=dict(type='path'),
1375 client_key=dict(type='path'),
1376 use_gssapi=dict(type='bool', default=False),
1377 )
1378
1379
1380 def url_redirect_argument_spec():
1381 """
1382 Creates an addition argument spec to `url_argument_spec`
1383 for `follow_redirects` argument
1384 """
1385 return dict(
1386 follow_redirects=dict(type='str', default='safe', choices=['all', 'none', 'safe', 'urllib2']),
1387 )
1388
1389
1390 def fetch_url(module, url, data=None, headers=None, method=None,
1391 use_proxy=None, force=False, last_mod_time=None, timeout=10,
1392 use_gssapi=False, unix_socket=None, ca_path=None, cookies=None, unredirected_headers=None,
1393 decompress=True, ciphers=None, use_netrc=True):
1394 """Sends a request via HTTP(S) or FTP (needs the module as parameter)
1395
1396 :arg module: The AnsibleModule (used to get username, password etc. (s.b.).
1397 :arg url: The url to use.
1398
1399 :kwarg data: The data to be sent (in case of POST/PUT).
1400 :kwarg headers: A dict with the request headers.
1401 :kwarg method: "POST", "PUT", etc.
1402 :kwarg use_proxy: (optional) whether or not to use proxy (Default: True)
1403 :kwarg boolean force: If True: Do not get a cached copy (Default: False)
1404 :kwarg last_mod_time: Default: None
1405 :kwarg int timeout: Default: 10
1406 :kwarg boolean use_gssapi: Default: False
1407 :kwarg unix_socket: (optional) String of file system path to unix socket file to use when establishing
1408 connection to the provided url
1409 :kwarg ca_path: (optional) String of file system path to CA cert bundle to use
1410 :kwarg cookies: (optional) CookieJar object to send with the request
1411 :kwarg unredirected_headers: (optional) A list of headers to not attach on a redirected request
1412 :kwarg decompress: (optional) Whether to attempt to decompress gzip content-encoded responses
1413 :kwarg cipher: (optional) List of ciphers to use
1414 :kwarg boolean use_netrc: (optional) If False: Ignores login and password in ~/.netrc file (Default: True)
1415
1416 :returns: A tuple of (**response**, **info**). Use ``response.read()`` to read the data.
1417 The **info** contains the 'status' and other meta data. When a HttpError (status >= 400)
1418 occurred then ``info['body']`` contains the error response data::
1419
1420 Example::
1421
1422 data={...}
1423 resp, info = fetch_url(module,
1424 "http://example.com",
1425 data=json.dumps(data),
1426 headers={'Content-type': 'application/json'},
1427 method="POST")
1428 status_code = info["status"]
1429 body = resp.read()
1430 if status_code >= 400 :
1431 body = info['body']
1432 """
1433
1434 if not HAS_GZIP:
1435 module.fail_json(msg=GzipDecodedReader.missing_gzip_error())
1436
1437 # ensure we use proper tempdir
1438 old_tempdir = tempfile.tempdir
1439 tempfile.tempdir = module.tmpdir
1440
1441 # Get validate_certs from the module params
1442 validate_certs = module.params.get('validate_certs', True)
1443
1444 if use_proxy is None:
1445 use_proxy = module.params.get('use_proxy', True)
1446
1447 username = module.params.get('url_username', '')
1448 password = module.params.get('url_password', '')
1449 http_agent = module.params.get('http_agent', get_user_agent())
1450 force_basic_auth = module.params.get('force_basic_auth', '')
1451
1452 follow_redirects = module.params.get('follow_redirects', 'urllib2')
1453
1454 client_cert = module.params.get('client_cert')
1455 client_key = module.params.get('client_key')
1456 use_gssapi = module.params.get('use_gssapi', use_gssapi)
1457
1458 if not isinstance(cookies, cookiejar.CookieJar):
1459 cookies = cookiejar.CookieJar()
1460
1461 r = None
1462 info = dict(url=mask_url(url), status=-1)
1463 try:
1464 r = open_url(url, data=data, headers=headers, method=method,
1465 use_proxy=use_proxy, force=force, last_mod_time=last_mod_time, timeout=timeout,
1466 validate_certs=validate_certs, url_username=username,
1467 url_password=password, http_agent=http_agent, force_basic_auth=force_basic_auth,
1468 follow_redirects=follow_redirects, client_cert=client_cert,
1469 client_key=client_key, cookies=cookies, use_gssapi=use_gssapi,
1470 unix_socket=unix_socket, ca_path=ca_path, unredirected_headers=unredirected_headers,
1471 decompress=decompress, ciphers=ciphers, use_netrc=use_netrc)
1472 # Lowercase keys, to conform to py2 behavior
1473 info.update({k.lower(): v for k, v in r.info().items()})
1474
1475 # Don't be lossy, append header values for duplicate headers
1476 temp_headers = {}
1477 for name, value in r.headers.items():
1478 # The same as above, lower case keys to match py2 behavior, and create more consistent results
1479 name = name.lower()
1480 if name in temp_headers:
1481 temp_headers[name] = ', '.join((temp_headers[name], value))
1482 else:
1483 temp_headers[name] = value
1484 info.update(temp_headers)
1485
1486 # parse the cookies into a nice dictionary
1487 cookie_list = []
1488 cookie_dict = {}
1489 # Python sorts cookies in order of most specific (ie. longest) path first. See ``CookieJar._cookie_attrs``
1490 # Cookies with the same path are reversed from response order.
1491 # This code makes no assumptions about that, and accepts the order given by python
1492 for cookie in cookies:
1493 cookie_dict[cookie.name] = cookie.value
1494 cookie_list.append((cookie.name, cookie.value))
1495 info['cookies_string'] = '; '.join('%s=%s' % c for c in cookie_list)
1496
1497 info['cookies'] = cookie_dict
1498 # finally update the result with a message about the fetch
1499 info.update(dict(msg="OK (%s bytes)" % r.headers.get('Content-Length', 'unknown'), url=mask_url(r.geturl()), status=r.code))
1500 except (ConnectionError, ValueError) as e:
1501 module.fail_json(msg=to_native(e), **info)
1502 except MissingModuleError as e:
1503 module.fail_json(msg=to_text(e))
1504 except urllib.error.HTTPError as e:
1505 r = e
1506 try:
1507 if e.fp is None:
1508 # Certain HTTPError objects may not have the ability to call ``.read()`` on Python 3
1509 # This is not handled gracefully in Python 3, and instead an exception is raised from
1510 # tempfile, due to ``urllib.response.addinfourl`` not being initialized
1511 raise AttributeError
1512 body = e.read()
1513 except AttributeError:
1514 body = ''
1515 else:
1516 e.close()
1517
1518 # Try to add exception info to the output but don't fail if we can't
1519 try:
1520 # Lowercase keys, to conform to py2 behavior, so that py3 and py2 are predictable
1521 info.update({k.lower(): v for k, v in e.info().items()})
1522 except Exception:
1523 pass
1524
1525 info.update({'msg': to_native(e), 'body': body, 'status': e.code})
1526
1527 except urllib.error.URLError as e:
1528 code = int(getattr(e, 'code', -1))
1529 info.update(dict(msg="Request failed: %s" % to_native(e), status=code))
1530 except OSError as ex:
1531 info.update(dict(msg=f"Connection failure: {ex}", status=-1))
1532 except http.client.BadStatusLine as e:
1533 info.update(dict(msg="Connection failure: connection was closed before a valid response was received: %s" % to_native(e.line), status=-1))
1534 except Exception as ex:
1535 info.update(dict(msg="An unknown error occurred: %s" % to_native(ex), status=-1, exception=traceback.format_exc()))
1536 finally:
1537 tempfile.tempdir = old_tempdir
1538
1539 return r, info
1540
1541
1542 def is_fetch_success(info: dict, additional_codes: list = None) -> bool:
1543 """Determine if a fetch_url response is successful independent of the protocol.
1544 :arg info: info dictionary returned from fetch_url
1545
1546 :kwarg additional_codes: (Optional) List of additional status codes that will be considered a success"""
1547
1548 status = info.get('status', -1)
1549 url = info.get('url', '').lower()
1550
1551 # Allow user to override with specific codes
1552 if additional_codes and status in additional_codes:
1553 return True
1554
1555 # General failure
1556 if status == -1:
1557 return False
1558
1559 if url.startswith('http'):
1560 return status == 200
1561 if url.startswith('ftp'):
1562 return status is None
1563
1564 # Should never reach here, assume it behaves like http and ftp
1565 return status == 200 or status is None
1566
1567
1568 def _suffixes(name):
1569 """A list of the final component's suffixes, if any."""
1570 if name.endswith('.'):
1571 return []
1572 name = name.lstrip('.')
1573 return ['.' + s for s in name.split('.')[1:]]
1574
1575
1576 def _split_multiext(name, min=3, max=4, count=2):
1577 """Split a multi-part extension from a file name.
1578
1579 Returns '([name minus extension], extension)'.
1580
1581 Define the valid extension length (including the '.') with 'min' and 'max',
1582 'count' sets the number of extensions, counting from the end, to evaluate.
1583 Evaluation stops on the first file extension that is outside the min and max range.
1584
1585 If no valid extensions are found, the original ``name`` is returned
1586 and ``extension`` is empty.
1587
1588 :arg name: File name or path.
1589 :kwarg min: Minimum length of a valid file extension.
1590 :kwarg max: Maximum length of a valid file extension.
1591 :kwarg count: Number of suffixes from the end to evaluate.
1592
1593 """
1594 extension = ''
1595 for i, sfx in enumerate(reversed(_suffixes(name))):
1596 if i >= count:
1597 break
1598
1599 if min <= len(sfx) <= max:
1600 extension = '%s%s' % (sfx, extension)
1601 name = name.rstrip(sfx)
1602 else:
1603 # Stop on the first invalid extension
1604 break
1605
1606 return name, extension
1607
1608
1609 def fetch_file(module, url, data=None, headers=None, method=None,
1610 use_proxy=True, force=False, last_mod_time=None, timeout=10,
1611 unredirected_headers=None, decompress=True, ciphers=None,
1612 ca_path=None, cookies=None):
1613 """Download and save a file via HTTP(S) or FTP (needs the module as parameter).
1614 This is basically a wrapper around fetch_url().
1615
1616 :arg module: The AnsibleModule (used to get username, password etc. (s.b.).
1617 :arg url: The url to use.
1618
1619 :kwarg data: The data to be sent (in case of POST/PUT).
1620 :kwarg headers: A dict with the request headers.
1621 :kwarg method: "POST", "PUT", etc.
1622 :kwarg boolean use_proxy: Default: True
1623 :kwarg boolean force: If True: Do not get a cached copy (Default: False)
1624 :kwarg last_mod_time: Default: None
1625 :kwarg int timeout: Default: 10
1626 :kwarg unredirected_headers: (optional) A list of headers to not attach on a redirected request
1627 :kwarg decompress: (optional) Whether to attempt to decompress gzip content-encoded responses
1628 :kwarg ciphers: (optional) List of ciphers to use
1629 :kwarg ca_path: (optional) Path to CA bundle
1630 :kwarg cookies: (optional) CookieJar object to send with the request
1631
1632 :returns: A string, the path to the downloaded file.
1633 """
1634 # download file
1635 bufsize = _CHUNK_SIZE
1636 parts = urlparse(url)
1637 file_prefix, file_ext = _split_multiext(os.path.basename(parts.path), count=2)
1638 fetch_temp_file = tempfile.NamedTemporaryFile(dir=module.tmpdir, prefix=file_prefix, suffix=file_ext, delete=False)
1639 module.add_cleanup_file(fetch_temp_file.name)
1640 try:
1641 rsp, info = fetch_url(module, url, data, headers, method, use_proxy, force, last_mod_time, timeout,
1642 unredirected_headers=unredirected_headers, decompress=decompress, ciphers=ciphers,
1643 ca_path=ca_path, cookies=cookies)
1644 if not rsp or (rsp.code and rsp.code >= 400):
1645 module.fail_json(msg="Failure downloading %s, %s" % (mask_url(url), info['msg']))
1646 data = rsp.read(bufsize)
1647 while data:
1648 fetch_temp_file.write(data)
1649 data = rsp.read(bufsize)
1650 fetch_temp_file.close()
1651 except Exception as e:
1652 module.fail_json(msg="Failure downloading %s, %s" % (mask_url(url), to_native(e)))
1653 return fetch_temp_file.name
1654
1655
1656 def get_user_agent():
1657 """Returns a user agent used by open_url"""
1658 return u"ansible-httpget"