Debian Codegraph @

src/buildstream_plugins/sources/_utils.py

raw
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 #
15 # Mostly copied from downloadablefilesource.py in buildstream.
16 #
17
18 import contextlib
19 import shutil
20 import os
21 import netrc
22 import urllib.parse
23 import urllib.request
24 import urllib.error
25
26
27 class _NetrcPasswordManager:
28 def __init__(self, netrc_config):
29 self.netrc = netrc_config
30
31 def add_password(self, realm, uri, user, passwd):
32 pass
33
34 def find_user_password(self, realm, authuri):
35 if not self.netrc:
36 return None, None
37 parts = urllib.parse.urlsplit(authuri)
38 entry = self.netrc.authenticators(parts.hostname)
39 if not entry:
40 return None, None
41 else:
42 login, _, password = entry
43 return login, password
44
45
46 def _parse_netrc():
47 netrc_config = None
48 try:
49 netrc_config = netrc.netrc()
50 except (OSError, netrc.NetrcParseError):
51 # If the .netrc file was not found, FileNotFoundError will be
52 # raised, but OSError will be raised directly by the netrc package
53 # in the case that $HOME is not set.
54 #
55 # This will catch both cases.
56 pass
57
58 return netrc_config
59
60
61 class _UrlOpenerCreator:
62 def __init__(self, netrc_config):
63 self.netrc_config = netrc_config
64
65 def get_url_opener(self, bearer_auth):
66 if self.netrc_config and not bearer_auth:
67 netrc_pw_mgr = _NetrcPasswordManager(self.netrc_config)
68 http_auth = urllib.request.HTTPBasicAuthHandler(netrc_pw_mgr)
69 return urllib.request.build_opener(http_auth)
70 return urllib.request.build_opener()
71
72
73 def download_file(url, etag, directory, auth_scheme):
74 opener_creator = _UrlOpenerCreator(_parse_netrc())
75 opener = opener_creator.get_url_opener(auth_scheme == "bearer")
76 default_name = os.path.basename(url)
77 request = urllib.request.Request(url)
78 request.add_header("Accept", "*/*")
79 request.add_header("User-Agent", "BuildStream/2")
80
81 if opener_creator.netrc_config and auth_scheme == "bearer":
82 parts = urllib.parse.urlsplit(url)
83 entry = opener_creator.netrc_config.authenticators(parts.hostname)
84 if entry:
85 _, _, password = entry
86 auth_header = "Bearer " + password
87 request.add_header("Authorization", auth_header)
88
89 if etag is not None:
90 request.add_header("If-None-Match", etag)
91
92 try:
93 with contextlib.closing(opener.open(request)) as response:
94 info = response.info()
95
96 # some servers don't honor the 'If-None-Match' header
97 if etag and info["ETag"] == etag:
98 return None, None, None
99
100 etag = info["ETag"]
101 length = info.get("Content-Length")
102
103 filename = info.get_filename(default_name)
104 filename = os.path.basename(filename)
105 local_file = os.path.join(directory, filename)
106 with open(local_file, "wb") as dest:
107 shutil.copyfileobj(response, dest)
108
109 actual_length = dest.tell()
110 if length and actual_length < int(length):
111 raise ValueError(f"Partial file {actual_length}/{length}")
112
113 except urllib.error.HTTPError as e:
114 if e.code == 304:
115 # 304 Not Modified.
116 # Because we use etag only for matching ref, currently specified ref is what
117 # we would have downloaded.
118 return None, None, None
119
120 return None, None, str(e)
121 except (urllib.error.URLError, OSError, ValueError) as e:
122 # Note that urllib.request.Request in the try block may throw a
123 # ValueError for unknown url types, so we handle it here.
124 return None, None, str(e)
125
126 return local_file, etag, None