blob: 9846d24f2668476d8fa10fa46745edb588294854 [file] [log] [blame]
David Pursehouse8898e2f2012-11-14 07:51:03 +09001#!/usr/bin/env python
Mike Frysingerf6013762019-06-13 02:30:51 -04002# -*- coding:utf-8 -*-
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07003#
4# Copyright (C) 2008 The Android Open Source Project
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17
Mike Frysinger87fb5a12019-06-13 01:54:46 -040018"""The repo tool.
19
20People shouldn't run this directly; instead, they should use the `repo` wrapper
21which takes care of execing this entry point.
22"""
23
Sarah Owenscecd1d82012-11-01 22:59:27 -070024from __future__ import print_function
JoonCheol Parke9860722012-10-11 02:31:44 +090025import getpass
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070026import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070027import optparse
28import os
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070029import sys
Mike Frysinger7c321f12019-12-02 16:49:44 -050030import textwrap
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070031import time
David Pursehouse59bbb582013-05-17 10:49:33 +090032
33from pyversion import is_python3
34if is_python3():
Sarah Owens1f7627f2012-10-31 09:21:55 -070035 import urllib.request
36else:
Rashed Abdel-Tawab2058c632019-10-05 00:18:41 -040037 import imp
David Pursehouse59bbb582013-05-17 10:49:33 +090038 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -070039 urllib = imp.new_module('urllib')
40 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070041
Carlos Aguado1242e602014-02-03 13:48:47 +010042try:
43 import kerberos
44except ImportError:
45 kerberos = None
46
Mike Frysinger902665b2014-12-22 15:17:59 -050047from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070048import event_log
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040049from repo_trace import SetTrace
David Pursehouse9090e802020-02-12 11:25:13 +090050from git_command import user_agent
Doug Anderson0048b692010-12-21 13:39:23 -080051from git_config import init_ssh, close_ssh
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080052from command import InteractiveCommand
53from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070054from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080055from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070056from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070057from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070058from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080059from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090060from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080061from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070062from error import NoSuchProjectError
63from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070064import gitc_utils
65from manifest_xml import GitcManifest, XmlManifest
Renaud Paquaye8595e92016-11-01 15:51:59 -070066from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080067from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070068
David Pursehouse5c6eeac2012-10-11 16:44:48 +090069from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070070
David Pursehouse59bbb582013-05-17 10:49:33 +090071if not is_python3():
David Pursehousea46bf7d2020-02-15 12:45:53 +090072 input = raw_input # noqa: F821
Chirayu Desai217ea7d2013-03-01 19:14:38 +053073
Mike Frysinger37f28f12020-02-16 15:15:53 -050074# NB: These do not need to be kept in sync with the repo launcher script.
75# These may be much newer as it allows the repo launcher to roll between
76# different repo releases while source versions might require a newer python.
77#
78# The soft version is when we start warning users that the version is old and
79# we'll be dropping support for it. We'll refuse to work with versions older
80# than the hard version.
81#
82# python-3.6 is in Ubuntu Bionic.
83MIN_PYTHON_VERSION_SOFT = (3, 6)
84MIN_PYTHON_VERSION_HARD = (3, 4)
85
86if sys.version_info.major < 3:
87 print('repo: warning: Python 2 is no longer supported; '
88 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
89 file=sys.stderr)
90else:
91 if sys.version_info < MIN_PYTHON_VERSION_HARD:
92 print('repo: error: Python 3 version is too old; '
93 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
94 file=sys.stderr)
95 sys.exit(1)
96 elif sys.version_info < MIN_PYTHON_VERSION_SOFT:
97 print('repo: warning: your Python 3 version is no longer supported; '
98 'Please upgrade to Python {}.{}+.'.format(*MIN_PYTHON_VERSION_SOFT),
99 file=sys.stderr)
100
101
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700102global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -0500103 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
104 add_help_option=False)
105global_options.add_option('-h', '--help', action='store_true',
106 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700107global_options.add_option('-p', '--paginate',
108 dest='pager', action='store_true',
109 help='display command output in the pager')
110global_options.add_option('--no-pager',
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500111 dest='pager', action='store_false',
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700112 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -0500113global_options.add_option('--color',
114 choices=('auto', 'always', 'never'), default=None,
115 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700116global_options.add_option('--trace',
117 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -0400118 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -0400119global_options.add_option('--trace-python',
120 dest='trace_python', action='store_true',
121 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -0700122global_options.add_option('--time',
123 dest='time', action='store_true',
124 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800125global_options.add_option('--version',
126 dest='show_version', action='store_true',
127 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700128global_options.add_option('--event-log',
129 dest='event_log', action='store',
130 help='filename of event log to append timeline to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700131
David Pursehouse819827a2020-02-12 15:20:19 +0900132
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700133class _Repo(object):
134 def __init__(self, repodir):
135 self.repodir = repodir
136 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -0400137 # add 'branch' as an alias for 'branches'
138 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139
Mike Frysinger3fc15722019-08-27 00:36:46 -0400140 def _ParseArgs(self, argv):
141 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700142 name = None
143 glob = []
144
Sarah Owensa6053d52012-11-01 13:36:50 -0700145 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700146 if not argv[i].startswith('-'):
147 name = argv[i]
148 if i > 0:
149 glob = argv[:i]
150 argv = argv[i + 1:]
151 break
152 if not name:
153 glob = argv
154 name = 'help'
155 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900156 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700157
Mike Frysinger7c321f12019-12-02 16:49:44 -0500158 if gopts.help:
159 global_options.print_help()
160 commands = ' '.join(sorted(self.commands))
161 wrapped_commands = textwrap.wrap(commands, width=77)
162 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
163 print('\nRun `repo help <command>` for command-specific details.')
164 global_options.exit()
165
Mike Frysinger3fc15722019-08-27 00:36:46 -0400166 return (name, gopts, argv)
167
168 def _Run(self, name, gopts, argv):
169 """Execute the requested subcommand."""
170 result = 0
171
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700172 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700173 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800174 if gopts.show_version:
175 if name == 'help':
176 name = 'version'
177 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700178 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400179 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800180
Mike Frysinger902665b2014-12-22 15:17:59 -0500181 SetDefaultColoring(gopts.color)
182
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700183 try:
184 cmd = self.commands[name]
185 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700186 print("repo: '%s' is not a repo command. See 'repo help'." % name,
187 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400188 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700189
190 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700191 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700192 cmd.gitc_manifest = None
193 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
194 if gitc_client_name:
195 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
196 cmd.manifest.isGitcClient = True
197
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700198 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800200 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700201 print("fatal: '%s' requires a working directory" % name,
202 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400203 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800204
Dan Willemsen79360642015-08-31 15:45:06 -0700205 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700206 print("fatal: '%s' requires GITC to be available" % name,
207 file=sys.stderr)
208 return 1
209
Dan Willemsen79360642015-08-31 15:45:06 -0700210 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
211 print("fatal: '%s' requires a GITC client" % name,
212 file=sys.stderr)
213 return 1
214
Dan Sandler53e902a2014-03-09 13:20:02 -0400215 try:
216 copts, cargs = cmd.OptionParser.parse_args(argv)
217 copts = cmd.ReadEnvironmentOptions(copts)
218 except NoManifestException as e:
219 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900220 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400221 print('error: manifest missing or unreadable -- please run init',
222 file=sys.stderr)
223 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700224
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500225 if gopts.pager and not isinstance(cmd, InteractiveCommand):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700226 config = cmd.manifest.globalConfig
227 if gopts.pager:
228 use_pager = True
229 else:
230 use_pager = config.GetBoolean('pager.%s' % name)
231 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700232 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700233 if use_pager:
234 RunPager(config)
235
Conley Owens7ba25be2012-11-14 14:18:06 -0800236 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700237 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
238 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700239 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400240 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800241 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400242 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900243 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400244 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900245 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400246 if isinstance(e, NoManifestException):
247 print('error: manifest missing or unreadable -- please run init',
248 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800249 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700250 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700251 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700252 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700253 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700254 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800255 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700256 except InvalidProjectGroupsError as e:
257 if e.name:
258 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
259 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900260 print('error: project group must be enabled for the project in the current directory',
261 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700262 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700263 except SystemExit as e:
264 if e.code:
265 result = e.code
266 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800267 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700268 finish = time.time()
269 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800270 hours, remainder = divmod(elapsed, 3600)
271 minutes, seconds = divmod(remainder, 60)
272 if gopts.time:
273 if hours == 0:
274 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
275 else:
276 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
277 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400278
David Rileye0684ad2017-04-05 00:02:59 -0700279 cmd.event_log.FinishEvent(cmd_event, finish,
280 result is None or result == 0)
281 if gopts.event_log:
282 cmd.event_log.Write(os.path.abspath(
283 os.path.expanduser(gopts.event_log)))
284
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400285 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286
Conley Owens094cdbe2014-01-30 15:09:59 -0800287
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500288def _CheckWrapperVersion(ver_str, repo_path):
289 """Verify the repo launcher is new enough for this checkout.
290
291 Args:
292 ver_str: The version string passed from the repo launcher when it ran us.
293 repo_path: The path to the repo launcher that loaded us.
294 """
295 # Refuse to work with really old wrapper versions. We don't test these,
296 # so might as well require a somewhat recent sane version.
297 # v1.15 of the repo launcher was released in ~Mar 2012.
298 MIN_REPO_VERSION = (1, 15)
299 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
300
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700301 if not repo_path:
302 repo_path = '~/bin/repo'
303
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500304 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700305 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900306 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700307
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500308 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800309 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500310 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700311
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900312 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500313 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700314 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500315repo: error:
316!!! Your version of repo %s is too old.
317!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900318!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500319!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320
321 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500322""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700323 sys.exit(1)
324
325 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700326 print("""
David Pursehouse3c5114c2020-02-13 09:55:59 +0900327... A new version of repo (%s) is available.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700328... You should upgrade soon:
329
330 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800331""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700332
David Pursehouse819827a2020-02-12 15:20:19 +0900333
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200334def _CheckRepoDir(repo_dir):
335 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700336 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900337 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700338
David Pursehouse819827a2020-02-12 15:20:19 +0900339
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700340def _PruneOptions(argv, opt):
341 i = 0
342 while i < len(argv):
343 a = argv[i]
344 if a == '--':
345 break
346 if a.startswith('--'):
347 eq = a.find('=')
348 if eq > 0:
349 a = a[0:eq]
350 if not opt.has_option(a):
351 del argv[i]
352 continue
353 i += 1
354
David Pursehouse819827a2020-02-12 15:20:19 +0900355
Sarah Owens1f7627f2012-10-31 09:21:55 -0700356class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700357 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400358 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700359 return req
360
361 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400362 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700363 return req
364
David Pursehouse819827a2020-02-12 15:20:19 +0900365
JoonCheol Parke9860722012-10-11 02:31:44 +0900366def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900367 # If repo could not find auth info from netrc, try to get it from user input
368 url = req.get_full_url()
369 user, password = handler.passwd.find_user_password(None, url)
370 if user is None:
371 print(msg)
372 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530373 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900374 password = getpass.getpass()
375 except KeyboardInterrupt:
376 return
377 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900378
David Pursehouse819827a2020-02-12 15:20:19 +0900379
Sarah Owens1f7627f2012-10-31 09:21:55 -0700380class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900381 def http_error_401(self, req, fp, code, msg, headers):
382 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700383 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900384 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900385
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700386 def http_error_auth_reqed(self, authreq, host, req, headers):
387 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700388 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900389
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700390 def _add_header(name, val):
391 val = val.replace('\n', '')
392 old_add_header(name, val)
393 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700394 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900395 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900396 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700397 reset = getattr(self, 'reset_retry_count', None)
398 if reset is not None:
399 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700400 elif getattr(self, 'retried', None):
401 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700402 raise
403
David Pursehouse819827a2020-02-12 15:20:19 +0900404
Sarah Owens1f7627f2012-10-31 09:21:55 -0700405class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900406 def http_error_401(self, req, fp, code, msg, headers):
407 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700408 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900409 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900410
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800411 def http_error_auth_reqed(self, auth_header, host, req, headers):
412 try:
413 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900414
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800415 def _add_header(name, val):
416 val = val.replace('\n', '')
417 old_add_header(name, val)
418 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700419 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900420 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900421 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800422 reset = getattr(self, 'reset_retry_count', None)
423 if reset is not None:
424 reset()
425 elif getattr(self, 'retried', None):
426 self.retried = 0
427 raise
428
David Pursehouse819827a2020-02-12 15:20:19 +0900429
Carlos Aguado1242e602014-02-03 13:48:47 +0100430class _KerberosAuthHandler(urllib.request.BaseHandler):
431 def __init__(self):
432 self.retried = 0
433 self.context = None
434 self.handler_order = urllib.request.BaseHandler.handler_order - 50
435
David Pursehouse65b0ba52018-06-24 16:21:51 +0900436 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100437 host = req.get_host()
438 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
439 return retry
440
441 def http_error_auth_reqed(self, auth_header, host, req, headers):
442 try:
443 spn = "HTTP@%s" % host
444 authdata = self._negotiate_get_authdata(auth_header, headers)
445
446 if self.retried > 3:
447 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900448 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100449 else:
450 self.retried += 1
451
452 neghdr = self._negotiate_get_svctk(spn, authdata)
453 if neghdr is None:
454 return None
455
456 req.add_unredirected_header('Authorization', neghdr)
457 response = self.parent.open(req)
458
459 srvauth = self._negotiate_get_authdata(auth_header, response.info())
460 if self._validate_response(srvauth):
461 return response
462 except kerberos.GSSError:
463 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900464 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100465 self.reset_retry_count()
466 raise
467 finally:
468 self._clean_context()
469
470 def reset_retry_count(self):
471 self.retried = 0
472
473 def _negotiate_get_authdata(self, auth_header, headers):
474 authhdr = headers.get(auth_header, None)
475 if authhdr is not None:
476 for mech_tuple in authhdr.split(","):
477 mech, __, authdata = mech_tuple.strip().partition(" ")
478 if mech.lower() == "negotiate":
479 return authdata.strip()
480 return None
481
482 def _negotiate_get_svctk(self, spn, authdata):
483 if authdata is None:
484 return None
485
486 result, self.context = kerberos.authGSSClientInit(spn)
487 if result < kerberos.AUTH_GSS_COMPLETE:
488 return None
489
490 result = kerberos.authGSSClientStep(self.context, authdata)
491 if result < kerberos.AUTH_GSS_CONTINUE:
492 return None
493
494 response = kerberos.authGSSClientResponse(self.context)
495 return "Negotiate %s" % response
496
497 def _validate_response(self, authdata):
498 if authdata is None:
499 return None
500 result = kerberos.authGSSClientStep(self.context, authdata)
501 if result == kerberos.AUTH_GSS_COMPLETE:
502 return True
503 return None
504
505 def _clean_context(self):
506 if self.context is not None:
507 kerberos.authGSSClientClean(self.context)
508 self.context = None
509
David Pursehouse819827a2020-02-12 15:20:19 +0900510
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700511def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700512 handlers = [_UserAgentHandler()]
513
Sarah Owens1f7627f2012-10-31 09:21:55 -0700514 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700515 try:
516 n = netrc.netrc()
517 for host in n.hosts:
518 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900519 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800520 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700521 except netrc.NetrcParseError:
522 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700523 except IOError:
524 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700525 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800526 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100527 if kerberos:
528 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700529
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700530 if 'http_proxy' in os.environ:
531 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700532 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700533 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700534 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
535 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
536 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700537
David Pursehouse819827a2020-02-12 15:20:19 +0900538
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400540 result = 0
541
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700542 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
543 opt.add_option("--repo-dir", dest="repodir",
544 help="path to .repo/")
545 opt.add_option("--wrapper-version", dest="wrapper_version",
546 help="version of the wrapper script")
547 opt.add_option("--wrapper-path", dest="wrapper_path",
548 help="location of the wrapper script")
549 _PruneOptions(argv, opt)
550 opt, argv = opt.parse_args(argv)
551
552 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
553 _CheckRepoDir(opt.repodir)
554
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800555 Version.wrapper_version = opt.wrapper_version
556 Version.wrapper_path = opt.wrapper_path
557
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700558 repo = _Repo(opt.repodir)
559 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700560 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800561 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700562 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400563 name, gopts, argv = repo._ParseArgs(argv)
564 run = lambda: repo._Run(name, gopts, argv) or 0
565 if gopts.trace_python:
566 import trace
567 tracer = trace.Trace(count=False, trace=True, timing=True,
568 ignoredirs=set(sys.path[1:]))
569 result = tracer.runfunc(run)
570 else:
571 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700572 finally:
573 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700574 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700575 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400576 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900577 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700578 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900579 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700580 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800581 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700582 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800583 argv = list(sys.argv)
584 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700585 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800586 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700587 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700588 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
589 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400590 result = 128
591
Renaud Paquaye8595e92016-11-01 15:51:59 -0700592 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400593 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700594
David Pursehouse819827a2020-02-12 15:20:19 +0900595
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700596if __name__ == '__main__':
597 _Main(sys.argv[1:])