blob: 16db144fffd876b3eb73de8ad065b3191ebd46b6 [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
Mike Frysinger71b0f312019-09-30 22:39:49 -040050from git_command import git, GitCommand, 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
104class _Repo(object):
105 def __init__(self, repodir):
106 self.repodir = repodir
107 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -0400108 # add 'branch' as an alias for 'branches'
109 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110
Mike Frysinger3fc15722019-08-27 00:36:46 -0400111 def _ParseArgs(self, argv):
112 """Parse the main `repo` command line options."""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700113 name = None
114 glob = []
115
Sarah Owensa6053d52012-11-01 13:36:50 -0700116 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700117 if not argv[i].startswith('-'):
118 name = argv[i]
119 if i > 0:
120 glob = argv[:i]
121 argv = argv[i + 1:]
122 break
123 if not name:
124 glob = argv
125 name = 'help'
126 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900127 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700128
Mike Frysinger7c321f12019-12-02 16:49:44 -0500129 if gopts.help:
130 global_options.print_help()
131 commands = ' '.join(sorted(self.commands))
132 wrapped_commands = textwrap.wrap(commands, width=77)
133 print('\nAvailable commands:\n %s' % ('\n '.join(wrapped_commands),))
134 print('\nRun `repo help <command>` for command-specific details.')
135 global_options.exit()
136
Mike Frysinger3fc15722019-08-27 00:36:46 -0400137 return (name, gopts, argv)
138
139 def _Run(self, name, gopts, argv):
140 """Execute the requested subcommand."""
141 result = 0
142
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700143 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700144 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800145 if gopts.show_version:
146 if name == 'help':
147 name = 'version'
148 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700149 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400150 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800151
Mike Frysinger902665b2014-12-22 15:17:59 -0500152 SetDefaultColoring(gopts.color)
153
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700154 try:
155 cmd = self.commands[name]
156 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700157 print("repo: '%s' is not a repo command. See 'repo help'." % name,
158 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400159 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160
161 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700162 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700163 cmd.gitc_manifest = None
164 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
165 if gitc_client_name:
166 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
167 cmd.manifest.isGitcClient = True
168
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700169 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700170
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800171 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700172 print("fatal: '%s' requires a working directory" % name,
173 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400174 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800175
Dan Willemsen79360642015-08-31 15:45:06 -0700176 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700177 print("fatal: '%s' requires GITC to be available" % name,
178 file=sys.stderr)
179 return 1
180
Dan Willemsen79360642015-08-31 15:45:06 -0700181 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
182 print("fatal: '%s' requires a GITC client" % name,
183 file=sys.stderr)
184 return 1
185
Dan Sandler53e902a2014-03-09 13:20:02 -0400186 try:
187 copts, cargs = cmd.OptionParser.parse_args(argv)
188 copts = cmd.ReadEnvironmentOptions(copts)
189 except NoManifestException as e:
190 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
191 file=sys.stderr)
192 print('error: manifest missing or unreadable -- please run init',
193 file=sys.stderr)
194 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700195
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700196 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
197 config = cmd.manifest.globalConfig
198 if gopts.pager:
199 use_pager = True
200 else:
201 use_pager = config.GetBoolean('pager.%s' % name)
202 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700203 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700204 if use_pager:
205 RunPager(config)
206
Conley Owens7ba25be2012-11-14 14:18:06 -0800207 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700208 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
209 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700210 try:
Mike Frysingerae6cb082019-08-27 01:10:59 -0400211 cmd.ValidateOptions(copts, cargs)
Conley Owens7ba25be2012-11-14 14:18:06 -0800212 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400213 except (DownloadError, ManifestInvalidRevisionError,
214 NoManifestException) as e:
215 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
216 file=sys.stderr)
217 if isinstance(e, NoManifestException):
218 print('error: manifest missing or unreadable -- please run init',
219 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800220 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700221 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700222 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700223 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700224 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700225 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800226 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700227 except InvalidProjectGroupsError as e:
228 if e.name:
229 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
230 else:
231 print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
232 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700233 except SystemExit as e:
234 if e.code:
235 result = e.code
236 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800237 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700238 finish = time.time()
239 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800240 hours, remainder = divmod(elapsed, 3600)
241 minutes, seconds = divmod(remainder, 60)
242 if gopts.time:
243 if hours == 0:
244 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
245 else:
246 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
247 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400248
David Rileye0684ad2017-04-05 00:02:59 -0700249 cmd.event_log.FinishEvent(cmd_event, finish,
250 result is None or result == 0)
251 if gopts.event_log:
252 cmd.event_log.Write(os.path.abspath(
253 os.path.expanduser(gopts.event_log)))
254
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400255 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256
Conley Owens094cdbe2014-01-30 15:09:59 -0800257
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258def _CheckWrapperVersion(ver, repo_path):
259 if not repo_path:
260 repo_path = '~/bin/repo'
261
262 if not ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700263 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900264 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700265
Conley Owens094cdbe2014-01-30 15:09:59 -0800266 exp = Wrapper().VERSION
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900267 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700268 if len(ver) == 1:
269 ver = (0, ver[0])
270
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900271 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700272 if exp[0] > ver[0] or ver < (0, 4):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700273 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700274!!! A new repo command (%5s) is available. !!!
275!!! You must upgrade before you can continue: !!!
276
277 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800278""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700279 sys.exit(1)
280
281 if exp > ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700282 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700283... A new repo command (%5s) is available.
284... You should upgrade soon:
285
286 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800287""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700288
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200289def _CheckRepoDir(repo_dir):
290 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700291 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900292 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700293
294def _PruneOptions(argv, opt):
295 i = 0
296 while i < len(argv):
297 a = argv[i]
298 if a == '--':
299 break
300 if a.startswith('--'):
301 eq = a.find('=')
302 if eq > 0:
303 a = a[0:eq]
304 if not opt.has_option(a):
305 del argv[i]
306 continue
307 i += 1
308
Sarah Owens1f7627f2012-10-31 09:21:55 -0700309class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700310 def http_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400311 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700312 return req
313
314 def https_request(self, req):
Mike Frysinger71b0f312019-09-30 22:39:49 -0400315 req.add_header('User-Agent', user_agent.repo)
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700316 return req
317
JoonCheol Parke9860722012-10-11 02:31:44 +0900318def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900319 # If repo could not find auth info from netrc, try to get it from user input
320 url = req.get_full_url()
321 user, password = handler.passwd.find_user_password(None, url)
322 if user is None:
323 print(msg)
324 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530325 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900326 password = getpass.getpass()
327 except KeyboardInterrupt:
328 return
329 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900330
Sarah Owens1f7627f2012-10-31 09:21:55 -0700331class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900332 def http_error_401(self, req, fp, code, msg, headers):
333 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700334 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900335 self, req, fp, code, msg, headers)
336
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700337 def http_error_auth_reqed(self, authreq, host, req, headers):
338 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700339 old_add_header = req.add_header
340 def _add_header(name, val):
341 val = val.replace('\n', '')
342 old_add_header(name, val)
343 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700344 return urllib.request.AbstractBasicAuthHandler.http_error_auth_reqed(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700345 self, authreq, host, req, headers)
346 except:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700347 reset = getattr(self, 'reset_retry_count', None)
348 if reset is not None:
349 reset()
Shawn O. Pearceb6605392011-10-11 15:58:07 -0700350 elif getattr(self, 'retried', None):
351 self.retried = 0
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700352 raise
353
Sarah Owens1f7627f2012-10-31 09:21:55 -0700354class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900355 def http_error_401(self, req, fp, code, msg, headers):
356 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700357 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900358 self, req, fp, code, msg, headers)
359
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800360 def http_error_auth_reqed(self, auth_header, host, req, headers):
361 try:
362 old_add_header = req.add_header
363 def _add_header(name, val):
364 val = val.replace('\n', '')
365 old_add_header(name, val)
366 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700367 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800368 self, auth_header, host, req, headers)
369 except:
370 reset = getattr(self, 'reset_retry_count', None)
371 if reset is not None:
372 reset()
373 elif getattr(self, 'retried', None):
374 self.retried = 0
375 raise
376
Carlos Aguado1242e602014-02-03 13:48:47 +0100377class _KerberosAuthHandler(urllib.request.BaseHandler):
378 def __init__(self):
379 self.retried = 0
380 self.context = None
381 self.handler_order = urllib.request.BaseHandler.handler_order - 50
382
David Pursehouse65b0ba52018-06-24 16:21:51 +0900383 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100384 host = req.get_host()
385 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
386 return retry
387
388 def http_error_auth_reqed(self, auth_header, host, req, headers):
389 try:
390 spn = "HTTP@%s" % host
391 authdata = self._negotiate_get_authdata(auth_header, headers)
392
393 if self.retried > 3:
394 raise urllib.request.HTTPError(req.get_full_url(), 401,
395 "Negotiate auth failed", headers, None)
396 else:
397 self.retried += 1
398
399 neghdr = self._negotiate_get_svctk(spn, authdata)
400 if neghdr is None:
401 return None
402
403 req.add_unredirected_header('Authorization', neghdr)
404 response = self.parent.open(req)
405
406 srvauth = self._negotiate_get_authdata(auth_header, response.info())
407 if self._validate_response(srvauth):
408 return response
409 except kerberos.GSSError:
410 return None
411 except:
412 self.reset_retry_count()
413 raise
414 finally:
415 self._clean_context()
416
417 def reset_retry_count(self):
418 self.retried = 0
419
420 def _negotiate_get_authdata(self, auth_header, headers):
421 authhdr = headers.get(auth_header, None)
422 if authhdr is not None:
423 for mech_tuple in authhdr.split(","):
424 mech, __, authdata = mech_tuple.strip().partition(" ")
425 if mech.lower() == "negotiate":
426 return authdata.strip()
427 return None
428
429 def _negotiate_get_svctk(self, spn, authdata):
430 if authdata is None:
431 return None
432
433 result, self.context = kerberos.authGSSClientInit(spn)
434 if result < kerberos.AUTH_GSS_COMPLETE:
435 return None
436
437 result = kerberos.authGSSClientStep(self.context, authdata)
438 if result < kerberos.AUTH_GSS_CONTINUE:
439 return None
440
441 response = kerberos.authGSSClientResponse(self.context)
442 return "Negotiate %s" % response
443
444 def _validate_response(self, authdata):
445 if authdata is None:
446 return None
447 result = kerberos.authGSSClientStep(self.context, authdata)
448 if result == kerberos.AUTH_GSS_COMPLETE:
449 return True
450 return None
451
452 def _clean_context(self):
453 if self.context is not None:
454 kerberos.authGSSClientClean(self.context)
455 self.context = None
456
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700457def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700458 handlers = [_UserAgentHandler()]
459
Sarah Owens1f7627f2012-10-31 09:21:55 -0700460 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700461 try:
462 n = netrc.netrc()
463 for host in n.hosts:
464 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800465 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
466 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700467 except netrc.NetrcParseError:
468 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700469 except IOError:
470 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700471 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800472 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100473 if kerberos:
474 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700475
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700476 if 'http_proxy' in os.environ:
477 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700478 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700479 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700480 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
481 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
482 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700483
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700484def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400485 result = 0
486
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700487 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
488 opt.add_option("--repo-dir", dest="repodir",
489 help="path to .repo/")
490 opt.add_option("--wrapper-version", dest="wrapper_version",
491 help="version of the wrapper script")
492 opt.add_option("--wrapper-path", dest="wrapper_path",
493 help="location of the wrapper script")
494 _PruneOptions(argv, opt)
495 opt, argv = opt.parse_args(argv)
496
497 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
498 _CheckRepoDir(opt.repodir)
499
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800500 Version.wrapper_version = opt.wrapper_version
501 Version.wrapper_path = opt.wrapper_path
502
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700503 repo = _Repo(opt.repodir)
504 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700505 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800506 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700507 init_http()
Mike Frysinger3fc15722019-08-27 00:36:46 -0400508 name, gopts, argv = repo._ParseArgs(argv)
509 run = lambda: repo._Run(name, gopts, argv) or 0
510 if gopts.trace_python:
511 import trace
512 tracer = trace.Trace(count=False, trace=True, timing=True,
513 ignoredirs=set(sys.path[1:]))
514 result = tracer.runfunc(run)
515 else:
516 result = run()
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700517 finally:
518 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700519 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700520 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400521 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900522 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700523 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900524 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700525 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800526 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700527 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800528 argv = list(sys.argv)
529 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700530 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800531 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700532 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700533 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
534 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400535 result = 128
536
Renaud Paquaye8595e92016-11-01 15:51:59 -0700537 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400538 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700539
540if __name__ == '__main__':
541 _Main(sys.argv[1:])