blob: 35023d52d0e257c81a275e17a74ae07045d7e92f [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)')
Shawn O. Pearce3a0e7822011-09-22 17:06:41 -070088global_options.add_option('--time',
89 dest='time', action='store_true',
90 help='time repo command execution')
Shawn O. Pearce47c1a632009-03-02 18:24:23 -080091global_options.add_option('--version',
92 dest='show_version', action='store_true',
93 help='display this version of repo')
David Rileye0684ad2017-04-05 00:02:59 -070094global_options.add_option('--event-log',
95 dest='event_log', action='store',
96 help='filename of event log to append timeline to')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070097
98class _Repo(object):
99 def __init__(self, repodir):
100 self.repodir = repodir
101 self.commands = all_commands
Mike Lockwood2bf9db02009-07-14 15:23:39 -0400102 # add 'branch' as an alias for 'branches'
103 all_commands['branch'] = all_commands['branches']
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700104
105 def _Run(self, argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400106 result = 0
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700107 name = None
108 glob = []
109
Sarah Owensa6053d52012-11-01 13:36:50 -0700110 for i in range(len(argv)):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700111 if not argv[i].startswith('-'):
112 name = argv[i]
113 if i > 0:
114 glob = argv[:i]
115 argv = argv[i + 1:]
116 break
117 if not name:
118 glob = argv
119 name = 'help'
120 argv = []
David Pursehouse8a68ff92012-09-24 12:15:13 +0900121 gopts, _gargs = global_options.parse_args(glob)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700122
Shawn O. Pearce0ed2bd12009-03-09 18:26:31 -0700123 if gopts.trace:
Shawn O. Pearcead3193a2009-04-18 09:54:51 -0700124 SetTrace()
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800125 if gopts.show_version:
126 if name == 'help':
127 name = 'version'
128 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700129 print('fatal: invalid usage of --version', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400130 return 1
Shawn O. Pearce47c1a632009-03-02 18:24:23 -0800131
Mike Frysinger902665b2014-12-22 15:17:59 -0500132 SetDefaultColoring(gopts.color)
133
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700134 try:
135 cmd = self.commands[name]
136 except KeyError:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700137 print("repo: '%s' is not a repo command. See 'repo help'." % name,
138 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400139 return 1
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700140
141 cmd.repodir = self.repodir
Shawn O. Pearcec8a300f2009-05-18 13:19:57 -0700142 cmd.manifest = XmlManifest(cmd.repodir)
Simran Basib9a1b732015-08-20 12:19:28 -0700143 cmd.gitc_manifest = None
144 gitc_client_name = gitc_utils.parse_clientdir(os.getcwd())
145 if gitc_client_name:
146 cmd.gitc_manifest = GitcManifest(cmd.repodir, gitc_client_name)
147 cmd.manifest.isGitcClient = True
148
Shawn O. Pearce7965f9f2008-10-29 15:20:02 -0700149 Editor.globalConfig = cmd.manifest.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700150
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800151 if not isinstance(cmd, MirrorSafeCommand) and cmd.manifest.IsMirror:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700152 print("fatal: '%s' requires a working directory" % name,
153 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400154 return 1
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800155
Dan Willemsen79360642015-08-31 15:45:06 -0700156 if isinstance(cmd, GitcAvailableCommand) and not gitc_utils.get_gitc_manifest_dir():
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700157 print("fatal: '%s' requires GITC to be available" % name,
158 file=sys.stderr)
159 return 1
160
Dan Willemsen79360642015-08-31 15:45:06 -0700161 if isinstance(cmd, GitcClientCommand) and not gitc_client_name:
162 print("fatal: '%s' requires a GITC client" % name,
163 file=sys.stderr)
164 return 1
165
Dan Sandler53e902a2014-03-09 13:20:02 -0400166 try:
167 copts, cargs = cmd.OptionParser.parse_args(argv)
168 copts = cmd.ReadEnvironmentOptions(copts)
169 except NoManifestException as e:
170 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
171 file=sys.stderr)
172 print('error: manifest missing or unreadable -- please run init',
173 file=sys.stderr)
174 return 1
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700175
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700176 if not gopts.no_pager and not isinstance(cmd, InteractiveCommand):
177 config = cmd.manifest.globalConfig
178 if gopts.pager:
179 use_pager = True
180 else:
181 use_pager = config.GetBoolean('pager.%s' % name)
182 if use_pager is None:
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700183 use_pager = cmd.WantPager(copts)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700184 if use_pager:
185 RunPager(config)
186
Conley Owens7ba25be2012-11-14 14:18:06 -0800187 start = time.time()
David Rileye0684ad2017-04-05 00:02:59 -0700188 cmd_event = cmd.event_log.Add(name, event_log.TASK_COMMAND, start)
189 cmd.event_log.SetParent(cmd_event)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700190 try:
Conley Owens7ba25be2012-11-14 14:18:06 -0800191 result = cmd.Execute(copts, cargs)
Dan Sandler53e902a2014-03-09 13:20:02 -0400192 except (DownloadError, ManifestInvalidRevisionError,
193 NoManifestException) as e:
194 print('error: in `%s`: %s' % (' '.join([name] + argv), str(e)),
195 file=sys.stderr)
196 if isinstance(e, NoManifestException):
197 print('error: manifest missing or unreadable -- please run init',
198 file=sys.stderr)
Conley Owens75ee0572012-11-15 17:33:11 -0800199 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700200 except NoSuchProjectError as e:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700201 if e.name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700202 print('error: project %s not found' % e.name, file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700203 else:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700204 print('error: no project in current directory', file=sys.stderr)
Conley Owens7ba25be2012-11-14 14:18:06 -0800205 result = 1
Jarkko Pöyry87ea5912015-06-19 15:39:25 -0700206 except InvalidProjectGroupsError as e:
207 if e.name:
208 print('error: project group must be enabled for project %s' % e.name, file=sys.stderr)
209 else:
210 print('error: project group must be enabled for the project in the current directory', file=sys.stderr)
211 result = 1
David Rileyaa900212017-04-05 13:50:52 -0700212 except SystemExit as e:
213 if e.code:
214 result = e.code
215 raise
Conley Owens7ba25be2012-11-14 14:18:06 -0800216 finally:
David Rileye0684ad2017-04-05 00:02:59 -0700217 finish = time.time()
218 elapsed = finish - start
Conley Owens7ba25be2012-11-14 14:18:06 -0800219 hours, remainder = divmod(elapsed, 3600)
220 minutes, seconds = divmod(remainder, 60)
221 if gopts.time:
222 if hours == 0:
223 print('real\t%dm%.3fs' % (minutes, seconds), file=sys.stderr)
224 else:
225 print('real\t%dh%dm%.3fs' % (hours, minutes, seconds),
226 file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400227
David Rileye0684ad2017-04-05 00:02:59 -0700228 cmd.event_log.FinishEvent(cmd_event, finish,
229 result is None or result == 0)
230 if gopts.event_log:
231 cmd.event_log.Write(os.path.abspath(
232 os.path.expanduser(gopts.event_log)))
233
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400234 return result
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700235
Conley Owens094cdbe2014-01-30 15:09:59 -0800236
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700237def _MyRepoPath():
238 return os.path.dirname(__file__)
239
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700240
241def _CheckWrapperVersion(ver, repo_path):
242 if not repo_path:
243 repo_path = '~/bin/repo'
244
245 if not ver:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700246 print('no --wrapper-version argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900247 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700248
Conley Owens094cdbe2014-01-30 15:09:59 -0800249 exp = Wrapper().VERSION
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900250 ver = tuple(map(int, ver.split('.')))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700251 if len(ver) == 1:
252 ver = (0, ver[0])
253
David Pursehouse7e6dd2d2012-10-25 12:40:51 +0900254 exp_str = '.'.join(map(str, exp))
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700255 if exp[0] > ver[0] or ver < (0, 4):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700256 print("""
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257!!! A new repo command (%5s) is available. !!!
258!!! You must upgrade before you can continue: !!!
259
260 cp %s %s
Conley Owens094cdbe2014-01-30 15:09:59 -0800261""" % (exp_str, WrapperPath(), repo_path), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700262 sys.exit(1)
263
264 if exp > ver:
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 should upgrade soon:
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
Mickaël Salaün2f6ab7f2012-09-30 00:37:55 +0200272def _CheckRepoDir(repo_dir):
273 if not repo_dir:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700274 print('no --repo-dir argument', file=sys.stderr)
David Pursehouse8a68ff92012-09-24 12:15:13 +0900275 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700276
277def _PruneOptions(argv, opt):
278 i = 0
279 while i < len(argv):
280 a = argv[i]
281 if a == '--':
282 break
283 if a.startswith('--'):
284 eq = a.find('=')
285 if eq > 0:
286 a = a[0:eq]
287 if not opt.has_option(a):
288 del argv[i]
289 continue
290 i += 1
291
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700292_user_agent = None
293
294def _UserAgent():
295 global _user_agent
296
297 if _user_agent is None:
298 py_version = sys.version_info
299
300 os_name = sys.platform
301 if os_name == 'linux2':
302 os_name = 'Linux'
303 elif os_name == 'win32':
304 os_name = 'Win32'
305 elif os_name == 'cygwin':
306 os_name = 'Cygwin'
307 elif os_name == 'darwin':
308 os_name = 'Darwin'
309
310 p = GitCommand(
311 None, ['describe', 'HEAD'],
312 cwd = _MyRepoPath(),
313 capture_stdout = True)
314 if p.Wait() == 0:
315 repo_version = p.stdout
316 if len(repo_version) > 0 and repo_version[-1] == '\n':
317 repo_version = repo_version[0:-1]
318 if len(repo_version) > 0 and repo_version[0] == 'v':
319 repo_version = repo_version[1:]
320 else:
321 repo_version = 'unknown'
322
323 _user_agent = 'git-repo/%s (%s) git/%s Python/%d.%d.%d' % (
324 repo_version,
325 os_name,
Mike Frysinger242fcdd2019-07-10 15:45:49 -0400326 git.version_tuple().full,
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700327 py_version[0], py_version[1], py_version[2])
328 return _user_agent
329
Sarah Owens1f7627f2012-10-31 09:21:55 -0700330class _UserAgentHandler(urllib.request.BaseHandler):
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700331 def http_request(self, req):
332 req.add_header('User-Agent', _UserAgent())
333 return req
334
335 def https_request(self, req):
336 req.add_header('User-Agent', _UserAgent())
337 return req
338
JoonCheol Parke9860722012-10-11 02:31:44 +0900339def _AddPasswordFromUserInput(handler, msg, req):
David Pursehousec1b86a22012-11-14 11:36:51 +0900340 # If repo could not find auth info from netrc, try to get it from user input
341 url = req.get_full_url()
342 user, password = handler.passwd.find_user_password(None, url)
343 if user is None:
344 print(msg)
345 try:
Chirayu Desai217ea7d2013-03-01 19:14:38 +0530346 user = input('User: ')
David Pursehousec1b86a22012-11-14 11:36:51 +0900347 password = getpass.getpass()
348 except KeyboardInterrupt:
349 return
350 handler.passwd.add_password(None, url, user, password)
JoonCheol Parke9860722012-10-11 02:31:44 +0900351
Sarah Owens1f7627f2012-10-31 09:21:55 -0700352class _BasicAuthHandler(urllib.request.HTTPBasicAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900353 def http_error_401(self, req, fp, code, msg, headers):
354 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700355 return urllib.request.HTTPBasicAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900356 self, req, fp, code, msg, headers)
357
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700358 def http_error_auth_reqed(self, authreq, host, req, headers):
359 try:
Shawn O. Pearcedf5ee522011-10-11 14:05:21 -0700360 old_add_header = req.add_header
361 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(
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700366 self, authreq, host, req, headers)
367 except:
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
Sarah Owens1f7627f2012-10-31 09:21:55 -0700375class _DigestAuthHandler(urllib.request.HTTPDigestAuthHandler):
JoonCheol Parke9860722012-10-11 02:31:44 +0900376 def http_error_401(self, req, fp, code, msg, headers):
377 _AddPasswordFromUserInput(self, msg, req)
Sarah Owens1f7627f2012-10-31 09:21:55 -0700378 return urllib.request.HTTPDigestAuthHandler.http_error_401(
JoonCheol Parke9860722012-10-11 02:31:44 +0900379 self, req, fp, code, msg, headers)
380
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800381 def http_error_auth_reqed(self, auth_header, host, req, headers):
382 try:
383 old_add_header = req.add_header
384 def _add_header(name, val):
385 val = val.replace('\n', '')
386 old_add_header(name, val)
387 req.add_header = _add_header
Sarah Owens1f7627f2012-10-31 09:21:55 -0700388 return urllib.request.AbstractDigestAuthHandler.http_error_auth_reqed(
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800389 self, auth_header, host, req, headers)
390 except:
391 reset = getattr(self, 'reset_retry_count', None)
392 if reset is not None:
393 reset()
394 elif getattr(self, 'retried', None):
395 self.retried = 0
396 raise
397
Carlos Aguado1242e602014-02-03 13:48:47 +0100398class _KerberosAuthHandler(urllib.request.BaseHandler):
399 def __init__(self):
400 self.retried = 0
401 self.context = None
402 self.handler_order = urllib.request.BaseHandler.handler_order - 50
403
David Pursehouse65b0ba52018-06-24 16:21:51 +0900404 def http_error_401(self, req, fp, code, msg, headers):
Carlos Aguado1242e602014-02-03 13:48:47 +0100405 host = req.get_host()
406 retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
407 return retry
408
409 def http_error_auth_reqed(self, auth_header, host, req, headers):
410 try:
411 spn = "HTTP@%s" % host
412 authdata = self._negotiate_get_authdata(auth_header, headers)
413
414 if self.retried > 3:
415 raise urllib.request.HTTPError(req.get_full_url(), 401,
416 "Negotiate auth failed", headers, None)
417 else:
418 self.retried += 1
419
420 neghdr = self._negotiate_get_svctk(spn, authdata)
421 if neghdr is None:
422 return None
423
424 req.add_unredirected_header('Authorization', neghdr)
425 response = self.parent.open(req)
426
427 srvauth = self._negotiate_get_authdata(auth_header, response.info())
428 if self._validate_response(srvauth):
429 return response
430 except kerberos.GSSError:
431 return None
432 except:
433 self.reset_retry_count()
434 raise
435 finally:
436 self._clean_context()
437
438 def reset_retry_count(self):
439 self.retried = 0
440
441 def _negotiate_get_authdata(self, auth_header, headers):
442 authhdr = headers.get(auth_header, None)
443 if authhdr is not None:
444 for mech_tuple in authhdr.split(","):
445 mech, __, authdata = mech_tuple.strip().partition(" ")
446 if mech.lower() == "negotiate":
447 return authdata.strip()
448 return None
449
450 def _negotiate_get_svctk(self, spn, authdata):
451 if authdata is None:
452 return None
453
454 result, self.context = kerberos.authGSSClientInit(spn)
455 if result < kerberos.AUTH_GSS_COMPLETE:
456 return None
457
458 result = kerberos.authGSSClientStep(self.context, authdata)
459 if result < kerberos.AUTH_GSS_CONTINUE:
460 return None
461
462 response = kerberos.authGSSClientResponse(self.context)
463 return "Negotiate %s" % response
464
465 def _validate_response(self, authdata):
466 if authdata is None:
467 return None
468 result = kerberos.authGSSClientStep(self.context, authdata)
469 if result == kerberos.AUTH_GSS_COMPLETE:
470 return True
471 return None
472
473 def _clean_context(self):
474 if self.context is not None:
475 kerberos.authGSSClientClean(self.context)
476 self.context = None
477
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700478def init_http():
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700479 handlers = [_UserAgentHandler()]
480
Sarah Owens1f7627f2012-10-31 09:21:55 -0700481 mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm()
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700482 try:
483 n = netrc.netrc()
484 for host in n.hosts:
485 p = n.hosts[host]
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800486 mgr.add_password(p[1], 'http://%s/' % host, p[0], p[2])
487 mgr.add_password(p[1], 'https://%s/' % host, p[0], p[2])
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700488 except netrc.NetrcParseError:
489 pass
Shawn O. Pearce7b947de2011-09-23 11:50:31 -0700490 except IOError:
491 pass
Shawn O. Pearcefab96c62011-10-11 12:00:38 -0700492 handlers.append(_BasicAuthHandler(mgr))
Xiaodong Xuae0a36c2012-01-31 11:10:09 +0800493 handlers.append(_DigestAuthHandler(mgr))
Carlos Aguado1242e602014-02-03 13:48:47 +0100494 if kerberos:
495 handlers.append(_KerberosAuthHandler())
Shawn O. Pearcebd0312a2011-09-19 10:04:23 -0700496
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700497 if 'http_proxy' in os.environ:
498 url = os.environ['http_proxy']
Sarah Owens1f7627f2012-10-31 09:21:55 -0700499 handlers.append(urllib.request.ProxyHandler({'http': url, 'https': url}))
Shawn O. Pearce334851e2011-09-19 08:05:31 -0700500 if 'REPO_CURL_VERBOSE' in os.environ:
Sarah Owens1f7627f2012-10-31 09:21:55 -0700501 handlers.append(urllib.request.HTTPHandler(debuglevel=1))
502 handlers.append(urllib.request.HTTPSHandler(debuglevel=1))
503 urllib.request.install_opener(urllib.request.build_opener(*handlers))
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700504
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700505def _Main(argv):
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400506 result = 0
507
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700508 opt = optparse.OptionParser(usage="repo wrapperinfo -- ...")
509 opt.add_option("--repo-dir", dest="repodir",
510 help="path to .repo/")
511 opt.add_option("--wrapper-version", dest="wrapper_version",
512 help="version of the wrapper script")
513 opt.add_option("--wrapper-path", dest="wrapper_path",
514 help="location of the wrapper script")
515 _PruneOptions(argv, opt)
516 opt, argv = opt.parse_args(argv)
517
518 _CheckWrapperVersion(opt.wrapper_version, opt.wrapper_path)
519 _CheckRepoDir(opt.repodir)
520
Shawn O. Pearceecff4f12011-11-29 15:01:33 -0800521 Version.wrapper_version = opt.wrapper_version
522 Version.wrapper_path = opt.wrapper_path
523
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700524 repo = _Repo(opt.repodir)
525 try:
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700526 try:
Doug Anderson0048b692010-12-21 13:39:23 -0800527 init_ssh()
Shawn O. Pearce014d0602011-09-11 12:57:15 -0700528 init_http()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400529 result = repo._Run(argv) or 0
Shawn O. Pearcefb231612009-04-10 18:53:46 -0700530 finally:
531 close_ssh()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700532 except KeyboardInterrupt:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700533 print('aborted by user', file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400534 result = 1
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900535 except ManifestParseError as mpe:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700536 print('fatal: %s' % mpe, file=sys.stderr)
David Pursehouse0b8df7b2012-11-13 09:51:57 +0900537 result = 1
Sarah Owensa5be53f2012-09-09 15:37:57 -0700538 except RepoChangedException as rce:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800539 # If repo changed, re-exec ourselves.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700540 #
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800541 argv = list(sys.argv)
542 argv.extend(rce.extra_args)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700543 try:
Shawn O. Pearcec9ef7442008-11-03 10:32:09 -0800544 os.execv(__file__, argv)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700545 except OSError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700546 print('fatal: cannot restart repo after upgrade', file=sys.stderr)
547 print('fatal: %s' % e, file=sys.stderr)
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400548 result = 128
549
Renaud Paquaye8595e92016-11-01 15:51:59 -0700550 TerminatePager()
Daniel Sandler3ce2a6b2011-04-29 09:59:12 -0400551 sys.exit(result)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700552
553if __name__ == '__main__':
554 _Main(sys.argv[1:])