blob: 3efb1c358bd595dfc9a04688528a150a818eb757 [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
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070074global_options = optparse.OptionParser(
Mike Frysinger7c321f12019-12-02 16:49:44 -050075 usage='repo [-p|--paginate|--no-pager] COMMAND [ARGS]',
76 add_help_option=False)
77global_options.add_option('-h', '--help', action='store_true',
78 help='show this help message and exit')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070079global_options.add_option('-p', '--paginate',
80 dest='pager', action='store_true',
81 help='display command output in the pager')
82global_options.add_option('--no-pager',
83 dest='no_pager', action='store_true',
84 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -050085global_options.add_option('--color',
86 choices=('auto', 'always', 'never'), default=None,
87 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070088global_options.add_option('--trace',
89 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040090 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -040091global_options.add_option('--trace-python',
92 dest='trace_python', action='store_true',
93 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070094global_options.add_option('--time',
95 dest='time', action='store_true',
96 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080097global_options.add_option('--version',
98 dest='show_version', action='store_true',
99 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -0700100global_options.add_option('--event-log',
101 dest='event_log', action='store',
102 help='filename of event log to append timeline to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700103
David Pursehouse819827a2020-02-12 15:20:19 +0900104
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700105class _Repo(object):
106 def __init__(self, repodir):
107 self.repodir = repodir
108 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -0400109 # add 'branch' as an alias for 'branches'
110 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700111
Mike Frysinger3fc15722019-08-27 00:36:46 -0400112 def _ParseArgs(self, argv):
113 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114 name = None
115 glob = []
116
Sarah Owensa6053d52012-11-01 13:36:50 -0700117 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118 if not argv[i].startswith('-'):
119 name = argv[i]
120 if i > 0:
121 glob = argv[:i]
122 argv = argv[i + 1:]
123 break
124 if not name:
125 glob = argv
126 name = 'help'
127 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900128 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700129
Mike Frysinger7c321f12019-12-02 16:49:44 -0500130 if gopts.help:
131 global_options.print_help()
132 commands = ' '.join(sorted(self.commands))
133 wrapped_commands = textwrap.wrap(commands, width=77)
134 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
135 print('\nRun `repo help <command>` for command-specific details.')
136 global_options.exit()
137
Mike Frysinger3fc15722019-08-27 00:36:46 -0400138 return (name, gopts, argv)
139
140 def _Run(self, name, gopts, argv):
141 """Execute the requested subcommand."""
142 result = 0
143
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700144 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700145 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800146 if gopts.show_version:
147 if name == 'help':
148 name = 'version'
149 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700150 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400151 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800152
Mike Frysinger902665b2014-12-22 15:17:59 -0500153 SetDefaultColoring(gopts.color)
154
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700155 try:
156 cmd = self.commands[name]
157 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700158 print("repo: '%s' is not a repo command. See 'repo help'." % name,
159 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400160 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700161
162 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700163 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700164 cmd.gitc_manifest = None
165 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
166 if gitc_client_name:
167 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
168 cmd.manifest.isGitcClient = True
169
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700170 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700171
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800172 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700173 print("fatal: '%s' requires a working directory" % name,
174 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400175 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800176
Dan Willemsen79360642015-08-31 15:45:06 -0700177 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700178 print("fatal: '%s' requires GITC to be available" % name,
179 file=sys.stderr)
180 return 1
181
Dan Willemsen79360642015-08-31 15:45:06 -0700182 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
183 print("fatal: '%s' requires a GITC client" % name,
184 file=sys.stderr)
185 return 1
186
Dan Sandler53e902a2014-03-09 13:20:02 -0400187 try:
188 copts, cargs = cmd.OptionParser.parse_args(argv)
189 copts = cmd.ReadEnvironmentOptions(copts)
190 except NoManifestException as e:
191 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900192 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400193 print('error: manifest missing or unreadable -- please run init',
194 file=sys.stderr)
195 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700196
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700197 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
198 config = cmd.manifest.globalConfig
199 if gopts.pager:
200 use_pager = True
201 else:
202 use_pager = config.GetBoolean('pager.%s' % name)
203 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700204 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700205 if use_pager:
206 RunPager(config)
207
Conley Owens7ba25be2012-11-14 14:18:06 -0800208 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700209 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
210 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700211 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400212 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800213 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400214 except (DownloadError, ManifestInvalidRevisionError,
David Pursehouseabdf7502020-02-12 14:58:39 +0900215 NoManifestException) as e:
Dan Sandler53e902a2014-03-09 13:20:02 -0400216 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
David Pursehouseabdf7502020-02-12 14:58:39 +0900217 file=sys.stderr)
Dan Sandler53e902a2014-03-09 13:20:02 -0400218 if isinstance(e, NoManifestException):
219 print('error: manifest missing or unreadable -- please run init',
220 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800221 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700222 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700223 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700224 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700225 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700226 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800227 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700228 except InvalidProjectGroupsError as e:
229 if e.name:
230 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
231 else:
David Pursehouse3cda50a2020-02-13 13:17:03 +0900232 print('error: project group must be enabled for the project in the current directory',
233 file=sys.stderr)
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700234 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700235 except SystemExit as e:
236 if e.code:
237 result = e.code
238 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800239 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700240 finish = time.time()
241 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800242 hours, remainder = divmod(elapsed, 3600)
243 minutes, seconds = divmod(remainder, 60)
244 if gopts.time:
245 if hours == 0:
246 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
247 else:
248 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
249 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400250
David Rileye0684ad2017-04-05 00:02:59 -0700251 cmd.event_log.FinishEvent(cmd_event, finish,
252 result is None or result == 0)
253 if gopts.event_log:
254 cmd.event_log.Write(os.path.abspath(
255 os.path.expanduser(gopts.event_log)))
256
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400257 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258
Conley Owens094cdbe2014-01-30 15:09:59 -0800259
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500260def _CheckWrapperVersion(ver_str, repo_path):
261 """Verify the repo launcher is new enough for this checkout.
262
263 Args:
264 ver_str: The version string passed from the repo launcher when it ran us.
265 repo_path: The path to the repo launcher that loaded us.
266 """
267 # Refuse to work with really old wrapper versions. We don't test these,
268 # so might as well require a somewhat recent sane version.
269 # v1.15 of the repo launcher was released in ~Mar 2012.
270 MIN_REPO_VERSION = (1, 15)
271 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
272
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700273 if not repo_path:
274 repo_path = '~/bin/repo'
275
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500276 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700277 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900278 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500280 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800281 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500282 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700283
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900284 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500285 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700286 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500287repo: error:
288!!! Your version of repo %s is too old.
289!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900290!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500291!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700292
293 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500294""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700295 sys.exit(1)
296
297 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700298 print("""
David Pursehouse3c5114c2020-02-13 09:55:59 +0900299... A new version of repo (%s) is available.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700300... You should upgrade soon:
301
302 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800303""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700304
David Pursehouse819827a2020-02-12 15:20:19 +0900305
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200306def _CheckRepoDir(repo_dir):
307 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700308 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900309 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700310
David Pursehouse819827a2020-02-12 15:20:19 +0900311
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700312def _PruneOptions(argv, opt):
313 i = 0
314 while i < len(argv):
315 a = argv[i]
316 if a == '--':
317 break
318 if a.startswith('--'):
319 eq = a.find('=')
320 if eq > 0:
321 a = a[0:eq]
322 if not opt.has_option(a):
323 del argv[i]
324 continue
325 i += 1
326
David Pursehouse819827a2020-02-12 15:20:19 +0900327
Sarah Owens1f7627f2012-10-31 09:21:55 -0700328class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700329 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400330 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700331 return req
332
333 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400334 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700335 return req
336
David Pursehouse819827a2020-02-12 15:20:19 +0900337
JoonCheol Parke9860722012-10-11 02:31:44 +0900338def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900339 # If repo could not find auth info from netrc, try to get it from user input
340 url = req.get_full_url()
341 user, password = handler.passwd.find_user_password(None, url)
342 if user is None:
343 print(msg)
344 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530345 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900346 password = getpass.getpass()
347 except KeyboardInterrupt:
348 return
349 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900350
David Pursehouse819827a2020-02-12 15:20:19 +0900351
Sarah Owens1f7627f2012-10-31 09:21:55 -0700352class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900353 def http_error_401(self, req, fp, code, msg, headers):
354 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700355 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900356 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900357
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700358 def http_error_auth_reqed(self, authreq, host, req, headers):
359 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700360 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900361
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700362 def _add_header(name, val):
363 val = val.replace('\n', '')
364 old_add_header(name, val)
365 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700366 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900367 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900368 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700369 reset = getattr(self, 'reset_retry_count', None)
370 if reset is not None:
371 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700372 elif getattr(self, 'retried', None):
373 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700374 raise
375
David Pursehouse819827a2020-02-12 15:20:19 +0900376
Sarah Owens1f7627f2012-10-31 09:21:55 -0700377class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900378 def http_error_401(self, req, fp, code, msg, headers):
379 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700380 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900381 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900382
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800383 def http_error_auth_reqed(self, auth_header, host, req, headers):
384 try:
385 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900386
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800387 def _add_header(name, val):
388 val = val.replace('\n', '')
389 old_add_header(name, val)
390 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700391 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900392 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900393 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800394 reset = getattr(self, 'reset_retry_count', None)
395 if reset is not None:
396 reset()
397 elif getattr(self, 'retried', None):
398 self.retried = 0
399 raise
400
David Pursehouse819827a2020-02-12 15:20:19 +0900401
Carlos Aguado1242e602014-02-03 13:48:47 +0100402class _KerberosAuthHandler(urllib.request.BaseHandler):
403 def __init__(self):
404 self.retried = 0
405 self.context = None
406 self.handler_order = urllib.request.BaseHandler.handler_order - 50
407
David Pursehouse65b0ba52018-06-24 16:21:51 +0900408 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100409 host = req.get_host()
410 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
411 return retry
412
413 def http_error_auth_reqed(self, auth_header, host, req, headers):
414 try:
415 spn = "HTTP@%s" % host
416 authdata = self._negotiate_get_authdata(auth_header, headers)
417
418 if self.retried > 3:
419 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900420 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100421 else:
422 self.retried += 1
423
424 neghdr = self._negotiate_get_svctk(spn, authdata)
425 if neghdr is None:
426 return None
427
428 req.add_unredirected_header('Authorization', neghdr)
429 response = self.parent.open(req)
430
431 srvauth = self._negotiate_get_authdata(auth_header, response.info())
432 if self._validate_response(srvauth):
433 return response
434 except kerberos.GSSError:
435 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900436 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100437 self.reset_retry_count()
438 raise
439 finally:
440 self._clean_context()
441
442 def reset_retry_count(self):
443 self.retried = 0
444
445 def _negotiate_get_authdata(self, auth_header, headers):
446 authhdr = headers.get(auth_header, None)
447 if authhdr is not None:
448 for mech_tuple in authhdr.split(","):
449 mech, __, authdata = mech_tuple.strip().partition(" ")
450 if mech.lower() == "negotiate":
451 return authdata.strip()
452 return None
453
454 def _negotiate_get_svctk(self, spn, authdata):
455 if authdata is None:
456 return None
457
458 result, self.context = kerberos.authGSSClientInit(spn)
459 if result < kerberos.AUTH_GSS_COMPLETE:
460 return None
461
462 result = kerberos.authGSSClientStep(self.context, authdata)
463 if result < kerberos.AUTH_GSS_CONTINUE:
464 return None
465
466 response = kerberos.authGSSClientResponse(self.context)
467 return "Negotiate %s" % response
468
469 def _validate_response(self, authdata):
470 if authdata is None:
471 return None
472 result = kerberos.authGSSClientStep(self.context, authdata)
473 if result == kerberos.AUTH_GSS_COMPLETE:
474 return True
475 return None
476
477 def _clean_context(self):
478 if self.context is not None:
479 kerberos.authGSSClientClean(self.context)
480 self.context = None
481
David Pursehouse819827a2020-02-12 15:20:19 +0900482
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700483def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700484 handlers = [_UserAgentHandler()]
485
Sarah Owens1f7627f2012-10-31 09:21:55 -0700486 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700487 try:
488 n = netrc.netrc()
489 for host in n.hosts:
490 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900491 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800492 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700493 except netrc.NetrcParseError:
494 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700495 except IOError:
496 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700497 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800498 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100499 if kerberos:
500 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700501
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700502 if 'http_proxy' in os.environ:
503 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700504 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700505 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700506 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
507 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
508 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700509
David Pursehouse819827a2020-02-12 15:20:19 +0900510
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700511def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400512 result = 0
513
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700514 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
515 opt.add_option("--repo-dir", dest="repodir",
516 help="path to .repo/")
517 opt.add_option("--wrapper-version", dest="wrapper_version",
518 help="version of the wrapper script")
519 opt.add_option("--wrapper-path", dest="wrapper_path",
520 help="location of the wrapper script")
521 _PruneOptions(argv, opt)
522 opt, argv = opt.parse_args(argv)
523
524 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
525 _CheckRepoDir(opt.repodir)
526
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800527 Version.wrapper_version = opt.wrapper_version
528 Version.wrapper_path = opt.wrapper_path
529
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700530 repo = _Repo(opt.repodir)
531 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700532 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800533 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700534 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400535 name, gopts, argv = repo._ParseArgs(argv)
536 run = lambda: repo._Run(name, gopts, argv) or 0
537 if gopts.trace_python:
538 import trace
539 tracer = trace.Trace(count=False, trace=True, timing=True,
540 ignoredirs=set(sys.path[1:]))
541 result = tracer.runfunc(run)
542 else:
543 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700544 finally:
545 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700546 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700547 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400548 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900549 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700550 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900551 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700552 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800553 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700554 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800555 argv = list(sys.argv)
556 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700557 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800558 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700559 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700560 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
561 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400562 result = 128
563
Renaud Paquaye8595e92016-11-01 15:51:59 -0700564 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400565 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700566
David Pursehouse819827a2020-02-12 15:20:19 +0900567
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700568if __name__ == '__main__':
569 _Main(sys.argv[1:])