blob: 2ab79b5732c31b9aa8144477ccfa60fcf8f6e073 [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
Conley Owensc9129d92012-10-01 16:12:28 -070026import imp
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -070027import netrc
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070028import optparse
29import os
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070030import sys
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:
David Pursehouse59bbb582013-05-17 10:49:33 +090037 import urllib2
Sarah Owens1f7627f2012-10-31 09:21:55 -070038 urllib = imp.new_module('urllib')
39 urllib.request = urllib2
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070040
Carlos Aguado1242e602014-02-03 13:48:47 +010041try:
42 import kerberos
43except ImportError:
44 kerberos = None
45
Mike Frysinger902665b2014-12-22 15:17:59 -050046from color import SetDefaultColoring
David Rileye0684ad2017-04-05 00:02:59 -070047import event_log
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040048from repo_trace import SetTrace
Shawn O. Pearce334851e2011-09-19 08:05:31 -070049from git_command import git, GitCommand
Doug Anderson0048b692010-12-21 13:39:23 -080050from git_config import init_ssh, close_ssh
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080051from command import InteractiveCommand
52from command import MirrorSafeCommand
Dan Willemsen79360642015-08-31 15:45:06 -070053from command import GitcAvailableCommand, GitcClientCommand
Shawn O. Pearceecff4f12011-11-29 15:01:33 -080054from subcmds.version import Version
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -070055from editor import Editor
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070056from error import DownloadError
Jarkko Pöyry87ea5912015-06-19 15:39:25 -070057from error import InvalidProjectGroupsError
Shawn O. Pearce559b8462009-03-02 12:56:08 -080058from error import ManifestInvalidRevisionError
David Pursehouse0b8df7b2012-11-13 09:51:57 +090059from error import ManifestParseError
Conley Owens75ee0572012-11-15 17:33:11 -080060from error import NoManifestException
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070061from error import NoSuchProjectError
62from error import RepoChangedException
Simran Basib9a1b732015-08-20 12:19:28 -070063import gitc_utils
64from manifest_xml import GitcManifest, XmlManifest
Renaud Paquaye8595e92016-11-01 15:51:59 -070065from pager import RunPager, TerminatePager
Conley Owens094cdbe2014-01-30 15:09:59 -080066from wrapper import WrapperPath, Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070067
David Pursehouse5c6eeac2012-10-11 16:44:48 +090068from subcmds import all_commands
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070069
David Pursehouse59bbb582013-05-17 10:49:33 +090070if not is_python3():
Chirayu Desai217ea7d2013-03-01 19:14:38 +053071 input = raw_input
Chirayu Desai217ea7d2013-03-01 19:14:38 +053072
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070073global_options = optparse.OptionParser(
74 usage="repo [-p|--paginate|--no-pager] COMMAND [ARGS]"
75 )
76global_options.add_option('-p', '--paginate',
77 dest='pager', action='store_true',
78 help='display command output in the pager')
79global_options.add_option('--no-pager',
80 dest='no_pager', action='store_true',
81 help='disable the pager')
Mike Frysinger902665b2014-12-22 15:17:59 -050082global_options.add_option('--color',
83 choices=('auto', 'always', 'never'), default=None,
84 help='control color usage: auto, always, never')
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -070085global_options.add_option('--trace',
86 dest='trace', action='store_true',
Mike Frysinger8a11f6f2019-08-27 00:26:15 -040087 help='trace git command execution (REPO_TRACE=1)')
Mike Frysinger3fc15722019-08-27 00:36:46 -040088global_options.add_option('--trace-python',
89 dest='trace_python', action='store_true',
90 help='trace python command execution')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070091global_options.add_option('--time',
92 dest='time', action='store_true',
93 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080094global_options.add_option('--version',
95 dest='show_version', action='store_true',
96 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -070097global_options.add_option('--event-log',
98 dest='event_log', action='store',
99 help='filename of event log to append timeline to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700100
101class _Repo(object):
102 def __init__(self, repodir):
103 self.repodir = repodir
104 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -0400105 # add 'branch' as an alias for 'branches'
106 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700107
Mike Frysinger3fc15722019-08-27 00:36:46 -0400108 def _ParseArgs(self, argv):
109 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110 name = None
111 glob = []
112
Sarah Owensa6053d52012-11-01 13:36:50 -0700113 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700114 if not argv[i].startswith('-'):
115 name = argv[i]
116 if i > 0:
117 glob = argv[:i]
118 argv = argv[i + 1:]
119 break
120 if not name:
121 glob = argv
122 name = 'help'
123 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900124 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700125
Mike Frysinger3fc15722019-08-27 00:36:46 -0400126 return (name, gopts, argv)
127
128 def _Run(self, name, gopts, argv):
129 """Execute the requested subcommand."""
130 result = 0
131
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700132 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700133 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800134 if gopts.show_version:
135 if name == 'help':
136 name = 'version'
137 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700138 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400139 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800140
Mike Frysinger902665b2014-12-22 15:17:59 -0500141 SetDefaultColoring(gopts.color)
142
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700143 try:
144 cmd = self.commands[name]
145 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700146 print("repo: '%s' is not a repo command. See 'repo help'." % name,
147 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400148 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700149
150 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700151 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700152 cmd.gitc_manifest = None
153 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
154 if gitc_client_name:
155 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
156 cmd.manifest.isGitcClient = True
157
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700158 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700159
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800160 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700161 print("fatal: '%s' requires a working directory" % name,
162 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400163 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800164
Dan Willemsen79360642015-08-31 15:45:06 -0700165 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700166 print("fatal: '%s' requires GITC to be available" % name,
167 file=sys.stderr)
168 return 1
169
Dan Willemsen79360642015-08-31 15:45:06 -0700170 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
171 print("fatal: '%s' requires a GITC client" % name,
172 file=sys.stderr)
173 return 1
174
Dan Sandler53e902a2014-03-09 13:20:02 -0400175 try:
176 copts, cargs = cmd.OptionParser.parse_args(argv)
177 copts = cmd.ReadEnvironmentOptions(copts)
178 except NoManifestException as e:
179 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
180 file=sys.stderr)
181 print('error: manifest missing or unreadable -- please run init',
182 file=sys.stderr)
183 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700184
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700185 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
186 config = cmd.manifest.globalConfig
187 if gopts.pager:
188 use_pager = True
189 else:
190 use_pager = config.GetBoolean('pager.%s' % name)
191 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700192 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700193 if use_pager:
194 RunPager(config)
195
Conley Owens7ba25be2012-11-14 14:18:06 -0800196 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700197 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
198 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700199 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400200 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800201 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400202 except (DownloadError, ManifestInvalidRevisionError,
203 NoManifestException) as e:
204 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
205 file=sys.stderr)
206 if isinstance(e, NoManifestException):
207 print('error: manifest missing or unreadable -- please run init',
208 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800209 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700210 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700211 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700212 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700213 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700214 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800215 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700216 except InvalidProjectGroupsError as e:
217 if e.name:
218 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
219 else:
220 print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
221 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700222 except SystemExit as e:
223 if e.code:
224 result = e.code
225 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800226 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700227 finish = time.time()
228 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800229 hours, remainder = divmod(elapsed, 3600)
230 minutes, seconds = divmod(remainder, 60)
231 if gopts.time:
232 if hours == 0:
233 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
234 else:
235 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
236 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400237
David Rileye0684ad2017-04-05 00:02:59 -0700238 cmd.event_log.FinishEvent(cmd_event, finish,
239 result is None or result == 0)
240 if gopts.event_log:
241 cmd.event_log.Write(os.path.abspath(
242 os.path.expanduser(gopts.event_log)))
243
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400244 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700245
Conley Owens094cdbe2014-01-30 15:09:59 -0800246
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700247def _MyRepoPath():
248 return os.path.dirname(__file__)
249
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700250
251def _CheckWrapperVersion(ver, repo_path):
252 if not repo_path:
253 repo_path = '~/bin/repo'
254
255 if not ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700256 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900257 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258
Conley Owens094cdbe2014-01-30 15:09:59 -0800259 exp = Wrapper().VERSION
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900260 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700261 if len(ver) == 1:
262 ver = (0, ver[0])
263
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900264 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265 if exp[0] > ver[0] or ver < (0, 4):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700266 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267!!! A new repo command (%5s) is available. !!!
268!!! You must upgrade before you can continue: !!!
269
270 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800271""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272 sys.exit(1)
273
274 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700275 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700276... A new repo command (%5s) is available.
277... You should upgrade soon:
278
279 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800280""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700281
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200282def _CheckRepoDir(repo_dir):
283 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700284 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900285 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700286
287def _PruneOptions(argv, opt):
288 i = 0
289 while i < len(argv):
290 a = argv[i]
291 if a == '--':
292 break
293 if a.startswith('--'):
294 eq = a.find('=')
295 if eq > 0:
296 a = a[0:eq]
297 if not opt.has_option(a):
298 del argv[i]
299 continue
300 i += 1
301
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700302_user_agent = None
303
304def _UserAgent():
305 global _user_agent
306
307 if _user_agent is None:
308 py_version = sys.version_info
309
310 os_name = sys.platform
311 if os_name == 'linux2':
312 os_name = 'Linux'
313 elif os_name == 'win32':
314 os_name = 'Win32'
315 elif os_name == 'cygwin':
316 os_name = 'Cygwin'
317 elif os_name == 'darwin':
318 os_name = 'Darwin'
319
320 p = GitCommand(
321 None, ['describe', 'HEAD'],
322 cwd = _MyRepoPath(),
323 capture_stdout = True)
324 if p.Wait() == 0:
325 repo_version = p.stdout
326 if len(repo_version) > 0 and repo_version[-1] == '\n':
327 repo_version = repo_version[0:-1]
328 if len(repo_version) > 0 and repo_version[0] == 'v':
329 repo_version = repo_version[1:]
330 else:
331 repo_version = 'unknown'
332
333 _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
334 repo_version,
335 os_name,
Mike Frysinger242fcdd2019-07-10 15:45:49 -0400336 git.version_tuple().full,
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700337 py_version[0], py_version[1], py_version[2])
338 return _user_agent
339
Sarah Owens1f7627f2012-10-31 09:21:55 -0700340class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700341 def http_request(self, req):
342 req.add_header('User-Agent', _UserAgent())
343 return req
344
345 def https_request(self, req):
346 req.add_header('User-Agent', _UserAgent())
347 return req
348
JoonCheol Parke9860722012-10-11 02:31:44 +0900349def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900350 # If repo could not find auth info from netrc, try to get it from user input
351 url = req.get_full_url()
352 user, password = handler.passwd.find_user_password(None, url)
353 if user is None:
354 print(msg)
355 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530356 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900357 password = getpass.getpass()
358 except KeyboardInterrupt:
359 return
360 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900361
Sarah Owens1f7627f2012-10-31 09:21:55 -0700362class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900363 def http_error_401(self, req, fp, code, msg, headers):
364 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700365 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900366 self, req, fp, code, msg, headers)
367
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700368 def http_error_auth_reqed(self, authreq, host, req, headers):
369 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700370 old_add_header = req.add_header
371 def _add_header(name, val):
372 val = val.replace('\n', '')
373 old_add_header(name, val)
374 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700375 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700376 self, authreq, host, req, headers)
377 except:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700378 reset = getattr(self, 'reset_retry_count', None)
379 if reset is not None:
380 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700381 elif getattr(self, 'retried', None):
382 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700383 raise
384
Sarah Owens1f7627f2012-10-31 09:21:55 -0700385class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900386 def http_error_401(self, req, fp, code, msg, headers):
387 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700388 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900389 self, req, fp, code, msg, headers)
390
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800391 def http_error_auth_reqed(self, auth_header, host, req, headers):
392 try:
393 old_add_header = req.add_header
394 def _add_header(name, val):
395 val = val.replace('\n', '')
396 old_add_header(name, val)
397 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700398 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800399 self, auth_header, host, req, headers)
400 except:
401 reset = getattr(self, 'reset_retry_count', None)
402 if reset is not None:
403 reset()
404 elif getattr(self, 'retried', None):
405 self.retried = 0
406 raise
407
Carlos Aguado1242e602014-02-03 13:48:47 +0100408class _KerberosAuthHandler(urllib.request.BaseHandler):
409 def __init__(self):
410 self.retried = 0
411 self.context = None
412 self.handler_order = urllib.request.BaseHandler.handler_order - 50
413
David Pursehouse65b0ba52018-06-24 16:21:51 +0900414 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100415 host = req.get_host()
416 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
417 return retry
418
419 def http_error_auth_reqed(self, auth_header, host, req, headers):
420 try:
421 spn = "HTTP@%s" % host
422 authdata = self._negotiate_get_authdata(auth_header, headers)
423
424 if self.retried > 3:
425 raise urllib.request.HTTPError(req.get_full_url(), 401,
426 "Negotiate auth failed", headers, None)
427 else:
428 self.retried += 1
429
430 neghdr = self._negotiate_get_svctk(spn, authdata)
431 if neghdr is None:
432 return None
433
434 req.add_unredirected_header('Authorization', neghdr)
435 response = self.parent.open(req)
436
437 srvauth = self._negotiate_get_authdata(auth_header, response.info())
438 if self._validate_response(srvauth):
439 return response
440 except kerberos.GSSError:
441 return None
442 except:
443 self.reset_retry_count()
444 raise
445 finally:
446 self._clean_context()
447
448 def reset_retry_count(self):
449 self.retried = 0
450
451 def _negotiate_get_authdata(self, auth_header, headers):
452 authhdr = headers.get(auth_header, None)
453 if authhdr is not None:
454 for mech_tuple in authhdr.split(","):
455 mech, __, authdata = mech_tuple.strip().partition(" ")
456 if mech.lower() == "negotiate":
457 return authdata.strip()
458 return None
459
460 def _negotiate_get_svctk(self, spn, authdata):
461 if authdata is None:
462 return None
463
464 result, self.context = kerberos.authGSSClientInit(spn)
465 if result < kerberos.AUTH_GSS_COMPLETE:
466 return None
467
468 result = kerberos.authGSSClientStep(self.context, authdata)
469 if result < kerberos.AUTH_GSS_CONTINUE:
470 return None
471
472 response = kerberos.authGSSClientResponse(self.context)
473 return "Negotiate %s" % response
474
475 def _validate_response(self, authdata):
476 if authdata is None:
477 return None
478 result = kerberos.authGSSClientStep(self.context, authdata)
479 if result == kerberos.AUTH_GSS_COMPLETE:
480 return True
481 return None
482
483 def _clean_context(self):
484 if self.context is not None:
485 kerberos.authGSSClientClean(self.context)
486 self.context = None
487
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700488def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700489 handlers = [_UserAgentHandler()]
490
Sarah Owens1f7627f2012-10-31 09:21:55 -0700491 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700492 try:
493 n = netrc.netrc()
494 for host in n.hosts:
495 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800496 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
497 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700498 except netrc.NetrcParseError:
499 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700500 except IOError:
501 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700502 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800503 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100504 if kerberos:
505 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700506
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700507 if 'http_proxy' in os.environ:
508 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700509 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700510 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700511 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
512 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
513 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700514
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700515def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400516 result = 0
517
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700518 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
519 opt.add_option("--repo-dir", dest="repodir",
520 help="path to .repo/")
521 opt.add_option("--wrapper-version", dest="wrapper_version",
522 help="version of the wrapper script")
523 opt.add_option("--wrapper-path", dest="wrapper_path",
524 help="location of the wrapper script")
525 _PruneOptions(argv, opt)
526 opt, argv = opt.parse_args(argv)
527
528 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
529 _CheckRepoDir(opt.repodir)
530
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800531 Version.wrapper_version = opt.wrapper_version
532 Version.wrapper_path = opt.wrapper_path
533
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700534 repo = _Repo(opt.repodir)
535 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700536 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800537 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700538 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400539 name, gopts, argv = repo._ParseArgs(argv)
540 run = lambda: repo._Run(name, gopts, argv) or 0
541 if gopts.trace_python:
542 import trace
543 tracer = trace.Trace(count=False, trace=True, timing=True,
544 ignoredirs=set(sys.path[1:]))
545 result = tracer.runfunc(run)
546 else:
547 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700548 finally:
549 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700550 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700551 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400552 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900553 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700554 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900555 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700556 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800557 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700558 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800559 argv = list(sys.argv)
560 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700561 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800562 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700563 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700564 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
565 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400566 result = 128
567
Renaud Paquaye8595e92016-11-01 15:51:59 -0700568 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400569 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700570
571if __name__ == '__main__':
572 _Main(sys.argv[1:])