blob: 889fc21615aeecc131862e548e8952d1e02f0fe6 [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:
Conley Owens7ba25be2012-11-14 14:18:06 -0800200 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400201 except (DownloadError, ManifestInvalidRevisionError,
202 NoManifestException) as e:
203 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
204 file=sys.stderr)
205 if isinstance(e, NoManifestException):
206 print('error: manifest missing or unreadable -- please run init',
207 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800208 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700209 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700210 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700211 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700212 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700213 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800214 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700215 except InvalidProjectGroupsError as e:
216 if e.name:
217 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
218 else:
219 print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
220 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700221 except SystemExit as e:
222 if e.code:
223 result = e.code
224 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800225 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700226 finish = time.time()
227 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800228 hours, remainder = divmod(elapsed, 3600)
229 minutes, seconds = divmod(remainder, 60)
230 if gopts.time:
231 if hours == 0:
232 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
233 else:
234 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
235 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400236
David Rileye0684ad2017-04-05 00:02:59 -0700237 cmd.event_log.FinishEvent(cmd_event, finish,
238 result is None or result == 0)
239 if gopts.event_log:
240 cmd.event_log.Write(os.path.abspath(
241 os.path.expanduser(gopts.event_log)))
242
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400243 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700244
Conley Owens094cdbe2014-01-30 15:09:59 -0800245
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700246def _MyRepoPath():
247 return os.path.dirname(__file__)
248
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700249
250def _CheckWrapperVersion(ver, repo_path):
251 if not repo_path:
252 repo_path = '~/bin/repo'
253
254 if not ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700255 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900256 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257
Conley Owens094cdbe2014-01-30 15:09:59 -0800258 exp = Wrapper().VERSION
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900259 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700260 if len(ver) == 1:
261 ver = (0, ver[0])
262
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900263 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700264 if exp[0] > ver[0] or ver < (0, 4):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700265 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700266!!! A new repo command (%5s) is available. !!!
267!!! You must upgrade before you can continue: !!!
268
269 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800270""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700271 sys.exit(1)
272
273 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700274 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700275... A new repo command (%5s) is available.
276... You should upgrade soon:
277
278 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800279""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700280
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200281def _CheckRepoDir(repo_dir):
282 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700283 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900284 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700285
286def _PruneOptions(argv, opt):
287 i = 0
288 while i < len(argv):
289 a = argv[i]
290 if a == '--':
291 break
292 if a.startswith('--'):
293 eq = a.find('=')
294 if eq > 0:
295 a = a[0:eq]
296 if not opt.has_option(a):
297 del argv[i]
298 continue
299 i += 1
300
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700301_user_agent = None
302
303def _UserAgent():
304 global _user_agent
305
306 if _user_agent is None:
307 py_version = sys.version_info
308
309 os_name = sys.platform
310 if os_name == 'linux2':
311 os_name = 'Linux'
312 elif os_name == 'win32':
313 os_name = 'Win32'
314 elif os_name == 'cygwin':
315 os_name = 'Cygwin'
316 elif os_name == 'darwin':
317 os_name = 'Darwin'
318
319 p = GitCommand(
320 None, ['describe', 'HEAD'],
321 cwd = _MyRepoPath(),
322 capture_stdout = True)
323 if p.Wait() == 0:
324 repo_version = p.stdout
325 if len(repo_version) > 0 and repo_version[-1] == '\n':
326 repo_version = repo_version[0:-1]
327 if len(repo_version) > 0 and repo_version[0] == 'v':
328 repo_version = repo_version[1:]
329 else:
330 repo_version = 'unknown'
331
332 _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
333 repo_version,
334 os_name,
Mike Frysinger242fcdd2019-07-10 15:45:49 -0400335 git.version_tuple().full,
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700336 py_version[0], py_version[1], py_version[2])
337 return _user_agent
338
Sarah Owens1f7627f2012-10-31 09:21:55 -0700339class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700340 def http_request(self, req):
341 req.add_header('User-Agent', _UserAgent())
342 return req
343
344 def https_request(self, req):
345 req.add_header('User-Agent', _UserAgent())
346 return req
347
JoonCheol Parke9860722012-10-11 02:31:44 +0900348def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900349 # If repo could not find auth info from netrc, try to get it from user input
350 url = req.get_full_url()
351 user, password = handler.passwd.find_user_password(None, url)
352 if user is None:
353 print(msg)
354 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530355 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900356 password = getpass.getpass()
357 except KeyboardInterrupt:
358 return
359 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900360
Sarah Owens1f7627f2012-10-31 09:21:55 -0700361class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900362 def http_error_401(self, req, fp, code, msg, headers):
363 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700364 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900365 self, req, fp, code, msg, headers)
366
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700367 def http_error_auth_reqed(self, authreq, host, req, headers):
368 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700369 old_add_header = req.add_header
370 def _add_header(name, val):
371 val = val.replace('\n', '')
372 old_add_header(name, val)
373 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700374 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700375 self, authreq, host, req, headers)
376 except:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700377 reset = getattr(self, 'reset_retry_count', None)
378 if reset is not None:
379 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700380 elif getattr(self, 'retried', None):
381 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700382 raise
383
Sarah Owens1f7627f2012-10-31 09:21:55 -0700384class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900385 def http_error_401(self, req, fp, code, msg, headers):
386 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700387 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900388 self, req, fp, code, msg, headers)
389
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800390 def http_error_auth_reqed(self, auth_header, host, req, headers):
391 try:
392 old_add_header = req.add_header
393 def _add_header(name, val):
394 val = val.replace('\n', '')
395 old_add_header(name, val)
396 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700397 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800398 self, auth_header, host, req, headers)
399 except:
400 reset = getattr(self, 'reset_retry_count', None)
401 if reset is not None:
402 reset()
403 elif getattr(self, 'retried', None):
404 self.retried = 0
405 raise
406
Carlos Aguado1242e602014-02-03 13:48:47 +0100407class _KerberosAuthHandler(urllib.request.BaseHandler):
408 def __init__(self):
409 self.retried = 0
410 self.context = None
411 self.handler_order = urllib.request.BaseHandler.handler_order - 50
412
David Pursehouse65b0ba52018-06-24 16:21:51 +0900413 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100414 host = req.get_host()
415 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
416 return retry
417
418 def http_error_auth_reqed(self, auth_header, host, req, headers):
419 try:
420 spn = "HTTP@%s" % host
421 authdata = self._negotiate_get_authdata(auth_header, headers)
422
423 if self.retried > 3:
424 raise urllib.request.HTTPError(req.get_full_url(), 401,
425 "Negotiate auth failed", headers, None)
426 else:
427 self.retried += 1
428
429 neghdr = self._negotiate_get_svctk(spn, authdata)
430 if neghdr is None:
431 return None
432
433 req.add_unredirected_header('Authorization', neghdr)
434 response = self.parent.open(req)
435
436 srvauth = self._negotiate_get_authdata(auth_header, response.info())
437 if self._validate_response(srvauth):
438 return response
439 except kerberos.GSSError:
440 return None
441 except:
442 self.reset_retry_count()
443 raise
444 finally:
445 self._clean_context()
446
447 def reset_retry_count(self):
448 self.retried = 0
449
450 def _negotiate_get_authdata(self, auth_header, headers):
451 authhdr = headers.get(auth_header, None)
452 if authhdr is not None:
453 for mech_tuple in authhdr.split(","):
454 mech, __, authdata = mech_tuple.strip().partition(" ")
455 if mech.lower() == "negotiate":
456 return authdata.strip()
457 return None
458
459 def _negotiate_get_svctk(self, spn, authdata):
460 if authdata is None:
461 return None
462
463 result, self.context = kerberos.authGSSClientInit(spn)
464 if result < kerberos.AUTH_GSS_COMPLETE:
465 return None
466
467 result = kerberos.authGSSClientStep(self.context, authdata)
468 if result < kerberos.AUTH_GSS_CONTINUE:
469 return None
470
471 response = kerberos.authGSSClientResponse(self.context)
472 return "Negotiate %s" % response
473
474 def _validate_response(self, authdata):
475 if authdata is None:
476 return None
477 result = kerberos.authGSSClientStep(self.context, authdata)
478 if result == kerberos.AUTH_GSS_COMPLETE:
479 return True
480 return None
481
482 def _clean_context(self):
483 if self.context is not None:
484 kerberos.authGSSClientClean(self.context)
485 self.context = None
486
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700487def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700488 handlers = [_UserAgentHandler()]
489
Sarah Owens1f7627f2012-10-31 09:21:55 -0700490 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700491 try:
492 n = netrc.netrc()
493 for host in n.hosts:
494 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800495 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
496 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700497 except netrc.NetrcParseError:
498 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700499 except IOError:
500 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700501 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800502 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100503 if kerberos:
504 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700505
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700506 if 'http_proxy' in os.environ:
507 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700508 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700509 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700510 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
511 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
512 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700513
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700514def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400515 result = 0
516
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700517 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
518 opt.add_option("--repo-dir", dest="repodir",
519 help="path to .repo/")
520 opt.add_option("--wrapper-version", dest="wrapper_version",
521 help="version of the wrapper script")
522 opt.add_option("--wrapper-path", dest="wrapper_path",
523 help="location of the wrapper script")
524 _PruneOptions(argv, opt)
525 opt, argv = opt.parse_args(argv)
526
527 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
528 _CheckRepoDir(opt.repodir)
529
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800530 Version.wrapper_version = opt.wrapper_version
531 Version.wrapper_path = opt.wrapper_path
532
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700533 repo = _Repo(opt.repodir)
534 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700535 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800536 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700537 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400538 name, gopts, argv = repo._ParseArgs(argv)
539 run = lambda: repo._Run(name, gopts, argv) or 0
540 if gopts.trace_python:
541 import trace
542 tracer = trace.Trace(count=False, trace=True, timing=True,
543 ignoredirs=set(sys.path[1:]))
544 result = tracer.runfunc(run)
545 else:
546 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700547 finally:
548 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700549 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700550 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400551 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900552 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700553 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900554 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700555 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800556 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700557 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800558 argv = list(sys.argv)
559 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700560 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800561 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700562 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700563 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
564 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400565 result = 128
566
Renaud Paquaye8595e92016-11-01 15:51:59 -0700567 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400568 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700569
570if __name__ == '__main__':
571 _Main(sys.argv[1:])