blob: fead2049ea7f9986a9032c6f625562aec156f910 [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():
Chirayu Desai217ea7d2013-03-01 19:14:38 +053072 input = raw_input
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:
232 print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
233 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700234 except SystemExit as e:
235 if e.code:
236 result = e.code
237 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800238 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700239 finish = time.time()
240 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800241 hours, remainder = divmod(elapsed, 3600)
242 minutes, seconds = divmod(remainder, 60)
243 if gopts.time:
244 if hours == 0:
245 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
246 else:
247 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
248 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400249
David Rileye0684ad2017-04-05 00:02:59 -0700250 cmd.event_log.FinishEvent(cmd_event, finish,
251 result is None or result == 0)
252 if gopts.event_log:
253 cmd.event_log.Write(os.path.abspath(
254 os.path.expanduser(gopts.event_log)))
255
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400256 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257
Conley Owens094cdbe2014-01-30 15:09:59 -0800258
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500259def _CheckWrapperVersion(ver_str, repo_path):
260 """Verify the repo launcher is new enough for this checkout.
261
262 Args:
263 ver_str: The version string passed from the repo launcher when it ran us.
264 repo_path: The path to the repo launcher that loaded us.
265 """
266 # Refuse to work with really old wrapper versions. We don't test these,
267 # so might as well require a somewhat recent sane version.
268 # v1.15 of the repo launcher was released in ~Mar 2012.
269 MIN_REPO_VERSION = (1, 15)
270 min_str = '.'.join(str(x) for x in MIN_REPO_VERSION)
271
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272 if not repo_path:
273 repo_path = '~/bin/repo'
274
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500275 if not ver_str:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700276 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900277 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700278
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500279 # Pull out the version of the repo launcher we know about to compare.
Conley Owens094cdbe2014-01-30 15:09:59 -0800280 exp = Wrapper().VERSION
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500281 ver = tuple(map(int, ver_str.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900283 exp_str = '.'.join(map(str, exp))
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500284 if ver < MIN_REPO_VERSION:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700285 print("""
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500286repo: error:
287!!! Your version of repo %s is too old.
288!!! We need at least version %s.
David Pursehouse7838e382020-02-13 09:54:49 +0900289!!! A new version of repo (%s) is available.
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500290!!! You must upgrade before you can continue:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700291
292 cp %s %s
Mike Frysinger3285e4b2020-02-10 17:34:49 -0500293""" % (ver_str, min_str, exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700294 sys.exit(1)
295
296 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700297 print("""
David Pursehouse3c5114c2020-02-13 09:55:59 +0900298... A new version of repo (%s) is available.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700299... You should upgrade soon:
300
301 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800302""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700303
David Pursehouse819827a2020-02-12 15:20:19 +0900304
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200305def _CheckRepoDir(repo_dir):
306 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700307 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900308 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700309
David Pursehouse819827a2020-02-12 15:20:19 +0900310
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700311def _PruneOptions(argv, opt):
312 i = 0
313 while i < len(argv):
314 a = argv[i]
315 if a == '--':
316 break
317 if a.startswith('--'):
318 eq = a.find('=')
319 if eq > 0:
320 a = a[0:eq]
321 if not opt.has_option(a):
322 del argv[i]
323 continue
324 i += 1
325
David Pursehouse819827a2020-02-12 15:20:19 +0900326
Sarah Owens1f7627f2012-10-31 09:21:55 -0700327class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700328 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400329 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700330 return req
331
332 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400333 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700334 return req
335
David Pursehouse819827a2020-02-12 15:20:19 +0900336
JoonCheol Parke9860722012-10-11 02:31:44 +0900337def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900338 # If repo could not find auth info from netrc, try to get it from user input
339 url = req.get_full_url()
340 user, password = handler.passwd.find_user_password(None, url)
341 if user is None:
342 print(msg)
343 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530344 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900345 password = getpass.getpass()
346 except KeyboardInterrupt:
347 return
348 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900349
David Pursehouse819827a2020-02-12 15:20:19 +0900350
Sarah Owens1f7627f2012-10-31 09:21:55 -0700351class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900352 def http_error_401(self, req, fp, code, msg, headers):
353 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700354 return urllib.request.HTTPBasicAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900355 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900356
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700357 def http_error_auth_reqed(self, authreq, host, req, headers):
358 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700359 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900360
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700361 def _add_header(name, val):
362 val = val.replace('\n', '')
363 old_add_header(name, val)
364 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700365 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900366 self, authreq, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900367 except Exception:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700368 reset = getattr(self, 'reset_retry_count', None)
369 if reset is not None:
370 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700371 elif getattr(self, 'retried', None):
372 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700373 raise
374
David Pursehouse819827a2020-02-12 15:20:19 +0900375
Sarah Owens1f7627f2012-10-31 09:21:55 -0700376class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900377 def http_error_401(self, req, fp, code, msg, headers):
378 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700379 return urllib.request.HTTPDigestAuthHandler.http_error_401(
David Pursehouseabdf7502020-02-12 14:58:39 +0900380 self, req, fp, code, msg, headers)
JoonCheol Parke9860722012-10-11 02:31:44 +0900381
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800382 def http_error_auth_reqed(self, auth_header, host, req, headers):
383 try:
384 old_add_header = req.add_header
David Pursehouse819827a2020-02-12 15:20:19 +0900385
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800386 def _add_header(name, val):
387 val = val.replace('\n', '')
388 old_add_header(name, val)
389 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700390 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
David Pursehouseabdf7502020-02-12 14:58:39 +0900391 self, auth_header, host, req, headers)
David Pursehouse145e35b2020-02-12 15:40:47 +0900392 except Exception:
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800393 reset = getattr(self, 'reset_retry_count', None)
394 if reset is not None:
395 reset()
396 elif getattr(self, 'retried', None):
397 self.retried = 0
398 raise
399
David Pursehouse819827a2020-02-12 15:20:19 +0900400
Carlos Aguado1242e602014-02-03 13:48:47 +0100401class _KerberosAuthHandler(urllib.request.BaseHandler):
402 def __init__(self):
403 self.retried = 0
404 self.context = None
405 self.handler_order = urllib.request.BaseHandler.handler_order - 50
406
David Pursehouse65b0ba52018-06-24 16:21:51 +0900407 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100408 host = req.get_host()
409 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
410 return retry
411
412 def http_error_auth_reqed(self, auth_header, host, req, headers):
413 try:
414 spn = "HTTP@%s" % host
415 authdata = self._negotiate_get_authdata(auth_header, headers)
416
417 if self.retried > 3:
418 raise urllib.request.HTTPError(req.get_full_url(), 401,
David Pursehouseabdf7502020-02-12 14:58:39 +0900419 "Negotiate auth failed", headers, None)
Carlos Aguado1242e602014-02-03 13:48:47 +0100420 else:
421 self.retried += 1
422
423 neghdr = self._negotiate_get_svctk(spn, authdata)
424 if neghdr is None:
425 return None
426
427 req.add_unredirected_header('Authorization', neghdr)
428 response = self.parent.open(req)
429
430 srvauth = self._negotiate_get_authdata(auth_header, response.info())
431 if self._validate_response(srvauth):
432 return response
433 except kerberos.GSSError:
434 return None
David Pursehouse145e35b2020-02-12 15:40:47 +0900435 except Exception:
Carlos Aguado1242e602014-02-03 13:48:47 +0100436 self.reset_retry_count()
437 raise
438 finally:
439 self._clean_context()
440
441 def reset_retry_count(self):
442 self.retried = 0
443
444 def _negotiate_get_authdata(self, auth_header, headers):
445 authhdr = headers.get(auth_header, None)
446 if authhdr is not None:
447 for mech_tuple in authhdr.split(","):
448 mech, __, authdata = mech_tuple.strip().partition(" ")
449 if mech.lower() == "negotiate":
450 return authdata.strip()
451 return None
452
453 def _negotiate_get_svctk(self, spn, authdata):
454 if authdata is None:
455 return None
456
457 result, self.context = kerberos.authGSSClientInit(spn)
458 if result < kerberos.AUTH_GSS_COMPLETE:
459 return None
460
461 result = kerberos.authGSSClientStep(self.context, authdata)
462 if result < kerberos.AUTH_GSS_CONTINUE:
463 return None
464
465 response = kerberos.authGSSClientResponse(self.context)
466 return "Negotiate %s" % response
467
468 def _validate_response(self, authdata):
469 if authdata is None:
470 return None
471 result = kerberos.authGSSClientStep(self.context, authdata)
472 if result == kerberos.AUTH_GSS_COMPLETE:
473 return True
474 return None
475
476 def _clean_context(self):
477 if self.context is not None:
478 kerberos.authGSSClientClean(self.context)
479 self.context = None
480
David Pursehouse819827a2020-02-12 15:20:19 +0900481
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700482def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700483 handlers = [_UserAgentHandler()]
484
Sarah Owens1f7627f2012-10-31 09:21:55 -0700485 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700486 try:
487 n = netrc.netrc()
488 for host in n.hosts:
489 p = n.hosts[host]
David Pursehouse54a4e602020-02-12 14:31:05 +0900490 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800491 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700492 except netrc.NetrcParseError:
493 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700494 except IOError:
495 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700496 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800497 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100498 if kerberos:
499 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700500
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700501 if 'http_proxy' in os.environ:
502 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700503 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700504 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700505 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
506 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
507 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700508
David Pursehouse819827a2020-02-12 15:20:19 +0900509
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700510def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400511 result = 0
512
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700513 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
514 opt.add_option("--repo-dir", dest="repodir",
515 help="path to .repo/")
516 opt.add_option("--wrapper-version", dest="wrapper_version",
517 help="version of the wrapper script")
518 opt.add_option("--wrapper-path", dest="wrapper_path",
519 help="location of the wrapper script")
520 _PruneOptions(argv, opt)
521 opt, argv = opt.parse_args(argv)
522
523 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
524 _CheckRepoDir(opt.repodir)
525
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800526 Version.wrapper_version = opt.wrapper_version
527 Version.wrapper_path = opt.wrapper_path
528
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700529 repo = _Repo(opt.repodir)
530 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700531 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800532 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700533 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400534 name, gopts, argv = repo._ParseArgs(argv)
535 run = lambda: repo._Run(name, gopts, argv) or 0
536 if gopts.trace_python:
537 import trace
538 tracer = trace.Trace(count=False, trace=True, timing=True,
539 ignoredirs=set(sys.path[1:]))
540 result = tracer.runfunc(run)
541 else:
542 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700543 finally:
544 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700545 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700546 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400547 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900548 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700549 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900550 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700551 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800552 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700553 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800554 argv = list(sys.argv)
555 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700556 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800557 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700558 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700559 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
560 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400561 result = 128
562
Renaud Paquaye8595e92016-11-01 15:51:59 -0700563 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400564 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700565
David Pursehouse819827a2020-02-12 15:20:19 +0900566
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700567if __name__ == '__main__':
568 _Main(sys.argv[1:])